code
stringlengths
2
1.05M
(function() { 'use strict'; angular .module('users') .controller('SettingsController', SettingsController); SettingsController.$inject = ['$scope', 'authenticationService', '$translatePartialLoader', '$translate', 'menuService']; function SettingsController ($scope, authenticationService, $translatePartialLoader, $translate, menuService) { var vm = this; vm.user = authenticationService.user; vm.accountMenu = menuService.getMenu('account').items[0]; $translatePartialLoader.addPart('users'); } })();
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2017 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.m.DisplayListItem. sap.ui.define(['jquery.sap.global', './ListItemBase', './library'], function(jQuery, ListItemBase, library) { "use strict"; /** * Constructor for a new DisplayListItem. * * @param {string} [sId] Id for the new control, generated automatically if no id is given * @param {object} [mSettings] Initial settings for the new control * * @class * <code>sap.m.DisplayListItem</code> can be used to represent a label and a value. * @extends sap.m.ListItemBase * * @author SAP SE * @version 1.46.7 * * @constructor * @public * @alias sap.m.DisplayListItem * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var DisplayListItem = ListItemBase.extend("sap.m.DisplayListItem", /** @lends sap.m.DisplayListItem.prototype */ { metadata : { library : "sap.m", properties : { /** * Defines the label of the list item. */ label : {type : "string", group : "Misc", defaultValue : null}, /** * Defines the value of the list item. */ value : {type : "string", group : "Data", defaultValue : null}, /** * Defines the <code>value</code> text directionality with enumerated options. By default, the control inherits text direction from the DOM. * @since 1.28.0 */ valueTextDirection : {type : "sap.ui.core.TextDirection", group : "Appearance", defaultValue : sap.ui.core.TextDirection.Inherit} } }}); DisplayListItem.prototype.getContentAnnouncement = function() { return this.getLabel() + " " + this.getValue(); }; return DisplayListItem; }, /* bExport= */ true);
/* bender-tags: editor */ /* bender-ckeditor-plugins: wysiwygarea,autoid */ // Clean up all instances been created on the page. (function () { 'use strict'; function removeAllInstances() { var allInstances = CKEDITOR.instances; for (var i in allInstances) { CKEDITOR.remove(allInstances[i]); } } bender.test({ setUp: function () { removeAllInstances(); }, 'test it loads with the plugin enabled': function () { CKEDITOR.replace('editor1'); assert.isObject(CKEDITOR.instances.editor1, 'editor instance not found'); } }); })();
Ui.App.extend('KJing.RoomApp', { scroll: undefined, request: undefined, rooms: undefined, constructor: function(config) { var vbox = new Ui.VBox({ margin: 20 }); this.setContent(vbox); vbox.append(new Ui.Text({ text: 'Liste des salles de médiation publiques', fontWeight: 'bold', fontSize: 20 })); vbox.append(new Ui.Text({ text: 'choisissez une salle pour rejoindre la médiation en cours', fontSize: 16 })); this.scroll = new Ui.ScrollingArea({ marginTop: 10 }); vbox.append(this.scroll, true); this.scroll.setContent(new Ui.Text({ text: 'Chargement en cours...', textAlign: 'center', verticalAlign: 'center' })); this.request = new Core.HttpRequest({ method: 'GET', url: '/cloud/map/public' }); this.connect(this.request, 'done', this.onRequestDone); this.connect(this.request, 'error', this.onRequestFails); this.request.send(); }, onRequestFails: function() { this.scroll.setContent(new Ui.Text({ text: 'Problème au chargement...', textAlign: 'center', verticalAlign: 'center' })); }, onRequestDone: function(req) { var res = req.getResponseJSON(); if(res.length <= 0) this.scroll.setContent(new Ui.Text({ text: 'Aucune salle publique pour le moment', textAlign: 'center', verticalAlign: 'center' })); else { this.rooms = new Ui.VBox({ spacing: 10 }); this.scroll.setContent(this.rooms); for(var i = 0; i < res.length; i++) { var button = new Ui.Button({ text: res[i].publicName }); button["KJing.RoomApp.room"] = res[i]; this.rooms.append(button); this.connect(button, 'press', this.onRoomPress); } } }, onRoomPress: function(button) { var room = button["KJing.RoomApp.room"]; var dialog = new Ui.Dialog({ preferredWidth: 350 }); dialog.setTitle('Choisir un pseudo'); dialog.setCancelButton(new Ui.DialogCloseButton()); var connectButton = new Ui.Button({ text: 'Rejoindre', disabled: true }); dialog.setActionButtons([ connectButton ]); var nameField = new Ui.TextField(); dialog.setContent(nameField); this.connect(nameField, 'change', function() { if(nameField.getValue() !== '') connectButton.enable(); else connectButton.disable(); }); this.connect(connectButton, 'press', function() { var location = '/client/'; if(window.location.pathname.indexOf('index-debug.html') != -1) location += 'index-debug.html'; location += '?parent='+encodeURIComponent(room.id)+'&name='+encodeURIComponent(nameField.getValue()); window.location = location; }); dialog.open(); } }); new KJing.RoomApp({ webApp: true, style: { "Ui.Element": { color: "#444444", fontSize: 16, interLine: 1.4 }, "Ui.MenuPopup": { background: "#ffffff", "Ui.Button": { background: new Ui.Color({ r: 1, g: 1, b: 1, a: 0.1 }), backgroundBorder: new Ui.Color({ r: 1, g: 1, b: 1, a: 0.1 }), iconSize: 28, textHeight: 28 }, "Ui.DefaultButton": { borderWidth: 1, background: "#fefefe", backgroundBorder: 'black', iconSize: 16, textHeight: 16 }, "Ui.ActionButton": { showText: false }, "Ui.SegmentBar": { spacing: 7, color: "#ffffff" } }, "Ui.SegmentBar": { spacing: 8, color: "#ffffff" }, "Ui.Dialog": { background: "#ffffff" }, "Ui.DialogTitle": { fontSize: 20, maxLine: 2, interLine: 1 }, "Ui.DialogCloseButton": { background: 'rgba(250,250,250,0)', radius: 0, borderWidth: 0 }, "Ui.ContextBarCloseButton": { textWidth: 5, borderWidth: 0, background: "rgba(250,250,250,0)", foreground: "#ffffff", radius: 0 }, "Ui.Separator": { color: "#999999" }, "Ui.CheckBox": { color: "#444444", focusColor: new Ui.Color({ r: 0.13, g: 0.83, b: 1 }), checkColor: new Ui.Color({ r: 0.03, g: 0.63, b: 0.9 }) }, "Ui.ScrollingArea": { color: "#999999", showScrollbar: false, overScroll: true, radius: 0 }, "Ui.Button": { background: "#fefefe", iconSize: 28, textHeight: 28, padding: 8, spacing: 10, focusBackground: new Ui.Color({ r: 0.13, g: 0.83, b: 1, a: 0.5 }) }, "Ui.TextBgGraphic": { focusBackground: new Ui.Color({ r: 0.13, g: 0.83, b: 1 }) }, "Ui.ActionButton": { iconSize: 28, textHeight: 28, background: new Ui.Color({ r: 1, g: 1, b: 1, a: 0 }), backgroundBorder: new Ui.Color({ r: 1, g: 1, b: 1, a: 0 }), foreground: "#ffffff", radius: 0, borderWidth: 0 }, "Ui.Slider": { foreground: new Ui.Color({ r: 0.03, g: 0.63, b: 0.9 }) }, "Ui.Locator": { color: "#eeeeee", iconSize: 30, spacing: 6 }, "Ui.MenuToolBarButton": { color: new Ui.Color({ r: 0.8, g: 0.8, b: 0.8, a: 0.2 }), iconSize: 28, spacing: 0 }, "Ui.ContextBar": { background: "#00b9f1", "Ui.Element": { color: "#ffffff" } }, "KJing.PosBar": { radius: 0, current: new Ui.Color({ r: 0.03, g: 0.63, b: 0.9 }) }, "KJing.OptionOpenButton": { borderWidth: 0, iconSize: 16, radius: 0, whiteSpace: 'pre-line', background: 'rgba(250,250,250,0)' }, "KJing.ItemView": { orientation: 'vertical', whiteSpace: 'pre-line', textWidth: 100, maxTextWidth: 100, fontSize: 16, interLine: 1, textHeight: 32, iconSize: 64, maxLine: 2, background: new Ui.Color({ r: 1, g: 1, b: 1, a: 0 }), backgroundBorder: new Ui.Color({ r: 1, g: 1, b: 1, a: 0 }), focusBackground: new Ui.Color({ r: 1, g: 1, b: 1, a: 0 }), focusBackgroundBorder: new Ui.Color({r: 0, g: 0.72, b: 0.95 }), selectCheckColor: new Ui.Color({r: 0, g: 0.72, b: 0.95 }), radius: 0, borderWidth: 2 }, "KJing.GroupUserItemView": { roundMode: true }, "KJing.GroupAddUserItemView": { roundMode: true }, "KJing.RightAddGroupItemView": { roundMode: true }, "KJing.RightAddUserItemView": { roundMode: true }, "KJing.RightItemView": { roundMode: true }, "KJing.MenuToolBar": { background: "#6c19ab", "Ui.Button": { background: new Ui.Color({ r: 1, g: 1, b: 1, a: 0.2 }), backgroundBorder: new Ui.Color({ r: 1, g: 1, b: 1, a: 0.3 }), foreground: "#ffffff", focusBackground: new Ui.Color({ r: 0.43, g: 1, b: 1, a: 0.6 }), focusForeground: "#ffffff" }, "Ui.TextBgGraphic": { background: "#ffffff", focusBackground: new Ui.Color({ r: 0.43, g: 1, b: 1, a: 0.6 }) }, "Ui.Entry": { color: "#ffffff" } }, "KJing.NewItem": { background: new Ui.Color({ r: 1, g: 1, b: 1, a: 0 }), backgroundBorder: new Ui.Color({ r: 1, g: 1, b: 1, a: 0 }), focusBackground: new Ui.Color({ r: 1, g: 1, b: 1, a: 0 }), focusBackgroundBorder: new Ui.Color({r: 0, g: 0.72, b: 0.95 }), iconSize: 48, padding: 31, radius: 0, borderWidth: 2 }, "KJing.UserProfilButton": { iconSize: 32 } } });
var _0x89fd = ["maps", "fn", "extend", "length", "ul", "children", "<span class='indicator'>+</span>", "append", "each", "li", "find", ".venus-menu", "<li class='showhide'><span class='title'>Menu</span><span class='icon'><em></em><em></em><em></em><em></em></span></li>", "prepend", "resize", "unbind", "li, a", "hide", "innerWidth", ".venus-menu > li:not(.showhide)", "slide-left", "removeClass", "mouseleave", "zoom-out", "speed", "fadeOut", "stop", "bind", "mouseover", "addClass", "fadeIn", ".venus-menu li", "click", "display", "css", "siblings", "none", "slideDown", "slideUp", "a", ".venus-menu li:not(.showhide)", "show", ".venus-menu > li.showhide", ":hidden", "is", ".venus-menu > li"]; $[_0x89fd[1]][_0x89fd[0]] = function(_0x2091x1) { var _0x2091x2 = { speed: 300 }; $[_0x89fd[2]](_0x2091x2, _0x2091x1); var _0x2091x3 = 0; $(_0x89fd[11])[_0x89fd[10]](_0x89fd[9])[_0x89fd[8]](function() { if ($(this)[_0x89fd[5]](_0x89fd[4])[_0x89fd[3]] > 0) { $(this)[_0x89fd[7]](_0x89fd[6]); }; }); $(_0x89fd[11])[_0x89fd[13]](_0x89fd[12]); _0x2091x4(); $(window)[_0x89fd[14]](function() { _0x2091x4(); }); function _0x2091x4() { $(_0x89fd[11])[_0x89fd[10]](_0x89fd[16])[_0x89fd[15]](); $(_0x89fd[11])[_0x89fd[10]](_0x89fd[4])[_0x89fd[17]](0); if (window[_0x89fd[18]] <= 768) { _0x2091x7(); _0x2091x6(); if (_0x2091x3 == 0) { $(_0x89fd[19])[_0x89fd[17]](0); }; } else { _0x2091x8(); _0x2091x5(); }; }; function _0x2091x5() { $(_0x89fd[11])[_0x89fd[10]](_0x89fd[4])[_0x89fd[21]](_0x89fd[20]); $(_0x89fd[31])[_0x89fd[27]](_0x89fd[28], function() { $(this)[_0x89fd[5]](_0x89fd[4])[_0x89fd[26]](true, true)[_0x89fd[30]](_0x2091x2[_0x89fd[24]])[_0x89fd[29]](_0x89fd[23]); })[_0x89fd[27]](_0x89fd[22], function() { $(this)[_0x89fd[5]](_0x89fd[4])[_0x89fd[26]](true, true)[_0x89fd[25]](_0x2091x2[_0x89fd[24]])[_0x89fd[21]](_0x89fd[23]); }); }; function _0x2091x6() { $(_0x89fd[11])[_0x89fd[10]](_0x89fd[4])[_0x89fd[21]](_0x89fd[23]); $(_0x89fd[40])[_0x89fd[8]](function() { if ($(this)[_0x89fd[5]](_0x89fd[4])[_0x89fd[3]] > 0) { $(this)[_0x89fd[5]](_0x89fd[39])[_0x89fd[27]](_0x89fd[32], function() { if ($(this)[_0x89fd[35]](_0x89fd[4])[_0x89fd[34]](_0x89fd[33]) == _0x89fd[36]) { $(this)[_0x89fd[35]](_0x89fd[4])[_0x89fd[37]](300)[_0x89fd[29]](_0x89fd[20]); _0x2091x3 = 1; } else { $(this)[_0x89fd[35]](_0x89fd[4])[_0x89fd[38]](300)[_0x89fd[21]](_0x89fd[20]); }; }); }; }); }; function _0x2091x7() { $(_0x89fd[42])[_0x89fd[41]](0); $(_0x89fd[42])[_0x89fd[27]](_0x89fd[32], function() { if ($(_0x89fd[45])[_0x89fd[44]](_0x89fd[43])) { $(_0x89fd[45])[_0x89fd[37]](300); _0x2091x3 = 1; } else { $(_0x89fd[19])[_0x89fd[38]](300); $(_0x89fd[42])[_0x89fd[41]](0); _0x2091x3 = 0; }; }); }; function _0x2091x8() { $(_0x89fd[45])[_0x89fd[41]](0); $(_0x89fd[42])[_0x89fd[17]](0); }; }; $(document).ready(function(){ $().maps(); });
var gulp = require("gulp"); var runSeq = require("run-sequence"); var merge = require("merge2"); var typescript = require("typescript"); var dtsGen = require("dts-generator"); var Builder = require("systemjs-builder"); var tsc = require("gulp-typescript"); var sourcemaps = require("gulp-sourcemaps"); var plumber = require("gulp-plumber"); var ngAnnotate = require("gulp-ng-annotate"); var config = require("../config"); var tsProject = tsc.createProject("tsconfig.json", { sortOutput: true, typescript: typescript }); gulp.task("scripts", (cb) => { return runSeq( ["compile:ts", "compile:dts"], cb); }); gulp.task("scripts:rel", (cb) => { return runSeq( "build", "compile:bundle", "scripts:copy-dist", cb); }); gulp.task("compile:ts", () => { var tsResult = gulp.src([config.src.tsd, config.src.ts, `!${config.test.files}`]) .pipe(plumber()) //.pipe(changed(config.dist.appJs, { extension: ".js" })) .pipe(sourcemaps.init()) .pipe(tsc(tsProject)); return merge([ tsResult.js .pipe(ngAnnotate()) .pipe(sourcemaps.write(".")) .pipe(gulp.dest(`${config.artifact}/amd`)), // tsResult.dts // .pipe(gulp.dest(config.artifact)) ]); }); // d.ts generation using dts-generator gulp.task("compile:dts", () => { return dtsGen.generate({ name: `${config.packageName}`, baseDir: `${config.root}/`, files: ["./index.ts", `../${config.src.tsd}`], out: `${config.artifact}/${config.packageName}.d.ts`, main: `${config.packageName}/index`, //externs: ["../angularjs/angular.d.ts"] }, (msg) => { console.log(`Generating ${config.packageName}.d.ts: ${msg}`); }); }); gulp.task("compile:bundle", () => { var builder = new Builder(".", "system.config.js"); return builder .buildStatic(`${config.packageName} - angular`, `${config.output}/amd-bundle/${config.packageName}.js`, { format: "amd", sourceMaps: true }); // return builder // .bundle(`${config.packageName} - angular`, // `${config.output}/${config.packageName}.js`, // { format: "amd", sourceMaps: true }); }); gulp.task("scripts:copy-dist", () => { return gulp.src([`${config.artifact}/**/*`, `!${config.test.output}/**/*`]) .pipe(gulp.dest(config.output)); });
'use strict'; describe('Controller: TimeCtrl', function () { var elm, elm2, $elm, $elm2, scope, scope2, $rootScope, $compile; // load the controller's module beforeEach(module('exampleApp')); // load the templates beforeEach(module('templates')); // Initialize the controller and a mock scope beforeEach(inject(function (_$rootScope_, _$compile_) { // scope = $rootScope.$new(); // dir_scope = $rootScope.$new(); $rootScope = _$rootScope_; $rootScope.current = {}; $rootScope.current.form = {}; $rootScope.current.block = { questions: [{ "body": "When time did that happen?", "type": "time", "options": { 'required': true, 'format': 24, 'increments': 15 } },{ "body": "What was the time of landing?", "type": "time", "options": { 'format': 12, 'increments': 1, 'initial': "12:44 PM" } }] }; scope = $rootScope.$new(); scope2 = $rootScope.$new(); $compile = _$compile_; $elm = angular.element( '<div time' + ' question="current.block.questions[0]"' + ' value="current.value"' + ' control="current.block.answers[0].form">' + '</div>'); $elm2 = angular.element( '<div time' + ' question="current.block.questions[1]"' + ' value="current.value"' + ' control="current.block.answers[1].form">' + '</div>'); //scope = $rootScope; elm = $compile($elm)(scope); elm2 = $compile($elm2)(scope2); scope.$digest(); scope2.$digest(); $rootScope.$apply(); })); it('should be answered if question is required', function(){ var isolated = elm.isolateScope(); isolated.value = 'Please Select a Time'; var is_valid = isolated.internalControl.validate_answer(); expect(is_valid).toBe(false); }); it('does not have to be answered if not required', function(){ var isolated = elm2.isolateScope(); isolated.value = "02:45 AM"; var is_valid = isolated.internalControl.validate_answer(); expect(is_valid).toBe(true); }); });
'use strict'; const path = require('path'); const babylon = require('babylon'); const traverse = require('babel-traverse').default; const babelTypes = require('babel-types'); const generate = require('babel-generator').default; const renderType = require('billund-enums').renderType; /** * 抓取require和exports出来的值,强烈建议和exports plugin一起使用,因为就不用指定default了 * * @param {String} source - 源代码 * @return {Object} - 抓取后的值 */ function extractRequireAndExport(source) { /* 根据源码进行解析成ast树 然后抓取各种情况: 1. var x = require('xxx'); 2. import xxx from 'xxx.js'; 3. module.exports = {}; 4. export default {}; */ const requireMap = {}; const exportMap = {}; const ast = babylon.parse(source); traverse(ast, { CallExpression(nodePath) { const isRequire = nodePath.node.callee && nodePath.node.callee.name === 'require'; if (!isRequire) return; const parentPath = nodePath.findParent((pa) => pa.isVariableDeclarator()); if (!parentPath) return; const key = parentPath.node.id.name; const requireVal = nodePath.node.arguments[0].value; requireMap[key] = requireVal; }, ImportDeclaration(nodePath) { const requireVal = nodePath.source.value; const specifiers = nodePath.specifiers; const isExportDefault = specifiers[0].node.type === 'ImportDefaultSpecifier'; if (!isExportDefault) throw new Error('sorry, for easier use,please use import default specifier'); const key = specifiers[0].node.local.name; requireMap[key] = requireVal; }, MemberExpression(nodePath) { const isModuleExports = nodePath.node.object.name == 'module' && nodePath.node.property.name == 'exports'; if (!isModuleExports) return; const parentPath = nodePath.findParent((pa) => pa.isAssignmentExpression()); const exportsObj = parentPath.node.right; if (!babelTypes.isObjectExpression(exportsObj)) throw new Error('sorry, please exports an object'); const properties = exportsObj.properties || []; properties.forEach((property) => { exportMap[property.key.name] = property.value; }); }, ExportDefaultDeclaration(nodePath) { const properties = nodePath.node.properties || []; properties.forEach((property) => { exportMap[property.key.name] = property.value; }); } }); return { requireMap, exportMap }; } /** * 从properties中抓取name的值 * * @param {Array} properties - 属性队列 * @return {String} */ function extractWidgetNameFromProperties(properties) { const nameProperty = properties.find((property) => { return property.key.name === 'name'; }); if (!nameProperty) return ''; /* 目前只支持export出来的对象中,name对应的value是一个字符串常量 */ const value = nameProperty.value; if (!(babelTypes.isLiteral(value) || babelTypes.isStringLiteral(value))) return ''; return value.value; } /** * 从config的代码中抓取widget的名称 * * @param {String} source - 源代码 * @return {String} */ function extractWidgetName(source) { if (!source) return ''; const ast = babylon.parse(source); let name = ''; traverse(ast, { MemberExpression(nodePath) { const isModuleExports = nodePath.node.object.name == 'module' && nodePath.node.property.name == 'exports'; if (!isModuleExports) return; const parentPath = nodePath.findParent((pa) => pa.isAssignmentExpression()); const exportsObj = parentPath.node.right; if (!babelTypes.isObjectExpression(exportsObj)) throw new Error('sorry, for lego widget cfg please export an object.'); const properties = exportsObj.properties || []; name = extractWidgetNameFromProperties(properties); }, ExportDefaultDeclaration(nodePath) { const properties = nodePath.node.properties || []; name = extractWidgetNameFromProperties(properties); } }); return name; } /** * 在ast中更新模板的信息 * * @param {String} source - 源代码 * @param {Array} properties - 属性ast树 * @param {Object} state - 状态对象 */ function updateTemplateInfo(source, properties, state) { const templateProperty = properties.find((property) => { return property.key.name === 'template'; }); if (!templateProperty) throw new Error('missing template in lego config.'); /* 根据源码解析成ast树,寻找module.exports或者export default中的template,分为以下几种情况 1.是变量情况,目前抛出异常,因为目前还需要解析出模板的类型 2.直接就是path.resolve的情况,那么执行,然后替换为require('./') 3.是'./template.jsx'的字符串情况,那么替换为require('./') */ const value = templateProperty.value; if (babelTypes.isIdentifier(value)) throw new Error(`sorry,we can't parse identifier template value`); let realPath = ''; if (babelTypes.isCallExpression(value)) { realPath = source.substring(value.start, value.end).replace('__dirname', `'${state.dirname}'`); realPath = eval(realPath); } else if (babelTypes.isLiteral(value) || babelTypes.isStringLiteral(value)) { realPath = value.value; } if (!realPath) throw new Error(`sorry,can't resolve template value:${value}`); templateProperty.value = babelTypes.callExpression(babelTypes.identifier('require'), [babelTypes.stringLiteral(realPath)]); /* 解析模板类型(目前利用文件后缀名来进行解析,目前限制只有react|vue两种),并且加入properties */ const extname = path.extname(realPath); if (!(extname && extname.length > 1)) throw new Error(`sorry,can't resolve template type. templatePath:${realPath}`); let type = renderType.RENDER_TYPE_REACT; const suffix = extname.substring(1); if (suffix === 'vue' || suffix === 'vjsx') { type = renderType.RENDER_TYPE_VUE; } const typeKey = babelTypes.identifier('renderType'); const typeValue = babelTypes.numericLiteral(type); properties.push(babelTypes.objectProperty(typeKey, typeValue)); } /** * 在ast中更新store的信息 * * @param {String} source - 源代码 * @param {Array} properties - 属性ast树 * @param {Object} state - 状态对象 */ function updateStoreConfig(source, properties, state) { const storeProperty = properties.find((property) => { return property.key.name === 'storeConfig'; }); if (!storeProperty) return; /* 根据源码解析成ast树,寻找module.exports或者export default中的template,分为以下几种情况 1.是变量情况,不做处理直接返回 2.直接就是path.resolve的情况,那么执行,然后替换为require('./') 3.是'./template.jsx'的字符串情况,那么替换为require('./') */ const value = storeProperty.value; if (babelTypes.isIdentifier(value)) return; let realPath = ''; if (babelTypes.isCallExpression(value)) { realPath = source.substring(value.start, value.end).replace('__dirname', `'${state.dirname}'`); realPath = eval(realPath); } else if (babelTypes.isLiteral(value) || babelTypes.isStringLiteral(value)) { realPath = value.value; } if (!realPath) throw new Error(`sorry,can't resolve template value:${value}`); storeProperty.value = babelTypes.callExpression(babelTypes.identifier('require'), [babelTypes.stringLiteral(realPath)]); } /** * 修正配置中的模板信息 * * @param {String} source - 源代码 * @param {Object} state - 状态对象,有如下几个字段: * { * dirname: [String], // 对应文件所在的文件夹名称 * } * @return {String} */ function correctTemplate(source, state) { const ast = babylon.parse(source); traverse(ast, { MemberExpression(nodePath) { const isModuleExports = nodePath.node.object.name == 'module' && nodePath.node.property.name == 'exports'; if (!isModuleExports) return; const parentPath = nodePath.findParent((pa) => pa.isAssignmentExpression()); const exportsObj = parentPath.node.right; if (!babelTypes.isObjectExpression(exportsObj)) throw new Error('sorry, please exports an object'); const properties = exportsObj.properties || []; updateTemplateInfo(source, properties, state); }, ExportDefaultDeclaration(nodePath) { const properties = nodePath.node.properties || []; updateTemplateInfo(source, properties, state); } }); return generate(ast, {}).code; } /** * 修正配置中的模板信息 * * @param {String} source - 源代码 * @param {Object} state - 状态对象,有如下几个字段: * { * dirname: [String], // 对应文件所在的文件夹名称 * } * @return {String} */ function correctStoreConfig(source, state) { const ast = babylon.parse(source); traverse(ast, { MemberExpression(nodePath) { const isModuleExports = nodePath.node.object.name == 'module' && nodePath.node.property.name == 'exports'; if (!isModuleExports) return; const parentPath = nodePath.findParent((pa) => pa.isAssignmentExpression()); const exportsObj = parentPath.node.right; if (!babelTypes.isObjectExpression(exportsObj)) throw new Error('sorry, please exports an object'); const properties = exportsObj.properties || []; updateStoreConfig(source, properties, state); }, ExportDefaultDeclaration(nodePath) { const properties = nodePath.node.properties || []; updateStoreConfig(source, properties, state); } }); return generate(ast, {}).code; } module.exports = { extractRequireAndExport, extractWidgetName, correctTemplate, correctStoreConfig };
var express = require('express'); var router = express.Router(); var PracticeService = require('../services/practiceService'); var PracticeItem = require('../models/practiceItem'); /* GET list of practice items meta data */ router.get('/practiceItems', function(req, res, next) { PracticeService.getItemList(function(err, items) { if(err) return next(err); res.status(200).json(items); }); }); /* GET practice item by id */ router.get('/practiceItems/:itemId', function(req, res, next) { PracticeService.getItemById(req.params.itemId, function(err, item) { if(err) return next(err); res.status(200).json(item); }); }); /* DELETE practice item by id */ router.delete('/practiceItems/:itemId', function(req, res, next) { // don't actually delete right now just in case PracticeService.updateItem(req.params.itemId, 'markDelete', true, function(err) { if(err) return next(err); res.status(200).json({ message: 'Item successfully updated'}); }); }); /* PUT update to existing item */ router.put('/practiceItems/:itemId/:field', function (req, res, next) { var field = req.params.field; var itemId = req.params.itemId; var value = req.body.value; PracticeService.updateItem(itemId, field, value, function(err) { if(err) return next(err); res.status(200).json({ message: 'Item successfully updated'}); }); }); //TODO: move service logic /* POST new practice item */ router.post('/practiceItems', function (req, res, next) { var item = req.body; // just create an item, no validation yet var practiceItem = new PracticeItem({ title: item.title || '', artist: item.artist || '', progress: item.progress || 0, lastPlayed: null, playCount: 0, mediaId: item.mediaId, tabData: item.tabData, lyricData: item.lyricData }); practiceItem.save(function(err) { if(err) { return next(err); } // echo back on success for now res.status(200).json(practiceItem); }) }); /* POST new session */ router.post('/practiceItems/:itemId/sessions', function (req, res, next) { PracticeService.saveNewSession(req.params.itemId, req.body.evaluation, function(err) { if(err) return next(err); res.status(200).json({ message: 'Session saved!'}); }); }); module.exports = router;
import { combineReducers } from 'redux'; import NewsFeedReducer from './NewsFeedReducer'; import MarsFeedReducer from './MarsFeedReducer'; import PictureOfDayReducer from './PictureOfDayReducer'; const rootReducer = combineReducers({ newsFeed: NewsFeedReducer, marsFeed: MarsFeedReducer, picturesFeed: PictureOfDayReducer, }); export default rootReducer;
/* * Rejewski * * Copyright 2014 Jason Gerfen * All rights reserved. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. */ var crypto = require('./crypto') , tools = require('./tools'); /** * @object handshake * Handshake encapsulation/decapsulation */ module.exports = { /** * @function set * Alias for create() * * @param {String} key Key to use for HMAC * @param {String} pt The payload (encrypted format) * @param {String} nonce An optional nonce associated with current handshake * @param {String} pkey An optional Private key for signature * @param {Function} cb Callback * * @returns {Function} */ set: function(key, pt, nonce, pkey, cb){ var timestamp = tools.timestamp() , digest = false , payload = false , signature = false , ct = false; nonce = nonce || crypto.pseudo(); try { if (typeof pt == 'object') { pt = JSON.stringify(pt); } if (256 > pt.length) { var pad = crypto.pseudo(256); pt = pt+'::'+pad; } crypto.encrypt(key, pt, false, false, function hsSet(err, enc){ if (err) cb(true); ct = enc; }); crypto.digest(key, ct, false, false, function hsSet(err, hmac){ if (err) cb(true); digest = hmac; }); this.create(timestamp, nonce, digest, ct, function hsSet(err, pld){ if (err) cb(true); payload = pld; }); if (pkey){ crypto.sign(pkey, payload, false, false, function hsSet(err, sig){ if (err) cb(true); signature = sig; }); } else { crypto.hash(payload, false, false, function hsSet(err, hash){ if (err) cb(true); signature = hash; }); } } catch(e) { console.log('handshake.set -> '+e); cb(true); } cb(null, { payload: payload, signature: signature }); }, /** * @function get * Alias for extract() * * @param {String} key Key/passphrase used for encryption of payload * @param {String} payload Payload to be extracted, decrypted & checksummed * @param {Integer} skew The clock skew used for timestamp verification * @param {String} pkey Optional private key to verify signature * @param {Function} cb Callback * * @returns {Function} */ get: function(key, payload, skew, pkey, cb){ var timestamp = (Number(tools.timestamp()) - skew) , signature = false , digest = false , obj = false , pt = false; try { if (pkey){ if (pkey != true) { crypto.verify(pkey, payload.payload, payload.signature, false, false, function hsGet(err, sig){ if (err) cb(true); if (sig != true) { console.log('handshake.get() -> Could not verify RSA signature'); cb(true); } }); } } else { crypto.hash(payload.payload, false, false, function hsGet(err, hash){ if (err) cb(true); signature = hash; }); if (signature != payload.signature){ console.log('handshake.get() -> Could not verify signature'); cb(true); } } this.extract(payload.payload, function hsGet(err, data){ if (err) cb(true); if (!data.payload || !data.digest || !data.nonce || !data.timestamp) { cb(true); } obj = data; }); if ((Number(obj.timestamp) - timestamp) > skew) { console.log('handshake.get() -> Clockskew too great'); cb(true); } crypto.digest(key, obj.payload, false, false, function hsSet(err, hmac){ if (err) cb(true); digest = hmac; }); if (digest != obj.digest) { console.log('handshake.get() -> Could not verify digest '); cb(true); } crypto.decrypt(key, obj.payload, false, false, false, function hsGet(err, p){ if (err) cb(true); pt = /::/.test(p) ? p.split('::')[0] : p; }); } catch(e) { console.log('handshake.get() -> '+e); cb(true); } return cb(null, { payload: pt, digest: obj.digest, nonce: obj.nonce, timestamp: obj.timestamp }); }, /** * @function create * Wrapper for creating an encapsulated payload containing * a timestamp, an nonce, a MAC digest & payload * * @param {String} timestamp An EPOCH * @param {String} nonce Forward secrecy random number * @param {String} digest The MAC digest of payload * @param {String} payload The payload of communication * * @returns {Function} */ create: function(timestamp, nonce, digest, payload, cb){ var one = this.encapsulate(nonce, timestamp) , two = this.encapsulate(digest, one) , three = this.encapsulate(payload, two); if (!three) return cb(false); return cb(null, three); }, /** * @function extract * Wrapper for extracting an encapsulated payload * * @param {String} payload The encapsulated payload * * @returns {Object} */ extract: function(payload, cb) { var one = this.decapsulate(payload) , two = this.decapsulate(one.digest) , three = this.decapsulate(two.digest); if (!one.payload || !two.payload || !three.payload || !three.digest) { cb(false); } return cb(null, { payload: one.payload, digest: two.payload, nonce: three.payload, timestamp: three.digest }); }, /** * @function encapsulate * Creates encapsulated payaload * * @param {String} payload The payload to be used * @param {String} digest The digest to be used * * @returns {String} */ encapsulate: function(payload, digest) { var a = [] , b = digest.split('') , ret = []; do { a.push(payload.substring(0, 2)) } while((payload = payload.substring(2, payload.length))); for (var n = 0; n < a.length; n++) { if (b[n] && a[n]) { ret.push(a[n]+b[n]); } else if(b[n] && !a[n]) { ret.push(b[n]); } else if(!b[n] && a[n]) { ret.push(a[n]); } } return ret.join('')+'/'+digest.length; }, /** * @function decapsulate * Decapsulates payload into an object * * @param {String} payload The payload to be used * * @returns {Object} */ decapsulate: function(payload) { try { var r = new RegExp('.{1, 3}', 'g') , i = /\/(\d+)$/g.exec(payload) , s = payload.replace(/\/\d+$/g, '') , c = s.match(/(.){1,3}/g) , d = [] , p = [] , x = 0; } catch(e) { return false; } for (var n = 0; n < i[1]; n++) { if (c[n]) d.push(c[n].substr(2, c[n].length)) } c.forEach(function(item) { if (item) { if (x < i[1]) { p.push(item.substr(0, item.length - 1)); } else { p.push(item); } x++; } }); return { digest: d.join(''), payload: p.join('') } }, /** * @function verify * Verify's payload with associated HMAC * * @param {Object} opts System configuration object * @param {Object} obj Object containing a secret & key * @param {String} payload The payload to be used * @param {Object} digest Object containing HMAC & signature * @param {Integer} ts The timestamp of associated payload * * @returns {Boolean} */ verify: function(opts, obj, payload, digest, ts){ if (Number(ts) < Number(tools.timestamp() - opts.clockskew)){ return false; } if (obj.key && digest.sig){ if (digest.sig != crypto.verify(obj.key, payload)){ return false; } } if (obj.secret && digest.hmac){ if (digest.hmac != crypto.digest(obj.secret, payload)){ return false; } } return true; } };
/* 6 sectors * 512 lines * 60 vertices, t=threads, m=stamps jetstream t: 1 m: 10 ms: 15651 jetstream t: 2 m: 10 ms: 9348 jetstream t: 3 m: 10 ms: 8583 jetstream t: 4 m: 10 ms: 7969 jetstream t: 5 m: 10 ms: 7891 jetstream t: 6 m: 10 ms: 8037 jetstream t: 7 m: 10 ms: 7981 jetstream t: 8 m: 10 ms: 8594 jetstream t: 9 m: 10 ms: 9060 jetstream t: 10 m: 10 ms: 8797 */ if( typeof importScripts === 'function') { const PI = Math.PI, TAU = 2 * PI, PI2 = PI / 2, RADIUS = 1.0, DEGRAD = PI / 180.0 ; var name = 'jet.worker', cfg, topics, doe, pool, datagrams = { ugrdprs: null, vgrdprs: null }, prelines = null, // pos, wid, col per sector multilines = null, // lines per sector sectors = null // with attributes per sector ; function vec3toLat (v, radius) {return 90 - (Math.acos(v.y / radius)) * 180 / PI;} function vec3toLon (v, radius) {return ((270 + (Math.atan2(v.x , v.z)) * 180 / PI) % 360);} function vector3ToLatLong (v, radius) { return { lat: 90 - (Math.acos(v.y / radius)) * 180 / Math.PI, lon: ((270 + (Math.atan2(v.x , v.z)) * 180 / Math.PI) % 360) }; } function latLonRadToVector3 (lat, lon, radius) { var phi = lat * Math.PI / 180; var theta = (lon - 180) * Math.PI / 180; var x = -radius * Math.cos(phi) * Math.cos(theta); var y = radius * Math.sin(phi); var z = radius * Math.cos(phi) * Math.sin(theta); return new Vector3(x, y, z); } function filterPool (sector, amount) { var i, j = 0, coord, out = [], len = pool.length; for (i=0; j<amount && i<len; i++) { coord = pool[i]; if ( coord.lat < sector[0] && coord.lon > sector[1] && coord.lat > sector[2] && coord.lon < sector[3] ) { out.push(coord); j += 1; } } return out; } function onmessage (event) { var id = event.data.id, topic = event.data.topic, payload = event.data.payload, callback = function (id, result, transferables) { postMessage({id, result}, transferables); } ; if (topics[topic]) { topics[topic](id, payload, callback); } else { console.warn(name + ': unknown topic', topic); } } topics = { importScripts: function (id, payload, callback) { importScripts.apply(null, payload.scripts); callback(id, null); }, retrieve: function (id, payload, callback) { var datagramm; cfg = payload.cfg; doe = payload.doe; pool = payload.pool; RES.load({ urls: payload.urls, onFinish: function (err, responses) { if (err) { throw err } else { responses.forEach(function (response) { datagramm = new SIM.Datagram(response.data); datagrams[datagramm.vari] = datagramm; }); topics.prepare(id, payload, function () { topics.process(id, payload, function () { topics.combine(id, payload, function (id, result, transferables) { callback(id, result, transferables) }); }); }); } }}); }, prepare: function (id, payload, callback) { var t0 = Date.now(), i, j, u, v, speed, width, pool, lat, lon, color, vec3, seeds, positions, widths, colors, seeds, sat = 0.4, spcl = new Spherical(), length = cfg.length, amount = NaN, filler = () => [], counter = (a, b) => a + b.positions.length ; // over sectors prelines = cfg.sim.sectors.map( sector => { seeds = []; pool = filterPool(sector, cfg.amount); amount = pool.length; positions = new Array(amount).fill(0).map(filler); colors = new Array(amount).fill(0).map(filler); widths = new Array(amount).fill(0).map(filler); // over lines for (i=0; i<amount; i++) { lat = pool[i].lat; lon = pool[i].lon; vec3 = latLonRadToVector3(lat, lon, cfg.radius); // keep start point seeds.push(vec3.x, vec3.y, vec3.z); // over vertices for (j=0; j<length; j++) { u = datagrams.ugrdprs.linearXY(doe, lat, lon); v = datagrams.vgrdprs.linearXY(doe, lat, lon); speed = Math.hypot(u, v); u /= Math.cos(lat * DEGRAD); color = new Color().setHSL(cfg.hue, sat, speed / 100); width = H.clampScale(speed, 0, 50, 0.5, 2.0); positions[i].push(vec3); colors[i].push(color); widths[i].push(width); spcl.setFromVector3(vec3); spcl.theta += u * cfg.factor; // east-direction spcl.phi -= v * cfg.factor; // north-direction vec3 = vec3.setFromSpherical(spcl).clone(); lat = vec3toLat(vec3, cfg.radius); lon = vec3toLon(vec3, cfg.radius); } } return { seeds: new Float32Array(seeds), positions, colors, widths }; }); // debugger; // console.log(name + ': prepare', id, Date.now() - t0, prelines.reduce(counter, 0)); callback(id, {}, []) }, process: function (id, payload, callback) { var t0 = Date.now(), counter = (a, b) => a + b.length ; multilines = prelines.map(preline => { var idx = 0, multiline = H.zip( preline.positions, preline.colors, preline.widths, (vectors, colors, widths) => new Multiline(idx++, vectors, colors, widths) ) ; multiline.seeds = preline.seeds; return multiline; }); // debugger; // console.log(name + ': process', id, Date.now() - t0, multilines.reduce(counter, 0)); callback(id, {}, []); }, combine: function (id, payload, callback) { var transferables, attributeTypes = { colors: Float32Array, index: Uint16Array, lineIndex: Float32Array, next: Float32Array, position: Float32Array, previous: Float32Array, side: Float32Array, width: Float32Array, }, textures = { u: datagrams.ugrdprs.data[doe], v: datagrams.vgrdprs.data[doe], } ; // debugger; // over sectors (n=6) sectors = multilines.map( lines => { var length, attributes = {}, uniforms = { seeds: lines.seeds } ; delete lines.seeds; // prepare attributes H.each(attributeTypes, (name, type) => { length = lines[0].attributes[name].length * lines.length; attributes[name] = new type(length); }); // over attributes (n=8) H.each(attributeTypes, (name) => { // debugger; // if (name === 'seeds') { return; } var i, source, length, pointer = 0, indexOffset = 0, positLength = lines[0].attributes['position'].length / 3, target = attributes[name] ; // over lines (n=512) H.each(lines, (_, line) => { source = line.attributes[name]; length = source.length; if (name === 'index'){ for (i=0; i<length; i++) { target[pointer + i] = source[i] + indexOffset; } } else if (name !== 'seeds') { for (i=0; i<length; i++) { target[pointer + i] = source[i]; } } pointer += length; indexOffset += positLength; }); }); return { attributes, uniforms }; }); // finish transferables transferables = [textures.u.buffer, textures.v.buffer]; H.each(sectors, (_, sector) => { transferables.push(sector.uniforms.seeds.buffer); H.each(attributeTypes, (name) => { transferables.push(sector.attributes[name].buffer); }); }); // TODO: check edge + transferable callback(id, {sectors, textures}, transferables); } }; } function Multiline ( idx, vertices, colors, widths ) { this.idx = idx; this.index = []; this.lineIndex = []; this.next = []; this.positions = []; this.previous = []; this.side = []; this.widths = []; this.colors = []; this.length = vertices.length; this.init(vertices, colors, widths); this.process(); // TODO: Needed? ~15% faster this.attributes = { index: new Uint16Array( this.index ), lineIndex: new Float32Array( this.lineIndex ), next: new Float32Array( this.next ), position: new Float32Array( this.positions ), previous: new Float32Array( this.previous ), side: new Float32Array( this.side ), width: new Float32Array( this.widths ), colors: new Float32Array( this.colors ), } }; Multiline.prototype = { constructor: Multiline, compareV3: function( a, b ) { var aa = a * 6, ab = b * 6; return ( ( this.positions[ aa ] === this.positions[ ab ] ) && ( this.positions[ aa + 1 ] === this.positions[ ab + 1 ] ) && ( this.positions[ aa + 2 ] === this.positions[ ab + 2 ] ) ); }, copyV3: function( a ) { var aa = a * 6; return [ this.positions[ aa ], this.positions[ aa + 1 ], this.positions[ aa + 2 ] ]; }, init: function( vertices, colors, widths ) { var j, ver, cnt, col, wid, n, len = this.length; for( j = 0; j < len; j++ ) { ver = vertices[ j ]; col = colors[ j ]; wid = widths[ j ]; cnt = j / vertices.length; this.positions.push( ver.x, ver.y, ver.z ); this.positions.push( ver.x, ver.y, ver.z ); this.lineIndex.push(this.idx + cnt); this.lineIndex.push(this.idx + cnt); this.colors.push(col.r, col.g, col.b); this.colors.push(col.r, col.g, col.b); this.widths.push(wid); this.widths.push(wid); this.side.push( 1 ); this.side.push( -1 ); } for( j = 0; j < len - 1; j++ ) { n = j + j; this.index.push( n, n + 1, n + 2 ); this.index.push( n + 2, n + 1, n + 3 ); } }, process: function() { var j, v, l = this.positions.length / 6; v = this.compareV3( 0, l - 1 ) ? this.copyV3( l - 2 ) : this.copyV3( 0 ) ; this.previous.push( v[ 0 ], v[ 1 ], v[ 2 ] ); this.previous.push( v[ 0 ], v[ 1 ], v[ 2 ] ); for( j = 0; j < l - 1; j++ ) { v = this.copyV3( j ); this.previous.push( v[ 0 ], v[ 1 ], v[ 2 ] ); this.previous.push( v[ 0 ], v[ 1 ], v[ 2 ] ); } for( j = 1; j < l; j++ ) { v = this.copyV3( j ); this.next.push( v[ 0 ], v[ 1 ], v[ 2 ] ); this.next.push( v[ 0 ], v[ 1 ], v[ 2 ] ); } v = this.compareV3( l - 1, 0 ) ? this.copyV3( 1 ) : this.copyV3( l - 1 ) ; this.next.push( v[ 0 ], v[ 1 ], v[ 2 ] ); this.next.push( v[ 0 ], v[ 1 ], v[ 2 ] ); } };
/*!* * \file MAVTKLoader.js * \author mrdoob, Bill Hill * \date June 2015 * \version $Id$ * \brief A VTK file loader for three.js. This is based on the VTK * loader by mrdoob. Differences (so far) from the original * are: * * slightly more flexible parsing * * polygons are optional and polygons other than triangles * are not supported * * able to set color of materials attached to geometry * * bounding box and sphere set */ THREE.VTKLoader = function(manager) { this.manager = (manager !== undefined)? manager: THREE.DefaultLoadingManager; }; THREE.VTKLoader.prototype = { constructor: THREE.VTKLoader, load: function(url, onLoad, onProgress, onError) { var scope = this; var loader = new THREE.XHRLoader(scope.manager); loader.setCrossOrigin(this.crossOrigin); var req = loader.load(url, function (text) { onLoad(scope.parse(text)); }, onProgress, onError); return(req); }, parse: function(data) { var idx, pattern, reg_index, result; var line = 0, n_points = 0, n_polys = 0; n_dpp = 0; var colors; var geometry = new THREE.Geometry(); /* * expects to find a legacy format vtk file, such as: * # vtk DataFile Version 1.0 * Some comment text * ASCII * DATASET POLYDATA * POINTS 4 float * 0 0 0 * 100 0 0 * 50 87 0 * 50 43 87 * POLYGONS 4 16 * 3 0 1 2 * 3 0 1 3 * 3 1 2 3 * 3 2 0 3 */ // # vtk DataFile Version <uint>.<uint> pattern = /#[\s]+vtk[\s]+DataFile[\s]+Version[\s]+\d+\.\d+/gi; result = pattern.exec(data); if(result) { // Some comment text ++line; // ASCII ++line; reg_index = pattern.lastIndex; pattern = /ASCII/g; pattern.lastIndex = reg_index; result = pattern.exec(data); } if(result) { // DATASET POLYDATA ++line; reg_index = pattern.lastIndex; pattern = /DATASET[\s]+POLYDATA/g; pattern.lastIndex = reg_index; result = pattern.exec(data); } if(result) { // POINTS 4 float ++line; pattern = /POINTS[\s]+([1-9]+[\d]*)[\s]+float/g; pattern.lastIndex = reg_index; if((result = pattern.exec(data)) !== null) { n_points = parseInt(result[1]); } } if(n_points > 0) { // <float> <float> <float> reg_index = pattern.lastIndex; pattern = /(([+-]?[\d]+[.]?[\d\+\-eE]*)[\s]+([+-]?[\d]+[.]?[\d\+\-eE]*)[\s]+([+-]?[\d]+[.]?[\d\+\-eE]*))/g; pattern.lastIndex = reg_index; for(idx = 0; idx < n_points; ++idx) { ++line; result = pattern.exec(data); if(!result) { break; } geometry.vertices.push( new THREE.Vector3(parseFloat(result[2]), parseFloat(result[3]), parseFloat(result[4]))); } } if((n_points > 0) && result) { // POLYGONS <uint> <uint> or LINES <uint> <uint> ++line; pattern = /(POLYGONS)[\s]+([1-9]+[\d]*)[\s]+([1-9]+[\d]*)/g; if((result = pattern.exec(data)) !== null) { if(result[1] === 'POLYGONS') { n_polys = parseInt(result[2]); var n_poly_points = parseInt(result[3]); n_dpp = n_poly_points / n_polys; } else { result = null; } } else { result = true; // Allow just points, no polygons or lines } } if((n_points > 0) && result) { if(n_polys > 0) { if(n_dpp === 4) { // 3 <uint> <uint> <uint> var reg_index = pattern.lastIndex; pattern = /3[\s]+([\d]+)[\s]+([\d]+)[\s]+([\d]+)/g; pattern.lastIndex = reg_index; for(idx = 0; idx < n_polys; ++idx) { ++line; if((result = pattern.exec(data)) === null) { break; } geometry.faces.push( new THREE.Face3(parseInt(result[1]), parseInt(result[2]), parseInt(result[3]))); } } else if(n_dpp === 5) { // 4 <uint> <uint> <uint> <uint> var reg_index = pattern.lastIndex; pattern = /4[\s]+([\d]+)[\s]+([\d]+)[\s]+([\d]+)[\s]+([\d]+)/g; pattern.lastIndex = reg_index; for(idx = 0; idx < n_polys; ++idx) { ++line; if((result = pattern.exec(data)) === null) { break; } geometry.faces.push( new THREE.Face3(parseInt(result[1]), parseInt(result[2]), parseInt(result[4]))); geometry.faces.push( new THREE.Face3(parseInt(result[2]), parseInt(result[3]), parseInt(result[4]))); } } } } if(result === null) { geometry = null; } else { if(n_polys > 0) { geometry.computeFaceNormals(); } geometry.computeBoundingBox(); geometry.computeBoundingSphere(); } return geometry; } }
/** * Utils for AngularJS v1.x * @author Bendy Zhang <zb@bndy.net> * @copyright BNDY.NET 2017 * @see {@link http://bndy.net|Home Page} * @external angular */ 'use strict'; ;(function (angular) { /** * Starts angular application. * @function external:angular.start * @param {string} appName - The angular application module name. * @param {object=} options - The options injected. * @param {function} options.run - The fun function. * @param {function} options.config - The config function. * @param {object} options.httpInterceptor - The httpIntercaptor. * @param {function} options.httpInterceptor.request - The intercaptor about request. * @param {function} options.httpInterceptor.requestError - The intercaptor about requestError. * @param {function} options.httpInterceptor.response - The intercaptor about response. * @param {function} options.httpInterceptor.responseError - The intercaptor about responseError. * * @example <caption>Usage</caption> * angular.start('ngApp', { * request: function(config) {}, * requestError: function(rejection) {}, * response: function(response) {}, * responseError: function(rejection) {}, * ... * }); * */ angular.start = function (appName, options) { options = options || {}; var app = angular.module(appName); if (angular.isFunction(options.config)) { app.config(options.config); } if (angular.isFunction(options.run)) { app.run(options.run); } if (angular.isObject(options.httpInterceptor)) { app.config([ '$provide', '$qProvider', '$httpProvider', function ($provide, $qProvider, $httpProvider) { $qProvider.errorOnUnhandledRejections(false); // http interceptor $provide.factory('appHttpInterceptor', [ '$q', '$injector', '$timeout', function ($q, $injector, $timeout) { return { 'request': function (config) { if (angular.isFunction(options.httpInterceptor.request)) { options.httpInterceptor.request(config); } return config; }, 'requestError': function (rejection) { if (angular.isFunction(options.httpInterceptor.requestError)) { options.httpInterceptor.requestError(rejection); } else { console.error(rejection); } return $q.reject(rejection); }, 'response': function (response) { if (angular.isFunction(options.httpInterceptor.response)) { options.httpInterceptor.response(response); } return response; }, 'responseError': function (rejection) { if (angular.isFunction(options.httpInterceptor.responseError)) { options.httpInterceptor.responseError(rejection); } else { console.error(rejection); } return $q.reject(rejection); } }; } ]); $httpProvider.interceptors.push('appHttpInterceptor'); } ]); } angular.element(document).ready(function () { angular.bootstrap(document, [appName]); }); } /** * Resets Form validation status. * @function external:angular.resetForm * @param {object} scopeDotFormName - The object of angular Form. * @example * angular.resetForm($scope.formName); */ angular.resetForm = function (scopeDotFormName) { var ngForm = scopeDotFormName; ngForm.$setPristine(); ngForm.$setUntouched(); ngForm.$error = {}; for (var item in ngForm) { if (item.indexOf('$') < 0) { if (ngForm[item]) { ngForm[item].$error = {}; } } } }; /** * Gets a single Promise that resolves all $http functions. * @function external:angular.ajaxAll * @param {$http} argument - A $http such as $http.get() * @param {$http} ... - more * @returns {Promise} A single promise. * @example * angular.ajaxAll($http.get(...), $http.post(...)).then(function(values){}, function(rejections){}); * angular.ajaxAll($http.get(...)); */ angular.ajaxAll = function () { var promises = []; for (var idx = 0; idx < arguments.length; idx++) { var ajax = arguments[idx]; promises.push(new Promise(function (resolve, reject) { ajax.then(resolve, reject); })); } return Promise.all(promises); } })(angular);
import React from 'react'; import { storiesOf } from '@kadira/storybook'; import DayPicker from '../src/components/DayPicker'; import moment from 'moment-jalaali' import { VERTICAL_ORIENTATION, VERTICAL_SCROLLABLE, } from '../constants'; const TestPrevIcon = props => ( <span style={{ border: '1px solid #dce0e0', backgroundColor: '#fff', color: '#484848', padding: '3px' }} > Prev </span> ); const TestNextIcon = props => ( <span style={{ border: '1px solid #dce0e0', backgroundColor: '#fff', color: '#484848', padding: '3px' }} > Next </span> ); storiesOf('DayPicker', module) .addWithInfo('default', () => ( <DayPicker /> )) .addWithInfo('Gregorian Datepicker', () => ( <DayPicker monthFormat="YYYY MMMM" inFarsi={false} /> )) .addWithInfo('more than one month', () => ( <DayPicker numberOfMonths={2} /> )) .addWithInfo('vertical', () => ( <DayPicker numberOfMonths={2} orientation={VERTICAL_ORIENTATION} /> )) .addWithInfo('vertically scrollable with 12 months', () => ( <div style={{ height: '568px', width: '320px', }}> <DayPicker numberOfMonths={12} orientation={VERTICAL_SCROLLABLE} /> </div> )) .addWithInfo('with custom arrows', () => ( <DayPicker navPrev={<TestPrevIcon />} navNext={<TestNextIcon />} /> )) .addWithInfo('with custom details', () => ( <DayPicker renderDay={day => (day.day() % 6 === 5 ? '😻' : day.format('D'))} /> )) .addWithInfo('vertical with fixed-width container', () => ( <div style={{ width: '400px' }}> <DayPicker numberOfMonths={2} orientation={VERTICAL_ORIENTATION} /> </div> ));
var userRoutes = FlowRouter.group({ prefix: '/meteoris/user', name: 'meteoris_user', triggersEnter: [function(context, redirect) { authenticating(context.path); }] }); /* router level validation, only allow user with group "admin" to access this page */ function authenticating(path) { var except = [ '/meteoris/user/login', '/meteoris/user/register', '/meteoris/user/profile' ]; if (except.indexOf(path) == -1) { if (!Meteoris.Role.userIsInGroup("admin")) { Meteoris.Flash.set("danger", "403 Unauthenticated"); FlowRouter.go("/"); } } } /* USERS */ userRoutes.route('/', { action: function() { BlazeLayout.render('meteoris_themeAdminMain', {content: "meteoris_userIndex"}); }, }); userRoutes.route('/login', { action: function() { BlazeLayout.render('meteoris_themeAdminLogin', {content: "meteoris_userLogin"}); }, }); userRoutes.route('/register', { action: function() { BlazeLayout.render('meteoris_themeAdminRegister', {content: "meteoris_userRegister"}); }, }); userRoutes.route('/insert', { action: function() { BlazeLayout.render('meteoris_themeAdminMain', {content: "meteoris_userInsert"}); }, }); userRoutes.route('/update/:id', { action: function() { BlazeLayout.render('meteoris_themeAdminMain', {content: "meteoris_userUpdate"}); }, }); userRoutes.route('/forget-password', { action: function() { console.log("forget password page") BlazeLayout.render('meteoris_themeAdminMain', {content: "meteoris_userForgetPassword"}); }, }); userRoutes.route('/view/:id', { action: function() { BlazeLayout.render('meteoris_themeAdminMain', {content: "meteoris_userView"}); }, }); userRoutes.route('/profile', { action: function() { BlazeLayout.render('meteoris_themeAdminMain', {content: "meteoris_userProfile"}); }, }); userRoutes.route('/reset-password/:token', { action: function() { BlazeLayout.render('meteoris_themeAdminMain', {content: "meteoris_userResetPassword"}); }, }); userRoutes.route('/settings', { action: function() { BlazeLayout.render('meteoris_themeAdminMain', {content: "meteoris_userSettings"}); }, }); /* EOF USERS */
"use strict"; const gulp = require('gulp'); //build system const source = require('vinyl-source-stream'); //converts reatable stream from webpack into the gulp compatible stream const sass = require('gulp-sass'); //css preprocessor const notifier = require('node-notifier'); //desktop notifications on error const del = require('del'); // remove files const runSequence = require('run-sequence'); // run tasks in order const flatten = require('gulp-flatten'); // removes folder structure from wilcard searches const Imagemin = require('imagemin'); // compress images in dist task const path = require('path'); const shell = require('gulp-shell') /* variables for use in gulp tasks */ const RAW_PATH = './app/'; const COMPONENT_PATH = './app/js/components/'; const RAW_IMG_PATH = RAW_PATH + 'images/'; const RAW_FONTS_PATH = RAW_PATH + 'fonts/'; const RAW_JS_PATH = RAW_PATH + 'js/'; const RAW_SCSS_PATH = RAW_PATH + 'scss/'; const SCRIPTS_FILENAME = 'app.js'; var DEV_PATH = './dev/' var DIST_PATH = './www/' var destPath; var destImgPath; var destJsPath; var destCssPath; var destFontsPath; gulp.task('buildGlobalStyles', function() { return gulp.src(RAW_SCSS_PATH + '**/*.scss') .pipe(sass().on('error', function(err){ notifier.notify({title:'ERROR', message:'CSS'}); sass.logError.bind(this)(err); })) .pipe(gulp.dest(RAW_PATH + 'css/')); }); gulp.task('buildComponentStyles', function() { return gulp.src(COMPONENT_PATH + '**/styles.scss') .pipe(sass()) .pipe(gulp.dest(COMPONENT_PATH)); }); /* basic server for development */ gulp.task('devServer', shell.task([ 'webpack-dev-server --colors --open --content-base dev/' ])); /* basic server for development */ gulp.task('writeBundle', shell.task([ 'webpack --config webpack.production.config.js -p' ])); /* copy images from App to www */ gulp.task('copyImages', function() { return gulp.src(RAW_IMG_PATH + '**/*') .pipe(gulp.dest(destImgPath)); }); gulp.task('copyFonts', function() { return gulp.src(RAW_FONTS_PATH + '**/*') .pipe(gulp.dest(destFontsPath)); }); gulp.task('updateIndexFile', function() { gulp.src(RAW_PATH + 'index.html') .pipe(gulp.dest(destPath)); }); /* Image tasks */ gulp.task('cleanImages', function() { del([ destImgPath + '**/*' ]); }); gulp.task('optimizeImages', function() { new Imagemin() .src(destImgPath + '*.{gif,jpg,png,svg}') .dest(destImgPath) .use(Imagemin.jpegtran({progressive: true})) .use(Imagemin.gifsicle({interlaced: true})) .use(Imagemin.optipng({optimizationLevel: 3})) .run(); }); /* bring component images into one image folder inside "App" */ gulp.task('gatherComponentImages', function() { return gulp.src(COMPONENT_PATH + '**/*.{gif,jpg,png,svg}') .pipe(flatten()) .pipe(gulp.dest(RAW_IMG_PATH)); }); /* Watchers */ gulp.task('watch', function() { gulp.watch([RAW_SCSS_PATH + '**/*.scss'],['buildGlobalStyles']); gulp.watch([COMPONENT_PATH + '**/*.scss'],['buildComponentStyles']); gulp.watch([RAW_IMG_PATH + '**/*'],['copyImages']); gulp.watch([RAW_FONTS_PATH + '**/*'],['copyFonts']); gulp.watch([COMPONENT_PATH + '**/*.{gif,jpg,png,svg}'],['gatherComponentImages']); }); /* work on project */ gulp.task('dev', function () { destPath = DEV_PATH; destImgPath = DEV_PATH + 'images/'; destJsPath = DEV_PATH + 'js/'; destCssPath = DEV_PATH + 'css/'; destFontsPath = DEV_PATH + 'fonts/'; runSequence('updateIndexFile', 'buildComponentStyles', 'buildGlobalStyles', 'gatherComponentImages', 'cleanImages', 'copyFonts', 'copyImages', 'watch', 'devServer'); }); /* prepare project for production evironemnt */ gulp.task('dist', function () { destPath = DIST_PATH; destImgPath = DIST_PATH + 'images/'; destJsPath = DIST_PATH + 'js/'; destCssPath = DIST_PATH + 'css/'; destFontsPath = DIST_PATH + 'fonts/'; runSequence('updateIndexFile', 'buildComponentStyles', 'buildGlobalStyles', 'gatherComponentImages', 'cleanImages', 'copyImages', 'copyFonts', 'optimizeImages', 'writeBundle'); }); /* Run 'dev' task as default gulp task */ gulp.task('default', function () { gulp.tasks.dev.fn(); });
'use strict'; /** * Module dependencies. */ var should = require('should'), mongoose = require('mongoose'), User = mongoose.model('User'), Colision = mongoose.model('Colision'); /** * Globals */ var user, colision; /** * Unit tests */ describe('Colision Model Unit Tests:', function() { beforeEach(function(done) { user = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: 'test@test.com', username: 'username', password: 'password' }); user.save(function() { colision = new Colision({ name: 'Colision Name', user: user }); done(); }); }); describe('Method Save', function() { it('should be able to save without problems', function(done) { return colision.save(function(err) { should.not.exist(err); done(); }); }); it('should be able to show an error when try to save without name', function(done) { colision.name = ''; return colision.save(function(err) { should.exist(err); done(); }); }); }); afterEach(function(done) { Colision.remove().exec(); User.remove().exec(); done(); }); });
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE import CodeMirror from 'codemirror'; var headerList = /(#+)(\s+)?/; CodeMirror.commands.headChangeRight = function (cm) { if (cm.getOption("disableInput")) return CodeMirror.Pass; var pos = cm.getCursor(); var line = cm.getLine(pos.line), match = headerList.exec(line); if (match && match[1].length < 5) { cm.replaceRange("#", { line: pos.line, ch: 0 }); } };
'use strict'; const path = require('path'); const mm = require('egg-mock'); const utils = require('../../../utils'); describe('test/lib/core/loader/config_loader.test.js', () => { let app; const home = utils.getFilepath('apps/demo/logs/home'); afterEach(() => app.close()); afterEach(mm.restore); it('should get middlewares', function* () { app = utils.app('apps/demo'); yield app.ready(); app.config.coreMiddleware.slice(0, 6).should.eql([ 'meta', 'siteFile', 'notfound', 'static', 'bodyParser', 'session', ]); }); it('should get logger dir when unittest', function* () { mm(process.env, 'EGG_HOME', home); mm(process.env, 'EGG_SERVER_ENV', 'unittest'); app = utils.app('apps/demo'); yield app.ready(); app.config.logger.dir.should.eql(utils.getFilepath('apps/demo/logs/demo')); }); it('should get logger dir when default', function* () { mm(process.env, 'EGG_HOME', home); mm(process.env, 'EGG_SERVER_ENV', 'default'); app = utils.app('apps/demo'); yield app.ready(); app.config.logger.dir.should.eql(path.join(home, 'logs/demo')); }); });
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2015 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides class sap.ui.core.support.plugins.Selector (Selector support plugin) sap.ui.define(['jquery.sap.global', 'sap/ui/core/Popup', 'sap/ui/core/support/Plugin'], function(jQuery, Popup, Plugin) { "use strict"; /** * Creates an instance of sap.ui.core.support.plugins.Selector. * @class This class represents the selector plugin for the support tool functionality of UI5. This class is internal and all its functions must not be used by an application. * * @abstract * @extends sap.ui.base.Object * @version 1.32.10 * @constructor * @private * @alias sap.ui.core.support.plugins.Selector */ var Selector = Plugin.extend("sap.ui.core.support.plugins.Selector", { constructor : function(oSupportStub) { Plugin.apply(this, ["sapUiSupportSelector", "", oSupportStub]); if (this.isToolPlugin()) { throw Error(); } this._aEventIds = [this.getId() + "Highlight"]; this._oPopup = new Popup(); } }); /** * Handler for sapUiSupportSelectorHighlight event * * @param {sap.ui.base.Event} oEvent the event * @private */ Selector.prototype.onsapUiSupportSelectorHighlight = function(oEvent){ highlight(oEvent.getParameter("id"), this, oEvent.getParameter("sendInfo")); }; Selector.prototype.init = function(oSupportStub){ Plugin.prototype.init.apply(this, arguments); var jPopupRef; if (!this._sPopupId) { this._sPopupId = this.getId() + "-" + jQuery.sap.uid(); var rm = sap.ui.getCore().createRenderManager(); rm.write("<div id='" + this._sPopupId + "' style='border: 2px solid rgb(0, 128, 0); background-color: rgba(0, 128, 0, .55);'></div>"); rm.flush(sap.ui.getCore().getStaticAreaRef(), false, true); rm.destroy(); jPopupRef = jQuery.sap.byId(this._sPopupId); this._oPopup.setContent(jPopupRef[0]); } else { jPopupRef = jQuery.sap.byId(this._sPopupId); } var that = this; this._fSelectHandler = function(oEvent){ if (!oEvent.shiftKey || !oEvent.altKey || !oEvent.ctrlKey) { return; } var sId = jQuery(oEvent.target).closest("[data-sap-ui]").attr("id"); if (highlight(sId, that, true)) { oEvent.stopPropagation(); oEvent.preventDefault(); } }; this._fCloseHandler = function(oEvent){ that._oPopup.close(0); }; jPopupRef.bind("click", this._fCloseHandler); jQuery(document).bind("mousedown", this._fSelectHandler); }; Selector.prototype.exit = function(oSupportStub){ this._oPopup.close(0); if (this._fCloseHandler) { jQuery.sap.byId(this._sPopupId).unbind("click", this._fCloseHandler); this._fCloseHandler = null; } if (this._fSelectHandler) { jQuery(document).unbind("mousedown", this._fSelectHandler); this._fSelectHandler = null; } Plugin.prototype.exit.apply(this, arguments); }; function highlight(sId, oPlugin, bSend){ if (sId) { var oElem = sap.ui.getCore().byId(sId); if (oElem) { var jPopupRef = jQuery.sap.byId(oPlugin._sPopupId); var jRef = oElem.$(); if (jRef.is(":visible")) { jPopupRef.width(jRef.outerWidth()); jPopupRef.height(jRef.outerHeight()); oPlugin._oPopup.open(0, "BeginTop", "BeginTop", jRef[0], "0 0", "none"); if (bSend) { sap.ui.core.support.Support.getStub().sendEvent(oPlugin.getId() + "Select", getElementDetailsForEvent(oElem, oPlugin)); } setTimeout(function(){ oPlugin._oPopup.close(0); }, 1000); return true; } } } return false; } function getElementDetailsForEvent(oElement, oPlugin){ //TODO: to be extended return {"id": oElement.getId()}; } return Selector; });
var benchmark = require('benchmark') , p = require('../fn-pasta')() var bench = new benchmark.Suite var add = p.op('+') bench.add('op', function () { var num = 0 for(var i = 1; i<12; i++) { num = add(num, i) } }).add('+', function () { var num = 0 for(var i = 1; i<12; i++) { num = num + i } }).on('cycle', function (e) { console.log(e.target.count + ' ' + e.target.name) }).on('complete', function () { console.log('Fastest is ' + this.filter('fastest').pluck('name')) }).run({ async: true })
/* written by Joe Wallace, October 2017 the code below adds the concordance functionality also the listeners for the "reset", "home", "previous" and "next" buttons the html texts themselves were generated by a Python script I wrote, which uses regular expressions to extract plays from Shakespeare's First Folio and then add html tags */ function setup() { var titles = ['The Tempest', 'The Two Gentlemen of Verona', 'The Merry Wiues of Windsor', 'Measvre, For Measure', 'The Comedie of Errors', 'Much adoe about Nothing', "Loues Labour's lost", 'A Midsommer Nights Dreame', 'The Merchant of Venice', 'As you Like it', 'The Taming of the Shrew', "All's Well, that Ends Well", 'Twelfe Night, Or what you will', 'The Winters Tale', 'The life and death of King John', 'The life and death of King Richard the Second', 'The First Part of Henry the Fourth', 'The Second Part of Henry the Fourth', 'The Life of Henry the Fift', 'The first Part of Henry the Sixt', 'The second Part of Henry the Sixt', 'The third Part of Henry the Sixt', 'The Tragedie of Richard the Third', 'The Famous History of the Life of King Henry the Eight', 'The Tragedie of Coriolanus', 'The Tragedie of Titus Andronicus', 'The Tragedie of Romeo and Juliet', 'The Life of Timon of Athens', 'The Tragedie of Julius Caesar', 'The Tragedie of Macbeth', 'The Tragedie of Hamlet', 'The Tragedie of King Lear', 'The Tragedie of Othello, the Moore of Venice', 'The Tragedie of Anthonie, and Cleopatra', 'The Tragedie of Cymbeline']; var $ = function(id) {return document.getElementById(id);}; var $_c = function(id) {return document.getElementsByClassName(id);}; var fulltext = ""; var word = ""; // some plays have act breaks and some not. fulltext id refers to those without act breaks if ($("fulltext")) { fulltext = $("fulltext").innerHTML; } else { for (var i = 0; i < 5; i++) { fulltext += $_c("text")[i].innerHTML; // not generally advisable to concatenate html but in this case is ok } } // function to parse url arguments function urlArgs() { var args = {}; var query = location.search.substring(1); var pos = query.indexOf('='); var nom = query.substring(0, pos); var val = query.substring(pos+1); val = decodeURIComponent(val); args[nom] = val; return args; } var args = urlArgs(); // only executes if the concordance form has a value if (args.word) { // defines word; strips + symbol and spaces if present word = args.word; var pluses = /[+]/g; word = word.replace(pluses, ""); var spaces = /[\s]/g; word = word.replace(spaces, ""); var pattern = /[\w]+|[^\s]+/g; // this regex tokenizes all words and punctuation; preserves <br> tags var tokens = fulltext.match(pattern); // array of tokens var output = []; // array to hold matching tokens var padding = 20; // number of tokens displayed before and after selected word var ending = "<br><br>-------------------------<br><br>"; // divider between text excerpts var pattern2 = /[.,;:?!]+<br>|[.,;:?!]+<br><br>/g; // this regex represents punctuation and <br> tags for (var i = 0; i < tokens.length; i++) { // deploys regex above to get word in usable form; checks each token against word if (tokens[i].replace(pattern2, "").toLowerCase() == word.toLowerCase()) { /* the three conditions below deal with possibility of word occurring at beginning or end of the text; the first branch is by far the most likely; word neither at beginning nor end */ if (tokens[i-padding] && tokens[i+padding]) { var line = tokens.slice(i-padding, i+padding); // show selected word in red; in this case padding denotes position of word line[padding] = "<span style='color:red'>"+line[padding]+"</span>"; output.push(line); } // in this case the word is near the beginning else if (!tokens[i-padding]) { var line = tokens.slice(0, i+padding); // in this case i simply denotes position of word line[i] = "<span style='color:red'>"+line[i]+"</span>"; output.push(line); } // in this case tokens[i+padding] would be undefined and therefore word is near the end else { var line = tokens.slice(i-padding, tokens.length); /* finds position of word by checking it against length of the tokens array and length of the line array; word will be i back from end of tokens array and so tokens.length minus i gives middle of line array */ line[line.length - (tokens.length-i)] = "<span style='color:red'>" +line[line.length - (tokens.length-i)]+"</span>"; output.push(line); } } } // now process the output for display; first display number of results var w = word; var results = "Word is: "+w+"<br><br>Total Results: "+output.length.toString()+ending; // output is an array of arrays; process each array separately and add divider for (var j = 0; j < output.length; j++) { var lines = ""; lines = output[j].join(" "); lines = lines+ending; results += lines; } // finally change the display to show the processed results if ($("fulltext")) { $("fulltext").innerHTML = results; } else { var text = $_c("text"); text[0].innerHTML = results; for (var k = 1; k < 5; k++) { text[k].style.display = "none"; } } } /* the following event listeners define the reset, previous, next, and home buttons */ $("reset").addEventListener("click", function() { if (location.search) { location = location.href.replace(location.search.substring(0), ""); } else {location.reload();} }); var index; // determine where we are in the titles array and set the index for (var i = 0; i < titles.length; i++) { if (titles[i] == $("title").innerHTML) index = i; } if ($("previous")) { if (titles[index-1]) { $("previous").addEventListener("click", function() { location = titles[index-1]+".html"; }); } else { $("previous").stytle.display = "none"; } if ($("next")) { if (titles[index+1]) { $("next").addEventListener("click", function() { location = titles[index+1]+".html"; }); } else { $("next").style.display = "none"; } $("home").addEventListener("click", function() { location = "Folio_Homepage.html"; }); } // function to register event listeners function onLoad(f) { if (onLoad.loaded) { window.setTimeout(f, 0); } else if (window.addEventListener) { window.addEventListener("load", f, false); } else if (window.attachEvent) { window.attachEvent("onload", f); } } onLoad.loaded = false; onLoad(function(){onLoad.loaded=true;}); onLoad(setup);
import testUsers from '@webex/test-helper-test-users'; import {expect} from 'chai'; describe('samples', () => { describe('browser-single-party-call', () => { describe('normal dialing', () => { let mccoy, spock; const browserSpock = browser.select('browserSpock'); const browserMccoy = browser.select('browserMccoy'); before('create test users', () => testUsers.create({count: 2}) .then((users) => { [spock, mccoy] = users; })); before('reload browser', () => { browser.refresh(); }); it('loads the app', () => { browser.url('/browser-single-party-call'); }); it('connects mccoy\'s browser', () => { expect(browserMccoy.getTitle()).to.equal('Sample: Single Party Calling'); browserMccoy.setValue('[placeholder="Your access token"]', mccoy.token.access_token); browserMccoy.click('[title="connect"]'); browserMccoy.waitForExist('.listening'); }); it('connects spock\'s browser', () => { expect(browserSpock.getTitle()).to.equal('Sample: Single Party Calling'); browserSpock.setValue('[placeholder="Your access token"]', spock.token.access_token); browserSpock.click('[title="connect"]'); browserSpock.waitForExist('.listening'); }); it('places call from spock to mccoy', () => { browserSpock.setValue('[placeholder="Person ID or Email Address or SIP URI or Room ID"]', mccoy.emailAddress); browserSpock.click('[title="dial"]'); browserMccoy.pause(2500); browserMccoy.alertAccept(); }); it('ends the call', () => { browser.pause(5000); // TODO add assertions around streams browserSpock.click('[title="hangup"]'); }); }); }); });
'use strict'; /* globals describe, expect, it, beforeEach, afterEach */ var app = require('../..'); import request from 'supertest'; var newSensor; describe('Sensor API:', function() { describe('GET /api/sensors', function() { var sensors; beforeEach(function(done) { request(app) .get('/api/sensors') .expect(200) .expect('Content-Type', /json/) .end((err, res) => { if (err) { return done(err); } sensors = res.body; done(); }); }); it('should respond with JSON array', function() { sensors.should.be.instanceOf(Array); }); }); describe('POST /api/sensors', function() { beforeEach(function(done) { request(app) .post('/api/sensors') .send({ name: 'New Sensor', info: 'This is the brand new sensor!!!' }) .expect(201) .expect('Content-Type', /json/) .end((err, res) => { if (err) { return done(err); } newSensor = res.body; done(); }); }); it('should respond with the newly created sensor', function() { newSensor.name.should.equal('New Sensor'); newSensor.info.should.equal('This is the brand new sensor!!!'); }); }); describe('GET /api/sensors/:id', function() { var sensor; beforeEach(function(done) { request(app) .get(`/api/sensors/${newSensor._id}`) .expect(200) .expect('Content-Type', /json/) .end((err, res) => { if (err) { return done(err); } sensor = res.body; done(); }); }); afterEach(function() { sensor = {}; }); it('should respond with the requested sensor', function() { sensor.name.should.equal('New Sensor'); sensor.info.should.equal('This is the brand new sensor!!!'); }); }); describe('PUT /api/sensors/:id', function() { var updatedSensor; beforeEach(function(done) { request(app) .put(`/api/sensors/${newSensor._id}`) .send({ name: 'Updated Sensor', info: 'This is the updated sensor!!!' }) .expect(200) .expect('Content-Type', /json/) .end(function(err, res) { if (err) { return done(err); } updatedSensor = res.body; done(); }); }); afterEach(function() { updatedSensor = {}; }); it('should respond with the updated sensor', function() { updatedSensor.name.should.equal('Updated Sensor'); updatedSensor.info.should.equal('This is the updated sensor!!!'); }); it('should respond with the updated sensor on a subsequent GET', function(done) { request(app) .get(`/api/sensors/${newSensor._id}`) .expect(200) .expect('Content-Type', /json/) .end((err, res) => { if (err) { return done(err); } let sensor = res.body; sensor.name.should.equal('Updated Sensor'); sensor.info.should.equal('This is the updated sensor!!!'); done(); }); }); }); describe('PATCH /api/sensors/:id', function() { var patchedSensor; beforeEach(function(done) { request(app) .patch(`/api/sensors/${newSensor._id}`) .send([ { op: 'replace', path: '/name', value: 'Patched Sensor' }, { op: 'replace', path: '/info', value: 'This is the patched sensor!!!' } ]) .expect(200) .expect('Content-Type', /json/) .end(function(err, res) { if (err) { return done(err); } patchedSensor = res.body; done(); }); }); afterEach(function() { patchedSensor = {}; }); it('should respond with the patched sensor', function() { patchedSensor.name.should.equal('Patched Sensor'); patchedSensor.info.should.equal('This is the patched sensor!!!'); }); }); describe('DELETE /api/sensors/:id', function() { it('should respond with 204 on successful removal', function(done) { request(app) .delete(`/api/sensors/${newSensor._id}`) .expect(204) .end(err => { if (err) { return done(err); } done(); }); }); it('should respond with 404 when sensor does not exist', function(done) { request(app) .delete(`/api/sensors/${newSensor._id}`) .expect(404) .end(err => { if (err) { return done(err); } done(); }); }); }); });
// not implemented as of ff 42.0 import "../tones/tones.js"; // flow: // - goals - hit the right notes, let the player design a level // - feedback - =- points etc. // - no distraction - use headphones // - just right - balance // simplicity: // - core - less is more // - limited choices - // - intuitive - guide the player a little bit // - player's perspective - step by step var r = 0, g = 0, b = 0; var background = { color: 'black' }; var game = { state: 'start', editMode: false, }; var overlay = { counter: -1, title: 'Squier', subtitle: 'bar' }; var player = { x: 60, y: 350, width: 10, height: 10, counter: 0, }; var keyboard = {}; var semitones = []; var level00 = [ // up and down a C maj scale {x: 90, y: 0, // C width: 10, height: 10, note: 'c', state: 'alive', color: 'brown'}, {x: 100, y: 0, width: 10, height: 10, state: 'alive', color: 'white'}, {x: 120, y: -30, // D width: 10, height: 10, note: 'd', state: 'alive', color: 'brown'}, {x: 150, y: -60, // E width: 10, height: 10, note: 'e', state: 'alive', color: 'brown'}, {x: 165, y: -90, // F width: 10, height: 10, note: 'f', state: 'alive', color: 'brown'}, {x: 195, y: -120, // G width: 10, height: 10, note: 'g', state: 'alive', color: 'brown'}, {x: 225, y: -150, // A width: 10, height: 10, note: 'a', state: 'alive', color: 'brown'}, {x: 255, y: -180, // B width: 10, height: 10, note: 'b', state: 'alive', color: 'brown'}, {x: 270, y: -210, // C5 width: 10, height: 10, note: 'c', state: 'alive', color: 'brown'}, {x: 255, y: -240, // B width: 10, height: 10, note: 'b', state: 'alive', color: 'brown'}, {x: 225, y: -270, // A width: 10, height: 10, note: 'a', state: 'alive', color: 'brown'}, {x: 195, y: -300, // G width: 10, height: 10, note: 'g', state: 'alive', color: 'brown'}, {x: 165, y: -330, // F width: 10, height: 10, note: 'f', state: 'alive', color: 'brown'}, {x: 150, y: -360, // E width: 10, height: 10, note: 'e', state: 'alive', color: 'brown'}, {x: 120, y: -390, // D width: 10, height: 10, note: 'd', state: 'alive', color: 'brown'}, {x: 90, y: -420, // C width: 10, height: 10, note: 'c', state: 'alive', color: 'brown'}, ]; var level01 = [ // up C maj scale in 3rds {x: 90, y: 0, // C width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 150, y: -30, // E width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 120, y: -60, // D width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 165, y: -90, // F width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 150, y: -120, // E width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 195, y: -150, // G width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 165, y: -180, // F width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 225, y: -210, // A width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 195, y: -240, // G width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 255, y: -270, // B width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 225, y: -300, // A width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 270, y: -330, // C5 width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 255, y: -350, // B width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 300, y: -380, // D5 width: 10, height: 10, state: 'alive', color: 'brown'}, ]; var level02 = [ // ovcaci, ctveraci {x: 90, y: 0, // C width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 150, y: -60, // E width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 195, y: -120, // G width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 90, y: -180, // C width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 150, y: -240, // E width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 195, y: -300, // G width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 150, y: -330, // E width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 150, y: -360, // E width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 120, y: -390, // D width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 150, y: -420, // E width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 150, y: -450, // E width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 120, y: -480, // D width: 10, height: 10, state: 'alive', color: 'brown'}, // repeat the middle part {x: 150, y: -510, // E width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 150, y: -540, // E width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 120, y: -570, // D width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 150, y: -600, // E width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 150, y: -630, // E width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 120, y: -660, // D width: 10, height: 10, state: 'alive', color: 'brown'}, // outro {x: 150, y: -690, // E width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 120, y: -720, // D width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 90, y: -750, // C width: 10, height: 10, state: 'alive', color: 'brown'}, ]; var level03 = [ // non-diatonic 3rds {x: 255, y: 0, // B width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 300, y: -20, // D5 width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 255, y: -40, // B width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 300, y: -60, // D5 width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 225, y: -80, // A width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 270, y: -100, // C5 width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 225, y: -120, // A width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 270, y: -140, // C5 width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 195, y: -160, // G width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 240, y: -180, // A# width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 195, y: -200, // G width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 240, y: -220, // A# width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 165, y: -240, // F width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 210, y: -260, // G# width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 165, y: -280, // F width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 210, y: -300, // G# width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 150, y: -320, // E width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 180, y: -340, // F# width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 150, y: -360, // E width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 180, y: -380, // F# width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 120, y: -400, // D width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 165, y: -420, // F width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 120, y: -440, // D width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 165, y: -460, // F width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 90, y: -480, // C width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 135, y: -500, // D# width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 90, y: -520, // C width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 135, y: -540, // D# width: 10, height: 10, state: 'alive', color: 'brown'}, ]; var level04 = [ {x: 90, y: 0, // C width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 135, y: -20, // D# width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 195, y: -40, // G width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 90, y: -60, // C width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 135, y: -80, // D# width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 195, y: -100, // G width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 90, y: -120, // C width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 135, y: -140, // D# width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 165, y: -150, // F width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 195, y: -170, // G width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 240, y: -190, // A# width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 270, y: -210, // C5 width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 195, y: -230, // G width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 240, y: -250, // A# width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 270, y: -270, // C5 width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 195, y: -290, // G width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 240, y: -310, // A# width: 10, height: 10, state: 'alive', color: 'brown'}, {x: 300, y: -320, // D5 width: 10, height: 10, state: 'alive', color: 'brown'}, ]; var levelLength = 0; function initLevel(level) { levelLength = level.length; for(var i = 0; i < level.length; i++) { semitones.push({ x: level[i].x, y: level[i].y, width: level[i].width, height: level[i].height, state: level[i].state, color: level[i].color, note: level[i].note }); } } var testlevel = [ {x: 10, y: -380, note: 'c', color: 'brown', state: 'alive'}, ]; var levels = [level00];//, level01, level02, level03, level04]; var levelIterator = 0; // =========== Game ============ function updateGame() { if(game.state == 'playing' && semitones.length == 0) { game.state = 'won'; if(player.counter >= levelLength / 1.33) { overlay.title = 'WELL PLAYED!'; } else if(player.counter < levelLength / 1.33 && player.counter >= levelLength / 2) { overlay.title = 'HEY, TONES :P'; } else if(player.counter < levelLength / 2 && player.counter >= levelLength / 4) { overlay.title = 'YOU DEAF???'; } else { overlay.title = 'YOU RUINED IT.'; levelIterator -= 1; } overlay.subtitle = 'press space to play next level'; overlay.counter = 0; player.counter = 0; } if(game.state == 'editing') { overlay.title = ''; overlay.subtitle = 'play your new level notes'; } if(game.state == 'over' && keyboard[32]) { game.state = 'start'; background.color = 'black'; player.y = 350; player.state = 'alive'; player.counter = 100; overlay.counter = -1; //overlay.title = 'READY YOUR SPEAKERS'; } if(game.state == 'won' && keyboard[32]) { game.state = 'start'; if(levelIterator >= levels.length) levelIterator = 0; initLevel(levels[levelIterator++]); player.y = 350; player.state = 'alive'; overlay.counter = -1; } if(overlay.counter >= 0) { overlay.counter++; } } //var language = (navigator.language || navigator.browserLanguage).split('-')[0]; function updatePlayer() { if(player.state == 'dead' || player.counter < 0) return;//<= 0) return; // key z or y if(keyboard[90]) { //|| keyboard[81]) { player.x = 12; //330; //r = 255; g = 0; b = 0; //background.color = 'rgb("+ r +", "+ g +", "+ b +")'; // red tones.play('c', 3); } // key x if(keyboard[88]) { player.x = 24; //330; //r = 255; g = 0; b = 0; //background.color = 'rgb("+ r +", "+ g +", "+ b +")'; // red tones.play('d', 3); } // key c if(keyboard[67]) { player.x = 36; //330; //r = 255; g = 0; b = 0; //background.color = 'rgb("+ r +", "+ g +", "+ b +")'; // red tones.play('e', 3); } // key v if(keyboard[86]) { player.x = 48; //330; //r = 255; g = 0; b = 0; //background.color = 'rgb("+ r +", "+ g +", "+ b +")'; // red tones.play('f', 3); } // key b if(keyboard[66]) { player.x = 60; //330; //r = 255; g = 0; b = 0; //background.color = 'rgb("+ r +", "+ g +", "+ b +")'; // red tones.play('g', 3); } // key n if(keyboard[78]) { player.x = 72; //330; //r = 255; g = 0; b = 0; //background.color = 'rgb("+ r +", "+ g +", "+ b +")'; // red tones.play('a', 3); } // key m if(keyboard[77]) { player.x = 84; //330; //r = 255; g = 0; b = 0; //background.color = 'rgb("+ r +", "+ g +", "+ b +")'; // red tones.play('b', 3); } // key a or q for French keyboard if(keyboard[65] || keyboard[81]) { player.x = 90; //330; r = 255; g = 0; b = 0; background.color = 'rgb("+ r +", "+ g +", "+ b +")'; // red tones.play('c'); } // key w or z for French keyboard if(keyboard[87]) { // || keyboard[90]) { player.x = 105; //305; r = 220; g = 20; b = 60; background.color = 'rgb("+ r +", "+ g +", "+ b +")'; // crimson tones.play('c#'); } // key s if(keyboard[83]) { player.x = 120; //300; r = 255; g = 165; b = 0; background.color = 'rgb("+ r +", "+ g +", "+ b +")'; // orange tones.play('D'); } // key e if(keyboard[69]) { player.x = 135; //285; r = 255; g = 215; b = 0; background.color = 'rgb("+ r +", "+ g +", "+ b +")'; // gold tones.play('D#'); } // key d if(keyboard[68]) { player.x = 150; //270; r = 255; g = 255; b = 0; background.color = 'rgb("+ r +", "+ g +", "+ b +")'; // yellow tones.play('E'); } // key f if(keyboard[70]) { player.x = 165; //240; r = 0; g = 128; b = 0; background.color = 'rgb("+ r +", "+ g +", "+ b +")'; // green tones.play('f'); } // key t if(keyboard[84]) { player.x = 180; //225; r = 46; g = 139; b = 87; background.color = 'rgb("+ r +", "+ g +", "+ b +")'; // seagreen tones.play('f#'); } // key g if(keyboard[71]) { player.x = 195; //210; r = 0; g = 255; b = 255; background.color = 'rgb("+ r +", "+ g +", "+ b +")'; // cyan tones.play('g'); } // key y if(keyboard[89]) { player.x = 210; //195; r = 0; g = 128; b = 128; background.color = 'rgb("+ r +", "+ g +", "+ b +")'; // teal tones.play('g#'); } // key h if(keyboard[72]) { player.x = 225; //180; r = 0; g = 0; b = 255; background.color = 'rgb("+ r +", "+ g +", "+ b +")'; // blue tones.play('A'); } // key u if(keyboard[85]) { player.x = 240; //165; r = 186; g = 85; b = 211; background.color = 'rgb("+ r +", "+ g +", "+ b +")'; // mediumorchid tones.play('A#'); } // key j if(keyboard[74]) { player.x = 255; //150; r = 128; g = 0; b = 128; background.color = 'rgb("+ r +", "+ g +", "+ b +")'; // purple tones.play('b'); } // key k if(keyboard[75]) { player.x = 270; //120; r = 255; g = 0; b = 255; background.color = 'rgb("+ r +", "+ g +", "+ b +")'; // magenta tones.play('c', 5); } // key l if(keyboard[76]) { player.x = 300; //90; r = 0; g = 0; b = 0; background.color = 'rgb("+ r +", "+ g +", "+ b +")'; // black tones.play('D', 5); } // key [ if(keyboard[219]) { player.x--; } // key ] if(keyboard[221]) { player.x++; } if(player.x < 350 && player.x > 60) { player.x--; } else { player.x = 60; } } function updateBackground() { //console.log('background.color: '+ background.color); background.color = "rgb("+ r-- +", "+ g-- +", "+ b-- +")"; } // ============== Enemy ============= function updateEnemies() { //create new enemies the first time through if(game.state == 'start' && keyboard[32]) { enemyBullets = []; game.state = 'playing'; } //for each enemy var enemy; for(var i = 0; i < semitones.length; i++) { enemy = semitones[i]; if(!enemy) continue; if(enemy && enemy.state == 'alive') { //enemy.counter++; enemy.y++; } } //remove the ones that are off the screen semitones = semitones.filter(function(enemy) { //return enemy.x + enemy.width > 0; return enemy.y < 400 ; //+ enemy.height > 0; }); } // =========== check for collisions === function checkCollisions() { if(player.state == 'dead') return; // counter = -1; harmless // counter = 0; harmful // counter = 1; collectable var enemy; for(var i = 0; i < semitones.length; i++) { enemy = semitones[i]; if(collided(enemy, player)) { player.state = 'hit'; if(enemy.color == 'white') { player.y = enemy.y - player.height; } else if(enemy.color == 'grey') { player.counter -= 1; } else if(enemy.color == 'brown') { player.counter += 1; enemy.x = -enemy.width; } if(player.counter <= 0) { player.state = 'dead'; levelIterator = 0; game.state = 'over'; overlay.title = 'DROPPED THE BEAT'; overlay.subtitle = 'press space to play again'; } } } } function collided(a, b) { // check for horizontal collision if(b.x + b.width >= a.x && b.x < a.x + a.width) { // check for vertical collision if(b.y + b.height >= a.y && b.y < a.y + a.height) { return true; } } // check a inside b if(b.x <= a.x && b.x + b.width >= a.x+a.width) { if(b.y <= a.y && b.y + b.height >= a.y + a.height) { return true; } } // check b inside a if(a.x <= b.x && a.x + a.width >= b.x+b.width) { if(a.y <= b.y && a.y + a.height >= b.y+b.height) { return true; } } return false; } // ========= Edit mode ======================= var editModeClicks = 1; function toggleEditMode() { if(editModeClicks % 2 == 0) { game.state = 'editing'; game.editMode = true; } else { game.state = 'start' game.editMode = false; } } // ============ Events ======================== var timestamp = Date.now(); var deltaTimestamp = 0; function checkEvents() { attachEvent(document, 'keydown', function(e) { //if(game.editMode == true) { //deltaTimestamp = Date.now() - timestamp; console.log('keycode: '+ e.keyCode +', character: '+ e.key); //String.fromCharCode(e.keyCode)); //console.log('tone.x: '+ Math.floor(deltaTimestamp / (1000 / 30))); //console.log('tone.y: '+ player.y); //console.log('timestamp: '+ timestamp +', delta: '+ deltaTimestamp); //} keyboard[e.keyCode] = true; }); attachEvent(document, 'keyup', function(e) { keyboard[e.keyCode] = false; }); attachEvent(document, 'mousedown', function(e) { console.log('mouse down event'); }); } function attachEvent(node, name, func) { if(node.addEventListener) { node.addEventListener(name, func, false); } else if(node.attachEvent) { node.attachEvent(name, func); } } // ============ Tones ============ (function(window) { var tones = { context: new (window.AudioContext || window.webkitAudioContext)(), attack: 1, release: 100, volume: 1, type: "sine", playFrequency: function(freq) { this.attack = this.attack || 1; this.release = this.release || 1; var envelope = this.context.createGain(); envelope.gain.setValueAtTime(this.volume, this.context.currentTime); envelope.connect(this.context.destination); envelope.gain.setValueAtTime(0, this.context.currentTime); envelope.gain.setTargetAtTime(this.volume, this.context.currentTime, this.attack / 1000); if(this.release) { envelope.gain.setTargetAtTime(0, this.context.currentTime + this.attack / 1000, this.release / 1000); setTimeout(function() { osc.stop(); osc.disconnect(envelope); envelope.gain.cancelScheduledValues(tones.context.currentTime); envelope.disconnect(tones.context.destination); }, this.attack * 10 + this.release * 10); } var osc = this.context.createOscillator(); osc.frequency.setValueAtTime(freq, this.context.currentTime); osc.type = this.type; osc.connect(envelope); osc.start(); }, /** * Usage: * notes.play(440); // plays 440 hz tone * notes.play("c"); // plays note c in default 4th octave * notes.play("c#"); // plays note c sharp in default 4th octave * notes.play("eb"); // plays note e flat in default 4th octave * notes.play("c", 2); // plays note c in 2nd octave */ play: function(freqOrNote, octave) { if(typeof freqOrNote === "number") { this.playFrequency(freqOrNote); } else if(typeof freqOrNote === "string") { if(octave == null) { octave = 4; } this.playFrequency(this.map[octave][freqOrNote.toLowerCase()]); } }, getTimeMS: function() { return this.context.currentTime * 1000; }, map: [{ // octave 0 "c": 16.351, "c#": 17.324, "db": 17.324, "d": 18.354, "d#": 19.445, "eb": 19.445, "e": 20.601, "f": 21.827, "f#": 23.124, "gb": 23.124, "g": 24.499, "g#": 25.956, "ab": 25.956, "a": 27.5, "a#": 29.135, "bb": 29.135, "b": 30.868 }, { // octave 1 "c": 32.703, "c#": 34.648, "db": 34.648, "d": 36.708, "d#": 38.891, "eb": 38.891, "e": 41.203, "f": 43.654, "f#": 46.249, "gb": 46.249, "g": 48.999, "g#": 51.913, "ab": 51.913, "a": 55, "a#": 58.27, "bb": 58.27, "b": 61.735 }, { // octave 2 "c": 65.406, "c#": 69.296, "db": 69.296, "d": 73.416, "d#": 77.782, "eb": 77.782, "e": 82.407, "f": 87.307, "f#": 92.499, "gb": 92.499, "g": 97.999, "g#": 103.826, "ab": 103.826, "a": 110, "a#": 116.541, "bb": 116.541, "b": 123.471 }, { // octave 3 "c": 130.813, "c#": 138.591, "db": 138.591, "d": 146.832, "d#": 155.563, "eb": 155.563, "e": 164.814, "f": 174.614, "f#": 184.997, "gb": 184.997, "g": 195.998, "g#": 207.652, "ab": 207.652, "a": 220, "a#": 233.082, "bb": 233.082, "b": 246.942 }, { // octave 4 "c": 261.626, "c#": 277.183, "db": 277.183, "d": 293.665, "d#": 311.127, "eb": 311.127, "e": 329.628, "f": 349.228, "f#": 369.994, "gb": 369.994, "g": 391.995, "g#": 415.305, "ab": 415.305, "a": 440, "a#": 466.164, "bb": 466.164, "b": 493.883 }, { // octave 5 "c": 523.251, "c#": 554.365, "db": 554.365, "d": 587.33, "d#": 622.254, "eb": 622.254, "e": 659.255, "f": 698.456, "f#": 739.989, "gb": 739.989, "g": 783.991, "g#": 830.609, "ab": 830.609, "a": 880, "a#": 932.328, "bb": 932.328, "b": 987.767 }, { // octave 6 "c": 1046.502, "c#": 1108.731, "db": 1108.731, "d": 1174.659, "d#": 1244.508, "eb": 1244.508, "e": 1318.51, "f": 1396.913, "f#": 1479.978, "gb": 1479.978, "g": 1567.982, "g#": 1661.219, "ab": 1661.219, "a": 1760, "a#": 1864.655, "bb": 1864.655, "b": 1975.533 }, { // octave 7 "c": 2093.005, "c#": 2217.461, "db": 2217.461, "d": 2349.318, "d#": 2489.016, "eb": 2489.016, "e": 2637.021, "f": 2793.826, "f#": 2959.955, "gb": 2959.955, "g": 3135.964, "g#": 3322.438, "ab": 3322.438, "a": 3520, "a#": 3729.31, "bb": 3729.31, "b": 3951.066 }, { // octave 8 "c": 4186.009, "c#": 4434.922, "db": 4434.922, "d": 4698.636, "d#": 4978.032, "eb": 4978.032, "e": 5274.042, "f": 5587.652, "f#": 5919.91, "gb": 5919.91, "g": 6271.928, "g#": 6644.876, "ab": 6644.876, "a": 7040, "a#": 7458.62, "bb": 7458.62, "b": 7902.132 }, { // octave 9 "c": 8372.018, "c#": 8869.844, "db": 8869.844, "d": 9397.272, "d#": 9956.064, "eb": 9956.064, "e": 10548.084, "f": 11175.304, "f#": 11839.82, "gb": 11839.82, "g": 12543.856, "g#": 13289.752, "ab": 13289.752, "a": 14080, "a#": 14917.24, "bb": 14917.24, "b": 15804.264 }] }; // need to create a node in order to kick off the timer in Chrome. tones.context.createGain(); if (typeof define === "function" && define.amd) { define(tones); } else { window.tones = tones; } }(window));
(function () { 'use strict'; angular.module('app.controllers', []) .controller('MapCtrl', MapCtrl) .controller('SitesCtrl', SitesCtrl) .controller('SiteDetailCtrl', SiteDetailCtrl) .controller('ConfigCtrl', ConfigCtrl); MapCtrl.$inject = ['$scope', '$ionicLoading', 'uiGmapGoogleMapApi', '$timeout', 'AuthFactory', '$cordovaFile', '$cordovaGeolocation', '$ionicModal', 'RESTService', '$cordovaCamera', '$cordovaActionSheet', 'UploadFactory']; ConfigCtrl.$inject = ['$scope']; SitesCtrl.$inject = ['$scope', 'RESTService']; SiteDetailCtrl.$inject = ['$scope', '$stateParams', 'Chats']; function MapCtrl($scope, $ionicLoading, uiGmapGoogleMapApi, $timeout, AuthFactory, $cordovaFile, $cordovaGeolocation, $ionicModal, RESTService, $cordovaCamera, $cordovaActionSheet, UploadFactory) { $scope.sites = {}; $scope.img_site = "img/icon_digitalizame.png"; RESTService.all('categories', null, function (response) { $scope.categories = response.results; $scope.categorySelected = response.results[0]; }); refresh(); $scope.refresh = function () { refresh(); }; $scope.locate = function () { initMap(); }; $scope.search = function () { var search = "search=" + document.getElementById("text").value; refresh(search); }; $scope.showModal = function () { $scope.modal.show(); }; //$scope.map = { center: { latitude: 45, longitude: -73 }, zoom: 8 }; $scope.markers = []; $scope.infoVisible = false; $scope.infoBusiness = {}; // Initialize and show infoWindow for business $scope.showInfo = function (marker, eventName, markerModel) { $scope.infoBusiness = markerModel; console.log(markerModel); $scope.infoVisible = true; }; // Hide infoWindow when 'x' is clicked $scope.hideInfo = function () { $scope.infoVisible = false; }; $scope.camera = function () { action_sheet(); }; initMap(); $scope.location = []; function refresh(search) { search = search || null; $ionicLoading.show({ template: 'Actualizando...' }); RESTService.all('sites', search, function (response) { $scope.sites_location = response.results; $ionicLoading.hide(); }); } //region TAKE AND SELECT PHOTO function action_sheet() { var options = { title: 'que quieres hacer?', buttonLabels: ['Tomar una foto', 'Escoger una foto'], addCancelButtonWithLabel: 'Cancelar', androidEnableCancelButton: true, winphoneEnableCancelButton: true }; $cordovaActionSheet.show(options) .then(function (btnIndex) { var index = btnIndex; if (index == 1) { take_photo(); } else if (index == 2) { find_photo(); } }); } function find_photo() { var options = { quality: 100, destinationType: Camera.DestinationType.DATA_URL, sourceType: Camera.PictureSourceType.PHOTOLIBRARY, allowEdit: true, encodingType: Camera.EncodingType.JPEG, //targetWidth: 100, //targetHeight: 100, popoverOptions: CameraPopoverOptions, saveToPhotoAlbum: false, correctOrientation: true }; $cordovaCamera.getPicture(options).then(function (imageData) { $scope.file_image = imageData; var image = document.getElementById('picture'); image.src = "data:image/jpeg;base64," + imageData; console.log(image); }, function (err) { // error }); } function take_photo() { var options = { quality: 100, destinationType: Camera.DestinationType.DATA_URL, sourceType: Camera.PictureSourceType.CAMERA, allowEdit: true, encodingType: Camera.EncodingType.JPEG, //targetWidth: 100, //targetHeight: 100, popoverOptions: CameraPopoverOptions, saveToPhotoAlbum: false, correctOrientation: true }; $cordovaCamera.getPicture(options).then(function (imageData) { //var sourceDirectory = sourcePath.substring(0, sourcePath.lastIndexOf('/') + 1); //var sourceFileName = imageData.substring(imageData.lastIndexOf('/') + 1, imageData.length); //$cordovaFile.copyFile(sourceDirectory, sourceFileName, cordova.file.dataDirectory, sourceFileName) // .then(function (success) { // $scope.file_image = imageData.file.dataDirectory + sourceFileName; //}, function (error) { // console.dir(error); //}); $scope.file_image = imageData; var image = document.getElementById('picture'); image.src = "data:image/jpeg;base64," + imageData; }, function (err) { // error }); } //endregion //region INIT MAP function initMap() { $ionicLoading.show({ template: 'Cargando...' }); uiGmapGoogleMapApi.then(function (maps) { // Don't pass timeout parameter here; that is handled by setTimeout below var posOptions = {enableHighAccuracy: false}; $cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) { $ionicLoading.hide(); initializeMap(position); }, function (error) { $ionicLoading.hide(); initializeMap(); }); }); } var initializeMap = function (position) { if (!position) { // Default to downtown Toronto position = { coords: { latitude: 43.6722780, longitude: -79.3745125 } }; } // TODO add marker on current location $scope.sites.latitude = position.coords.latitude; $scope.sites.longitude = position.coords.longitude; $scope.map = { center: { latitude: position.coords.latitude, longitude: position.coords.longitude }, zoom: 16 }; // Make info window for marker show up above marker $scope.windowOptions = { pixelOffset: { height: -32, width: 0 } }; $scope.marker = { id: 0, coords: { latitude: position.coords.latitude, longitude: position.coords.longitude }, options: {draggable: true}, events: { dragend: function (marker, eventName, args) { var lat = marker.getPosition().lat(); var lon = marker.getPosition().lng(); $scope.sites.latitude = lat; $scope.sites.longitude = lon; //$scope.marker.options = { // draggable: true, // labelContent: "lat: " + $scope.marker.coords.latitude + ' ' + 'lon: ' + $scope.marker.coords.longitude, // labelAnchor: "100 0", // labelClass: "marker-labels" //}; }, click: function (marker, eventName, args) { $scope.showInfo(); } } }; $ionicModal.fromTemplateUrl('modal.html', { scope: $scope, animation: 'slide-in-up' }).then(function (modal) { $scope.modal = modal; }); $scope.saveSite = function () { $ionicLoading.show({ template: 'Guardando...' }); $scope.sites.category = $scope.categorySelected.id; $scope.sites.creator_by = AuthFactory.getUserId(); $scope.sites.picture = $scope.file_image; //UploadFactory.uploadImagePost(URL.ROOT+'/api/v1/sites', file_image, $scope.sites, function (response) { // console.log(response) // //success //}, function (evt) { // //pre // file_image.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total)); //}, function (error) { // //error //}); RESTService.save('sites', $scope.sites, function (response) { $scope.modal.hide(); $scope.sites = {}; refresh(); }); } }; //endregion // Deal with case where user does not make a selection $timeout(function () { if (!$scope.map) { console.log("No confirmation from user, using fallback"); //initializeMap(); } }, 5000); } function SitesCtrl($scope, RESTService) { RESTService.all('sites', null, function (response) { $scope.sites = response.results; }); } function SiteDetailCtrl($scope, $stateParams, Chats) { $scope.chat = Chats.get($stateParams.chatId); } function ConfigCtrl($scope) { $scope.settings = { enableFriends: true }; } })();
(function(){ var currentProject = 0; $('.jcarousel').each(function(){ var carousel = $(this).jcarousel({ wrap: 'circular' }); var left = carousel.parents('.carousel').find('.jcarousel-prev'); var right = carousel.parents('.carousel').find('.jcarousel-next'); left.jcarouselControl({ target: '-=1', carousel: carousel }); right.jcarouselControl({ target: '+=1', carousel: carousel }); }); $('.submenu a').each(function(index){ var projects = $('.project'); var current = $(projects[index]); $(this).click(function(e){ e.preventDefault(); $(projects[currentProject]).addClass('visuallyhidden'); $(projects[index]).removeClass('visuallyhidden'); currentProject = index; }); }); }());
var hive = require('hive'); exports = module.exports = hive.Query.extend({ _name: 'user' });
'use strict'; // 定义模块依赖 var _ = require('lodash'), mkdirp = require('mkdirp'), fs = require('fs'), path = require('path'), errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')), mongoose = require('mongoose'), User = mongoose.model('User'); /** * 更新用户信息 * * @param {Object} req 用户发起的HTTP请求 * @param {Object} res 用户得到的HTTP响应 */ exports.update = function(req, res) { // 获取当前登录用户对象 var user = req.user; // 出于安全因素考虑,删除信息更新请求中针对用户角色的数据定义 // 用户的角色在注册时由系统自动赋予,之后也只可由管理员手动变更 delete req.body.roles; if (user) { // 将用户的更新合并到当前用户对象之中 user = _.extend(user, req.body); user.updated = Date.now(); // 保存用户信息 user.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { // 调用Passport的login函数来建立login session req.login(user, function(err) { if (err) { res.status(400).send(err); } else { res.json(user); } }); } }); } else { res.status(400).send({ message: 'User is not signed in' }); } }; /** * 更新用户头像 * * @param {Object} req 用户发起的HTTP请求 * @param {Object} res 用户得到的HTTP响应 */ exports.changeProfilePicture = function(req, res) { // 获取当前登录用户对象 var user = req.user; // 上传用户头像并更新信息 if (user) { // 图片保存路径 var filepath = 'uploads/profile/' + req.files.file.name; // 确保图片保存的目录存在 mkdirp(path.dirname('./' + filepath), function(error) { if (error) { return res.status(400).send({ message: 'Error occurred while creating folder for the profile picture' }); } else { // 写入图片文件 fs.writeFile(filepath, req.files.file.buffer, function(uploadError) { if (uploadError) { return res.status(400).send({ message: 'Error occurred while uploading profile picture' }); } else { // 用户头像图片上传成功,返回图片URL res.json(filepath); } }); } }); } else { res.status(400).send({ message: 'User is not signed in' }); } }; /** * 获取用户个人信息 * * @param {Object} req 用户发起的HTTP请求 * @param {Object} res 用户得到的HTTP响应 */ exports.me = function(req, res) { // 返回当前登录用户对象 res.json(req.user || null); };
// All other packages automatically depend on this one Package.describe({ summary: "Core Meteor environment", version: '1.2.18-beta.5' }); Package.registerBuildPlugin({ name: "basicFileTypes", sources: ['plugin/basic-file-types.js'] }); Npm.depends({ "meteor-deque": "2.1.0" }); Package.onUse(function (api) { api.use('underscore', ['client', 'server']); api.use('isobuild:compiler-plugin@1.0.0'); api.export('Meteor'); api.addFiles('global.js', ['client', 'server']); api.export('global'); api.addFiles('client_environment.js', 'client'); api.addFiles('server_environment.js', 'server'); // Defined by client_environment.js and server_environment.js. api.export("meteorEnv"); api.addFiles('cordova_environment.js', 'web.cordova'); api.addFiles('helpers.js', ['client', 'server']); api.addFiles('setimmediate.js', ['client', 'server']); api.addFiles('timers.js', ['client', 'server']); api.addFiles('errors.js', ['client', 'server']); api.addFiles('fiber_helpers.js', 'server'); api.addFiles('fiber_stubs_client.js', 'client'); api.addFiles('startup_client.js', ['client']); api.addFiles('startup_server.js', ['server']); api.addFiles('debug.js', ['client', 'server']); api.addFiles('string_utils.js', ['client', 'server']); api.addFiles('test_environment.js', ['client', 'server']); // dynamic variables, bindEnvironment // XXX move into a separate package? api.addFiles('dynamics_browser.js', 'client'); api.addFiles('dynamics_nodejs.js', 'server'); // note server before common. usually it is the other way around, but // in this case server must load first. api.addFiles('url_server.js', 'server'); api.addFiles('url_common.js', ['client', 'server']); // People expect process.exit() to not swallow console output. // On Windows, it sometimes does, so we fix it for all apps and packages api.addFiles('flush-buffers-on-exit-in-windows.js', 'server'); }); Package.onTest(function (api) { api.use(['underscore', 'tinytest', 'test-helpers']); api.addFiles('browser_environment_test.js', 'web.browser'); api.addFiles('client_environment_test.js', 'client'); api.addFiles('cordova_environment_test.js', 'web.cordova'); api.addFiles('server_environment_test.js', 'server'); api.addFiles('helpers_test.js', ['client', 'server']); api.addFiles('dynamics_test.js', ['client', 'server']); api.addFiles('fiber_helpers_test.js', ['server']); api.addFiles('wrapasync_test.js', ['server']); api.addFiles('url_tests.js', ['client', 'server']); api.addFiles('timers_tests.js', ['client', 'server']); api.addFiles('debug_test.js', 'client'); api.addFiles('bare_test_setup.js', 'client', {bare: true}); api.addFiles('bare_tests.js', 'client'); });
/** * Informational Commands * Pokemon Showdown - https://pokemonshowdown.com/ * * These are informational commands. For instance, you can define the command * 'whois' here, then use it by typing /whois into Pokemon Showdown. * * For the API, see chat-plugins/COMMANDS.md * * @license MIT license */ var commands = exports.commands = { //Breakdown Commands banfromheart: 'bfh', bfh: function(target, room, user) { if(user.can('broadcast')){ room.addRaw('<font color="#009999"><b>'+target+'</font></b> was banned from my heart by <font color="#009999"><b>'+user.name+'</font></b>') return false; } }, facepalm: 'face', face: function(target, room, user) { { room.addRaw('<font color="#009999"><b>'+target+'</font></b> has caused <font color="#009999"><b>'+user.name+'</font></b> to facepalm') return false; } }, hastur: function(target, room, user) { if(user.can('broadcast')){ room.addRaw('<div style="background-color:#6688AA;color:white;padding:2px 4px"><img src="http://i215.photobucket.com/albums/cc249/Toke2000/hastur_zpsf1e60cbf.png" height="229" /></div>') return false; } }, wall: 'htmlwall', declare: 'htmlwall', announce: 'htmlwall', htmlwall: function(target, room, user) { if (!user.can('broadcast')){ return this.sendReply('You do not have enough authority to use this command.')}; { room.addRaw('<div class="infobox"><b>Walled by '+user.name+':</font></b> <br />'+target+'</div>') return false; } }, hspeak: function(target, room, user) { if(user.can('broadcast')){ room.addRaw('<font color="#666666">♥</font><font color="#0dff57"><b>Hastur:</font></b> '+target) return false; } }, hme: function(target, room, user) { if(user.can('broadcast')){ room.addRaw('<font color="#0dff57"><b>•</font> +Hastur <i>'+target+'</i>') return false; } }, introduction: 'intro', intro: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('New to the server?<br />' + '- <a href="http://breakdown.forumotion.com/t370-to-our-showdown-users" target="_blank">We Are Not Smogon.</a><br />' + '- <a href="http://breakdown.forumotion.com/t144-5th-gen-tiers" target="_blank">Our Tiers</a><br />' + '- <a href="http://breakdown.forumotion.com/t380-server-rules#1982" target="_blank">Server Rules</a>'); }, forums: 'forum', forum: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('Welcome to Breakdown. Have a lovely time. Here is the site:<br />' + '- <a href="http://breakdown.forumotion.com" target="_blank">breakdown.forumotion.com</a><br />'); }, legendaries: 'legends', legends: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('The truth about legendary Pokemon:<br />' + '- <a href="http://breakdown.forumotion.com/t271-legendaries-explained" target="_blank">Legendary Pokemon are not all banned or broken.</a><br />'); }, cap: 'cang', cang: function(target, room, user) { if (!this.canBroadcast()) return; if (!target) this.sendReplyBox('Breakdown is making its own metagame, with hookers and black jack, Check it out here:<br />' + '- <a href="http://breakdown.forumotion.com/t595-breakdown-cang-submission" target="_blank">CANG Submission</a><br />' + '- <a href="http://breakdowncang.wikia.com/wiki/Breakdown_CANG_Wiki" target="_blank">CANG Wiki</a><br />' + '- Proper formatting to link to a page is /CANG Pokemon, Move, Item, or Ability.<br />' + '- eg: /CANG Abra'); else this.sendReplyBox('- <a href="http://breakdowncang.wikia.com/wiki/'+target+'" target="_blank">'+target+' Wiki Page</a><br />'); }, kingtracebanit: 'kbi', kbi: function(target, room, user) { if(user.can('broadcast')){ room.addRaw('<font color="#009999"><b>Baniteer Kingtrace</font></b> adds the power of justice, granting Captain Ban-it the ability to uphold the rules regardless of your understanding of them. No one knows why.') return false; } }, invalidbanit: 'ibi', ibi: function(target, room, user) { if(user.can('broadcast')){ room.addRaw('<font color="#009999"><b>Baniteer Invalid</font></b> suspends the writ of Habeas Corpus for Captain Ban-it. No one knows why.') return false; } }, frostbanit: 'fbi', fbi: function(target, room, user) { if(user.can('broadcast')){ room.addRaw('<font color="#009999"><b>Baniteer Frost</font></b> removes all accountability from Captain Ban-it. No one knows why.') return false; } }, banitbanit: 'bibi', bibi: function(target, room, user) { if(user.can('broadcast')){ room.addRaw('<b><font color="#009999">Captain Ban-it:</b></font> When your powers combine. I am Captain Ban-it! <font color="#009999"><b>Captain Ban-it</font></b> spiraled so fast he created a tornado that pulled in <b><font color="#009999">'+target+'</b></font> and dispersed the remnants where no one would ever find them.') return false; } }, fantasy: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('Breakdown is hosting a Fantasy Pokemon league, learn everything about it and join here:<br />' + '- <a href="http://breakdown.forumotion.com/t541-fantasy-pokemon-a-breakdown-invention/" target="_blank">Fantasy Pokemon</a><br />'); }, speedtiers: 'st', speed: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('- <a href="http://breakdown.forumotion.com/t492-speed-tiers/" target="_blank">As you requested, Speed Tiers.</a><br />'); }, rule: 'rules', rules: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>Follow the rules:</b><br />' + '<b>No Hate Speech</b> - Hate Speech will get you banned. If your word dehumanizes an entire section of the human race, it is hate speech, if we say it is hate speech it is. If your name contains hatespeech, it will be changed and you will be locked until you comply with the rules.<br />' + '<b>No Spam</b> - Use your best judgement. If it can be said in one line, say it in one line. Do not repeat yourself. Do not post a link that is intended to detract from the server.<br />' + 'a) You may link to Oriserver. You may link to your Youtube, Twitter, etc.<br />' + '<b>Do Not Ask For Auth</b> - Ask and you shall not receive.<br />' + '<b>Do Not Abuse Auth</b> - Do not ban, mute, or kick people that do not deserve it. Using auth when it is not necessary is also abuse because it is showing off that you are auth.<br />'+ '<b>Do Not Be An Attention Whore</b> - If everyone is sick of hearing about your stupid life, and or relationship, and or other thing that revolves around you, shut the hell up about it.<br />' + '<b>No Minimodding</b> - Minimodding is telling people what the rules are when you are not auth or attempt to help a mod by bullying a user who broke rules. Chances are you are only going to make the infraction seem stupid, so shut up and let the staff work.<br />' + '<b>No Harassment</b> - If you do not know what harassment is, look it up. And do not antagonize people then say they are harassing you, we will ban you. (see "Do Not Be An Attention Whore")<br />' + '<b>Keep Arguments In PMs</b> - Extended personal arguments should be moved to private messages. Discussions and debates are fine in main, but if things escelate beyond civil levels take it to PMs. Refusal to do so when asked may result in a ban. </div>'); }, rpstiff: 'rpstuff', rpstuff: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<b>Role Playing Rules:</b><br />' + '<b>Do Not Break Server Rules</b> - Type /rules to read the rules, Do not think that I have come to abolish the law or the prophets.<br />' + '<b>In Character</b> - When your character is talking, just type what s/he is saying with no special formatting.<br />' + '<b>Character Actions</b> - Use /me to denote character actions.<br />' + '<b>Event Narration</b> - If something is happenning that cannot be explained through other means, put it in quotation marks.<br />' + '<b>Out of Character</b> - when you speak out of character, put what you say in parenthesis.<br />'+ '<b>Room Master</b> - Not every RP needs a Room Master, a room master narrates the events and almost exclusively uses quotation marks. The Room Master may want to use a die to decide the outcomes of actions. If so use a 20 sided die or set random.org to min 1 max 20 and treat it as a die roll. 1 means something bad happenned to the person performing the action, 20 means crit so think of something unlikely and beneficial.<br />'+ '<b>No Godmodding</b> - You cannot be invincible, reality warping, or plot centering for no reason what so ever.</div>'); }, banlist: 'tiers', tiers: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<a href="http://breakdown.forumotion.com/t571-gen-6-tiers" target="_blank">Gen 6 Tiers</a><br /><a href="http://breakdown.forumotion.com/t144-5th-gen-tiers" target="_blank">Gen 5 Tiers</a>'); }, mnt: 'mynameto', mynameto: function(target, room, user) { if (!target || target.length > 19) { return this.sendReply('No valid name was specified.'); } { var entry = ''+user.name+' changed their name to '+target+'(imp) by using /mynameto or /mnt.'; this.privateModCommand('(' + entry + ')'); user.forceRename(target+'(imp)', undefined, true); } }, donate: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('<center><div><img src="http://catputer.com/joe/breakdown/bdown2.png "></div><div><a href="http://breakdown.forumotion.com" border="0"><img src="http://catputer.com/joe/breakdown/bdown-forums.png"></a><a href="http://breakdown.forumotion.com/t571-gen-6-tiers" border="0"><img src="http://catputer.com/joe/breakdown/bdown-tiers.png"></a></div>CANG: <a href="http://breakdown.forumotion.com/t595-breakdown-cang-submission" target="_blank">Submission</a> <a href="http://breakdowncang.wikia.com/wiki/Breakdown_CANG_Wiki" target="_blank">Wiki</a> - <a href="http://breakdown.forumotion.com/t637-breakdown-clan-prize-player-league" target="_blank">Clan Season</a> - <a href="http://breakdown.forumotion.com/t659-july-2014-tier-nominations" target="_blank">Tier Noms</a></center>'); }, //End Breakdown Commands ip: 'whois', rooms: 'whois', alt: 'whois', alts: 'whois', whoare: 'whois', whois: function (target, room, user, connection, cmd) { var targetUser = this.targetUserOrSelf(target, user.group === ' '); if (!targetUser) { return this.sendReply("User " + this.targetUsername + " not found."); } this.sendReply("|raw|User: " + targetUser.name + (!targetUser.connected ? ' <font color="gray"><em>(offline)</em></font>' : '')); if (user.can('alts', targetUser)) { var alts = targetUser.getAlts(true); var output = Object.keys(targetUser.prevNames).join(", "); if (output) this.sendReply("Previous names: " + output); for (var j = 0; j < alts.length; ++j) { var targetAlt = Users.get(alts[j]); if (!targetAlt.named && !targetAlt.connected) continue; if (targetAlt.group === '~' && user.group !== '~') continue; this.sendReply("|raw|Alt: " + targetAlt.name + (!targetAlt.connected ? ' <font color="gray"><em>(offline)</em></font>' : '')); output = Object.keys(targetAlt.prevNames).join(", "); if (output) this.sendReply("Previous names: " + output); } if (targetUser.locked) { switch (targetUser.locked) { case '#dnsbl': this.sendReply("Locked: IP is in a DNS-based blacklist. "); break; case '#range': this.sendReply("Locked: IP or host is in a temporary range-lock."); break; case '#hostfilter': this.sendReply("Locked: host is permanently locked for being a proxy."); break; default: this.sendReply("Locked under the username: " + targetUser.locked); } } } if (Config.groups[targetUser.group] && Config.groups[targetUser.group].name) { this.sendReply("Group: " + Config.groups[targetUser.group].name + " (" + targetUser.group + ")"); } if (targetUser.isSysop) { this.sendReply("(Pok\xE9mon Showdown System Operator)"); } if (!targetUser.registered) { this.sendReply("(Unregistered)"); } if ((cmd === 'ip' || cmd === 'whoare') && (user.can('ip', targetUser) || user === targetUser)) { var ips = Object.keys(targetUser.ips); this.sendReply("IP" + ((ips.length > 1) ? "s" : "") + ": " + ips.join(", ") + (user.group !== ' ' && targetUser.latestHost ? "\nHost: " + targetUser.latestHost : "")); } var publicrooms = "In rooms: "; var hiddenrooms = "In hidden rooms: "; var first = true; var hiddencount = 0; for (var i in targetUser.roomCount) { var targetRoom = Rooms.get(i); if (i === 'global' || targetRoom.isPrivate === true) continue; var output = (targetRoom.auth && targetRoom.auth[targetUser.userid] ? targetRoom.auth[targetUser.userid] : '') + '<a href="/' + i + '" room="' + i + '">' + i + '</a>'; if (targetRoom.isPrivate) { if (hiddencount > 0) hiddenrooms += " | "; ++hiddencount; hiddenrooms += output; } else { if (!first) publicrooms += " | "; first = false; publicrooms += output; } } this.sendReply('|raw|' + publicrooms); if (cmd === 'whoare' && user.can('lock') && hiddencount > 0) { this.sendReply('|raw|' + hiddenrooms); } }, whoishelp: ["/whois - Get details on yourself: alts, group, IP address, and rooms.", "/whois [username] - Get details on a username: alts (Requires: % @ & ~), group, IP address (Requires: @ & ~), and rooms."], ipsearchall: 'ipsearch', hostsearch: 'ipsearch', ipsearch: function (target, room, user, connection, cmd) { if (!target.trim()) return this.parse('/help ipsearch'); if (!this.can('rangeban')) return; var results = []; var isAll = (cmd === 'ipsearchall'); if (/[a-z]/.test(target)) { // host this.sendReply("Users with host " + target + ":"); for (var userid in Users.users) { var curUser = Users.users[userid]; if (!curUser.latestHost || !curUser.latestHost.endsWith(target)) continue; if (results.push((curUser.connected ? " \u25C9 " : " \u25CC ") + " " + curUser.name) > 100 && !isAll) { return this.sendReply("More than 100 users match the specified IP range. Use /ipsearchall to retrieve the full list."); } } } else if (target.slice(-1) === '*') { // IP range this.sendReply("Users in IP range " + target + ":"); target = target.slice(0, -1); for (var userid in Users.users) { var curUser = Users.users[userid]; if (!curUser.latestIp.startsWith(target)) continue; if (results.push((curUser.connected ? " \u25C9 " : " \u25CC ") + " " + curUser.name) > 100 && !isAll) { return this.sendReply("More than 100 users match the specified IP range. Use /ipsearchall to retrieve the full list."); } } } else { this.sendReply("Users with IP " + target + ":"); for (var userid in Users.users) { var curUser = Users.users[userid]; if (curUser.latestIp === target) { results.push((curUser.connected ? " \u25C9 " : " \u25CC ") + " " + curUser.name); } } } if (!results.length) return this.sendReply("No results found."); return this.sendReply(results.join('; ')); }, ipsearchhelp: ["/ipsearch [ip|range|host] - Find all users with specified IP, IP range, or host (Requires: & ~)"], /********************************************************* * Shortcuts *********************************************************/ inv: 'invite', invite: function (target, room, user) { target = this.splitTarget(target); if (!this.targetUser) { return this.sendReply("User " + this.targetUsername + " not found."); } var targetRoom = (target ? Rooms.search(target) : room); if (!targetRoom) { return this.sendReply("Room " + target + " not found."); } return this.parse('/msg ' + this.targetUsername + ', /invite ' + targetRoom.id); }, invitehelp: ["/invite [username], [roomname] - Invites the player [username] to join the room [roomname]."], /********************************************************* * Data Search Tools *********************************************************/ pstats: 'data', stats: 'data', dex: 'data', pokedex: 'data', data: function (target, room, user, connection, cmd) { if (!this.canBroadcast()) return; var buffer = ''; var targetId = toId(target); if (!targetId) return this.parse('/help data'); if (targetId === '' + parseInt(targetId)) { for (var p in Tools.data.Pokedex) { var pokemon = Tools.getTemplate(p); if (pokemon.num === parseInt(target)) { target = pokemon.species; targetId = pokemon.id; break; } } } var newTargets = Tools.dataSearch(target); var showDetails = (cmd === 'dt' || cmd === 'details'); if (newTargets && newTargets.length) { for (var i = 0; i < newTargets.length; ++i) { if (newTargets[i].id !== targetId && !Tools.data.Aliases[targetId] && !i) { buffer = "No Pokemon, item, move, ability or nature named '" + target + "' was found. Showing the data of '" + newTargets[0].name + "' instead.\n"; } if (newTargets[i].searchType === 'nature') { buffer += "" + newTargets[i].name + " nature: "; if (newTargets[i].plus) { var statNames = {'atk': "Attack", 'def': "Defense", 'spa': "Special Attack", 'spd': "Special Defense", 'spe': "Speed"}; buffer += "+10% " + statNames[newTargets[i].plus] + ", -10% " + statNames[newTargets[i].minus] + "."; } else { buffer += "No effect."; } return this.sendReply(buffer); } else { buffer += '|c|~|/data-' + newTargets[i].searchType + ' ' + newTargets[i].name + '\n'; } } } else { return this.sendReply("No Pokemon, item, move, ability or nature named '" + target + "' was found. (Check your spelling?)"); } if (showDetails) { var details; var isSnatch = false; var isMirrorMove = false; if (newTargets[0].searchType === 'pokemon') { var pokemon = Tools.getTemplate(newTargets[0].name); var weighthit = 20; if (pokemon.weightkg >= 200) { weighthit = 120; } else if (pokemon.weightkg >= 100) { weighthit = 100; } else if (pokemon.weightkg >= 50) { weighthit = 80; } else if (pokemon.weightkg >= 25) { weighthit = 60; } else if (pokemon.weightkg >= 10) { weighthit = 40; } details = { "Dex#": pokemon.num, "Gen": pokemon.gen, "Height": pokemon.heightm + " m", "Weight": pokemon.weightkg + " kg <em>(" + weighthit + " BP)</em>", "Dex Colour": pokemon.color, "Egg Group(s)": pokemon.eggGroups.join(", ") }; if (!pokemon.evos.length) { details["<font color=#585858>Does Not Evolve</font>"] = ""; } else { details["Evolution"] = pokemon.evos.map(function (evo) { evo = Tools.getTemplate(evo); return evo.name + " (" + evo.evoLevel + ")"; }).join(", "); } } else if (newTargets[0].searchType === 'move') { var move = Tools.getMove(newTargets[0].name); details = { "Priority": move.priority, "Gen": move.gen }; if (move.secondary || move.secondaries) details["<font color=black>&#10003; Secondary effect</font>"] = ""; if (move.flags['contact']) details["<font color=black>&#10003; Contact</font>"] = ""; if (move.flags['sound']) details["<font color=black>&#10003; Sound</font>"] = ""; if (move.flags['bullet']) details["<font color=black>&#10003; Bullet</font>"] = ""; if (move.flags['pulse']) details["<font color=black>&#10003; Pulse</font>"] = ""; if (!move.flags['protect'] && !/(ally|self)/i.test(move.target)) details["<font color=black>&#10003; Bypasses Protect</font>"] = ""; if (move.flags['authentic']) details["<font color=black>&#10003; Bypasses Substitutes</font>"] = ""; if (move.flags['defrost']) details["<font color=black>&#10003; Thaws user</font>"] = ""; if (move.flags['bite']) details["<font color=black>&#10003; Bite</font>"] = ""; if (move.flags['punch']) details["<font color=black>&#10003; Punch</font>"] = ""; if (move.flags['powder']) details["<font color=black>&#10003; Powder</font>"] = ""; if (move.flags['reflectable']) details["<font color=black>&#10003; Bounceable</font>"] = ""; if (move.flags['gravity']) details["<font color=black>&#10007; Suppressed by Gravity</font>"] = ""; if (move.id === 'snatch') isSnatch = true; if (move.id === 'mirrormove') isMirrorMove = true; details["Target"] = { 'normal': "One Adjacent Pokemon", 'self': "User", 'adjacentAlly': "One Ally", 'adjacentAllyOrSelf': "User or Ally", 'adjacentFoe': "One Adjacent Opposing Pokemon", 'allAdjacentFoes': "All Adjacent Opponents", 'foeSide': "Opposing Side", 'allySide': "User's Side", 'allyTeam': "User's Side", 'allAdjacent': "All Adjacent Pokemon", 'any': "Any Pokemon", 'all': "All Pokemon" }[move.target] || "Unknown"; } else if (newTargets[0].searchType === 'item') { var item = Tools.getItem(newTargets[0].name); details = { "Gen": item.gen }; if (item.fling) { details["Fling Base Power"] = item.fling.basePower; if (item.fling.status) details["Fling Effect"] = item.fling.status; if (item.fling.volatileStatus) details["Fling Effect"] = item.fling.volatileStatus; if (item.isBerry) details["Fling Effect"] = "Activates the Berry's effect on the target."; if (item.id === 'whiteherb') details["Fling Effect"] = "Restores the target's negative stat stages to 0."; if (item.id === 'mentalherb') details["Fling Effect"] = "Removes the effects of Attract, Disable, Encore, Heal Block, Taunt, and Torment from the target."; } else { details["Fling"] = "This item cannot be used with Fling."; } if (item.naturalGift) { details["Natural Gift Type"] = item.naturalGift.type; details["Natural Gift Base Power"] = item.naturalGift.basePower; } } else { details = {}; } buffer += '|raw|<font size="1">' + Object.keys(details).map(function (detail) { return '<font color=#585858>' + detail + (details[detail] !== '' ? ':</font> ' + details[detail] : '</font>'); }).join("&nbsp;|&ThickSpace;") + '</font>'; if (isSnatch) buffer += '&nbsp;|&ThickSpace;<a href="http://pokemonshowdown.com/dex/moves/snatch"><font size="1">Snatchable Moves</font></a>'; if (isMirrorMove) buffer += '&nbsp;|&ThickSpace;<a href="http://pokemonshowdown.com/dex/moves/mirrormove"><font size="1">Mirrorable Moves</font></a>'; } this.sendReply(buffer); }, datahelp: ["/data [pokemon/item/move/ability] - Get details on this pokemon/item/move/ability/nature.", "!data [pokemon/item/move/ability] - Show everyone these details. Requires: + % @ & ~"], dt: 'details', details: function () { CommandParser.commands.data.apply(this, arguments); }, detailshelp: ["/details [pokemon] - Get additional details on this pokemon/item/move/ability/nature.", "!details [pokemon] - Show everyone these details. Requires: + % @ & ~"], ds: 'dexsearch', dsearch: 'dexsearch', dexsearch: function (target, room, user) { if (!this.canBroadcast()) return; if (!target) return this.parse('/help dexsearch'); var targets = target.split(','); var searches = {}; var allTiers = {'uber':1, 'ou':1, 'bl':1, 'uu':1, 'bl2':1, 'ru':1, 'bl3':1, 'nu':1, 'bl4':1, 'pu':1, 'nfe':1, 'lc uber':1, 'lc':1, 'cap':1}; var allColours = {'green':1, 'red':1, 'blue':1, 'white':1, 'brown':1, 'yellow':1, 'purple':1, 'pink':1, 'gray':1, 'black':1}; var allStats = {'hp':1, 'atk':1, 'def':1, 'spa':1, 'spd':1, 'spe':1}; var showAll = false; var megaSearch = null; var output = 10; var categories = ['gen', 'tier', 'color', 'types', 'ability', 'stats', 'compileLearnsets', 'moves', 'recovery', 'priority']; for (var i = 0; i < targets.length; i++) { var isNotSearch = false; target = targets[i].trim().toLowerCase(); if (target.charAt(0) === '!') { isNotSearch = true; target = target.substr(1); } var targetAbility = Tools.getAbility(targets[i]); if (targetAbility.exists) { if (!searches['ability']) searches['ability'] = {}; if (Object.count(searches['ability'], true) === 1 && !isNotSearch) return this.sendReplyBox("Specify only one ability."); if ((searches['ability'][targetAbility.name] && isNotSearch) || (searches['ability'][targetAbility.name] === false && !isNotSearch)) return this.sendReplyBox("A search cannot both exclude and include an ability."); searches['ability'][targetAbility.name] = !isNotSearch; continue; } if (target in allTiers) { if (!searches['tier']) searches['tier'] = {}; if ((searches['tier'][target] && isNotSearch) || (searches['tier'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a tier.'); searches['tier'][target] = !isNotSearch; continue; } if (target in allColours) { if (!searches['color']) searches['color'] = {}; if ((searches['color'][target] && isNotSearch) || (searches['color'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a color.'); searches['color'][target] = !isNotSearch; continue; } if (target.substr(0, 3) === 'gen' && Number.isInteger(parseFloat(target.substr(3)))) target = target.substr(3).trim(); var targetInt = parseInt(target); if (0 < targetInt && targetInt < 7) { if (!searches['gen']) searches['gen'] = {}; if ((searches['gen'][target] && isNotSearch) || (searches['gen'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a generation.'); searches['gen'][target] = !isNotSearch; continue; } if (target === 'all') { if (this.broadcasting) return this.sendReplyBox("A search with the parameter 'all' cannot be broadcast."); showAll = true; continue; } if (target === 'megas' || target === 'mega') { if ((megaSearch && isNotSearch) || (megaSearch === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include Mega Evolutions.'); megaSearch = !isNotSearch; continue; } if (target === 'recovery') { if ((searches['recovery'] && isNotSearch) || (searches['recovery'] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and recovery moves.'); searches['recovery'] = !isNotSearch; continue; } if (target === 'priority') { if ((searches['priority'] && isNotSearch) || (searches['priority'] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and recovery moves.'); searches['priority'] = !isNotSearch; continue; } var targetMove = Tools.getMove(target); if (targetMove.exists) { if (!searches['moves']) searches['moves'] = {}; if (Object.count(searches['moves'], true) === 4 && !isNotSearch) return this.sendReplyBox("Specify a maximum of 4 moves."); if ((searches['moves'][targetMove.id] && isNotSearch) || (searches['moves'][targetMove.id] === false && !isNotSearch)) return this.sendReplyBox("A search cannot both exclude and include a move."); searches['moves'][targetMove.id] = !isNotSearch; continue; } var typeIndex = target.indexOf(' type'); if (typeIndex >= 0) { target = target.charAt(0).toUpperCase() + target.substring(1, typeIndex); if (target in Tools.data.TypeChart) { if (!searches['types']) searches['types'] = {}; if (Object.count(searches['types'], true) === 2 && !isNotSearch) return this.sendReplyBox("Specify a maximum of two types."); if ((searches['types'][target] && isNotSearch) || (searches['types'][target] === false && !isNotSearch)) return this.sendReplyBox("A search cannot both exclude and include a type."); searches['types'][target] = !isNotSearch; continue; } } var inequality = target.search(/>|<|=/); if (inequality >= 0) { if (isNotSearch) return this.sendReplyBox("You cannot use the negation symbol '!' in stat ranges."); inequality = target.charAt(inequality); var targetParts = target.replace(/\s/g, '').split(inequality); var numSide, statSide, direction; if (!isNaN(targetParts[0])) { numSide = 0; statSide = 1; switch (inequality) { case '>': direction = 'less'; break; case '<': direction = 'greater'; break; case '=': direction = 'equal'; break; } } else if (!isNaN(targetParts[1])) { numSide = 1; statSide = 0; switch (inequality) { case '<': direction = 'less'; break; case '>': direction = 'greater'; break; case '=': direction = 'equal'; break; } } else { return this.sendReplyBox("No value given to compare with '" + Tools.escapeHTML(target) + "'."); } var stat = targetParts[statSide]; switch (toId(targetParts[statSide])) { case 'attack': stat = 'atk'; break; case 'defense': stat = 'def'; break; case 'specialattack': stat = 'spa'; break; case 'spatk': stat = 'spa'; break; case 'specialdefense': stat = 'spd'; break; case 'spdef': stat = 'spd'; break; case 'speed': stat = 'spe'; break; } if (!(stat in allStats)) return this.sendReplyBox("'" + Tools.escapeHTML(target) + "' did not contain a valid stat."); if (!searches['stats']) searches['stats'] = {}; if (direction === 'equal') { if (searches['stats'][stat]) return this.sendReplyBox("Invalid stat range for " + stat + "."); searches['stats'][stat] = {}; searches['stats'][stat]['less'] = parseFloat(targetParts[numSide]); searches['stats'][stat]['greater'] = parseFloat(targetParts[numSide]); } else { if (!searches['stats'][stat]) searches['stats'][stat] = {}; if (searches['stats'][stat][direction]) return this.sendReplyBox("Invalid stat range for " + stat + "."); searches['stats'][stat][direction] = parseFloat(targetParts[numSide]); } continue; } return this.sendReplyBox("'" + Tools.escapeHTML(target) + "' could not be found in any of the search categories."); } if (showAll && Object.size(searches) === 0 && megaSearch === null) return this.sendReplyBox("No search parameters other than 'all' were found. Try '/help dexsearch' for more information on this command."); var dex = {}; for (var pokemon in Tools.data.Pokedex) { var template = Tools.getTemplate(pokemon); var megaSearchResult = (megaSearch === null || (megaSearch === true && template.isMega) || (megaSearch === false && !template.isMega)); if (template.tier !== 'Unreleased' && template.tier !== 'Illegal' && (template.tier !== 'CAP' || (searches['tier'] && searches['tier']['cap'])) && megaSearchResult) { dex[pokemon] = template; } } //Only construct full learnsets for Pokemon if learnsets are used in the search if (searches.moves || searches.recovery || searches.priority) searches['compileLearnsets'] = true; for (var cat = 0; cat < categories.length; cat++) { var search = categories[cat]; if (!searches[search]) continue; switch (search) { case 'types': for (var mon in dex) { if (Object.count(searches[search], true) === 2) { if (!(searches[search][dex[mon].types[0]]) || !(searches[search][dex[mon].types[1]])) delete dex[mon]; } else { if (searches[search][dex[mon].types[0]] === false || searches[search][dex[mon].types[1]] === false || (Object.count(searches[search], true) > 0 && (!(searches[search][dex[mon].types[0]]) && !(searches[search][dex[mon].types[1]])))) delete dex[mon]; } } break; case 'tier': for (var mon in dex) { if ('lc' in searches[search]) { // some LC legal Pokemon are stored in other tiers (Ferroseed/Murkrow etc) // this checks for LC legality using the going criteria, instead of dex[mon].tier var isLC = (dex[mon].evos && dex[mon].evos.length > 0) && !dex[mon].prevo && dex[mon].tier !== "LC Uber" && Tools.data.Formats['lc'].banlist.indexOf(dex[mon].species) < 0; if ((searches[search]['lc'] && !isLC) || (!searches[search]['lc'] && isLC)) { delete dex[mon]; continue; } } if (searches[search][String(dex[mon][search]).toLowerCase()] === false) { delete dex[mon]; } else if (Object.count(searches[search], true) > 0 && !searches[search][String(dex[mon][search]).toLowerCase()]) delete dex[mon]; } break; case 'gen': case 'color': for (var mon in dex) { if (searches[search][String(dex[mon][search]).toLowerCase()] === false) { delete dex[mon]; } else if (Object.count(searches[search], true) > 0 && !searches[search][String(dex[mon][search]).toLowerCase()]) delete dex[mon]; } break; case 'ability': for (var mon in dex) { for (var ability in searches[search]) { var needsAbility = searches[search][ability]; var hasAbility = Object.count(dex[mon].abilities, ability) > 0; if (hasAbility !== needsAbility) { delete dex[mon]; break; } } } break; case 'compileLearnsets': for (var mon in dex) { var template = dex[mon]; if (!template.learnset) template = Tools.getTemplate(template.baseSpecies); if (!template.learnset) continue; var fullLearnset = template.learnset; while (template.prevo) { template = Tools.getTemplate(template.prevo); for (var move in template.learnset) { if (!fullLearnset[move]) fullLearnset[move] = template.learnset[move]; } } dex[mon].learnset = fullLearnset; } break; case 'moves': for (var mon in dex) { if (!dex[mon].learnset) continue; for (var move in searches[search]) { var canLearn = (dex[mon].learnset.sketch && ['chatter', 'struggle', 'magikarpsrevenge'].indexOf(move) < 0) || dex[mon].learnset[move]; if ((!canLearn && searches[search][move]) || (searches[search][move] === false && canLearn)) { delete dex[mon]; break; } } } break; case 'recovery': for (var mon in dex) { if (!dex[mon].learnset) continue; var recoveryMoves = ["recover", "roost", "moonlight", "morningsun", "synthesis", "milkdrink", "slackoff", "softboiled", "wish", "healorder"]; var canLearn = false; for (var i = 0; i < recoveryMoves.length; i++) { canLearn = (dex[mon].learnset.sketch) || dex[mon].learnset[recoveryMoves[i]]; if (canLearn) break; } if ((!canLearn && searches[search]) || (searches[search] === false && canLearn)) delete dex[mon]; } break; case 'priority': var priorityMoves = []; for (var move in Tools.data.Movedex) { var moveData = Tools.getMove(move); if (moveData.category === "Status") continue; if (moveData.priority > 0) priorityMoves.push(move); } for (var mon in dex) { if (!dex[mon].learnset) continue; var canLearn = false; for (var i = 0; i < priorityMoves.length; i++) { canLearn = (dex[mon].learnset.sketch) || dex[mon].learnset[priorityMoves[i]]; if (canLearn) break; } if ((!canLearn && searches[search]) || (searches[search] === false && canLearn)) delete dex[mon]; } break; case 'stats': for (var stat in searches[search]) { for (var mon in dex) { if (typeof searches[search][stat].less === 'number') { if (dex[mon].baseStats[stat] > searches[search][stat].less) { delete dex[mon]; continue; } } if (typeof searches[search][stat].greater === 'number') { if (dex[mon].baseStats[stat] < searches[search][stat].greater) { delete dex[mon]; continue; } } } } break; default: return this.sendReplyBox("Something broke! PM SolarisFox here or on the Smogon forums with the command you tried."); } } var results = []; for (var mon in dex) { if (dex[mon].baseSpecies && results.indexOf(dex[mon].baseSpecies) >= 0) continue; results.push(dex[mon].species); } var resultsStr = ""; if (results.length > 0) { if (showAll || results.length <= output + 5) { results.sort(); resultsStr = results.join(", "); } else { resultsStr = results.slice(0, output).join(", ") + ", and " + string(results.length - output) + " more. <font color=#999999>Redo the search with 'all' as a search parameter to show all results.</font>"; } } else { resultsStr = "No Pok&eacute;mon found."; } return this.sendReplyBox(resultsStr); }, dexsearchhelp: ["/dexsearch [type], [move], [move], ... - Searches for Pokemon that fulfill the selected criteria", "Search categories are: type, tier, color, moves, ability, gen, recovery, priority, stat.", "Valid colors are: green, red, blue, white, brown, yellow, purple, pink, gray and black.", "Valid tiers are: Uber/OU/BL/UU/BL2/RU/BL3/NU/PU/NFE/LC/CAP.", "Types must be followed by ' type', e.g., 'dragon type'.", "Inequality ranges use the characters '>' and '<' though they behave as '≥' and '≤', e.g., 'speed > 100' searches for all Pokemon equal to and greater than 100 speed.", "Parameters can be excluded through the use of '!', e.g., '!water type' excludes all water types.", "The parameter 'mega' can be added to search for Mega Evolutions only, and the parameters 'FE' or 'NFE' can be added to search fully or not-fully evolved Pokemon only.", "The order of the parameters does not matter."], ms: 'movesearch', msearch: 'movesearch', movesearch: function (target, room, user) { if (!this.canBroadcast()) return; if (!target) return this.parse('/help movesearch'); var targets = target.split(','); var searches = {}; var allCategories = {'physical':1, 'special':1, 'status':1}; var allProperties = {'basePower':1, 'accuracy':1, 'priority':1, 'pp':1}; var allFlags = {'bite':1, 'bullet':1, 'contact':1, 'defrost':1, 'powder':1, 'pulse':1, 'punch':1, 'secondary':1, 'snatch':1, 'sound':1}; var allStatus = {'psn':1, 'tox':1, 'brn':1, 'par':1, 'frz':1, 'slp':1}; var allVolatileStatus = {'flinch':1, 'confusion':1, 'partiallytrapped':1}; var allBoosts = {'hp':1, 'atk':1, 'def':1, 'spa':1, 'spd':1, 'spe':1, 'accuracy':1, 'evasion':1}; var showAll = false; var output = 10; var lsetData = {}; var targetMon = ''; for (var i = 0; i < targets.length; i++) { var isNotSearch = false; target = targets[i].toLowerCase().trim(); if (target.charAt(0) === '!') { isNotSearch = true; target = target.substr(1); } var typeIndex = target.indexOf(' type'); if (typeIndex >= 0) { target = target.charAt(0).toUpperCase() + target.substring(1, typeIndex); if (!(target in Tools.data.TypeChart)) return this.sendReplyBox("Type '" + Tools.escapeHTML(target) + "' not found."); if (!searches['type']) searches['type'] = {}; if ((searches['type'][target] && isNotSearch) || (searches['type'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a type.'); searches['type'][target] = !isNotSearch; continue; } if (target in allCategories) { target = target.charAt(0).toUpperCase() + target.substr(1); if (!searches['category']) searches['category'] = {}; if ((searches['category'][target] && isNotSearch) || (searches['category'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a category.'); searches['category'][target] = !isNotSearch; continue; } if (target in allFlags) { if (!searches['flags']) searches['flags'] = {}; if ((searches['flags'][target] && isNotSearch) || (searches['flags'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include \'' + target + '\'.'); searches['flags'][target] = !isNotSearch; continue; } if (target === 'all') { if (this.broadcasting) return this.sendReplyBox("A search with the parameter 'all' cannot be broadcast."); showAll = true; continue; } if (target === 'recovery') { if (!searches['recovery']) { searches['recovery'] = !isNotSearch; } else if ((searches['recovery'] && isNotSearch) || (searches['recovery'] === false && !isNotSearch)) { return this.sendReplyBox('A search cannot both exclude and include recovery moves.'); } continue; } var template = Tools.getTemplate(target); if (template.exists) { if (Object.size(lsetData) !== 0) return this.sendReplyBox("A search can only include one Pokemon learnset."); if (!template.learnset) template = Tools.getTemplate(template.baseSpecies); lsetData = template.learnset; targetMon = template.name; while (template.prevo) { template = Tools.getTemplate(template.prevo); for (var move in template.learnset) { if (!lsetData[move]) lsetData[move] = template.learnset[move]; } } continue; } var inequality = target.search(/>|<|=/); if (inequality >= 0) { if (isNotSearch) return this.sendReplyBox("You cannot use the negation symbol '!' in quality ranges."); inequality = target.charAt(inequality); var targetParts = target.replace(/\s/g, '').split(inequality); var numSide, propSide, direction; if (!isNaN(targetParts[0])) { numSide = 0; propSide = 1; switch (inequality) { case '>': direction = 'less'; break; case '<': direction = 'greater'; break; case '=': direction = 'equal'; break; } } else if (!isNaN(targetParts[1])) { numSide = 1; propSide = 0; switch (inequality) { case '<': direction = 'less'; break; case '>': direction = 'greater'; break; case '=': direction = 'equal'; break; } } else { return this.sendReplyBox("No value given to compare with '" + Tools.escapeHTML(target) + "'."); } var prop = targetParts[propSide]; switch (toId(targetParts[propSide])) { case 'basepower': prop = 'basePower'; break; case 'bp': prop = 'basePower'; break; case 'acc': prop = 'accuracy'; break; } if (!(prop in allProperties)) return this.sendReplyBox("'" + Tools.escapeHTML(target) + "' did not contain a valid property."); if (!searches['property']) searches['property'] = {}; if (direction === 'equal') { if (searches['property'][prop]) return this.sendReplyBox("Invalid property range for " + prop + "."); searches['property'][prop] = {}; searches['property'][prop]['less'] = parseFloat(targetParts[numSide]); searches['property'][prop]['greater'] = parseFloat(targetParts[numSide]); } else { if (!searches['property'][prop]) searches['property'][prop] = {}; if (searches['property'][prop][direction]) { return this.sendReplyBox("Invalid property range for " + prop + "."); } else { searches['property'][prop][direction] = parseFloat(targetParts[numSide]); } } continue; } if (target.substr(0, 8) === 'priority') { var sign = ''; target = target.substr(8).trim(); if (target === "+") { sign = 'greater'; } else if (target === "-") { sign = 'less'; } else { return this.sendReplyBox("Priority type '" + target + "' not recognized."); } if (!searches['property']) searches['property'] = {}; if (searches['property']['priority']) { return this.sendReplyBox("Priority cannot be set with both shorthand and inequality range."); } else { searches['property']['priority'] = {}; searches['property']['priority'][sign] = (sign === 'less' ? -1 : 1); } continue; } if (target.substr(0, 7) === 'boosts ') { switch (target.substr(7)) { case 'attack': target = 'atk'; break; case 'defense': target = 'def'; break; case 'specialattack': target = 'spa'; break; case 'spatk': target = 'spa'; break; case 'specialdefense': target = 'spd'; break; case 'spdef': target = 'spd'; break; case 'speed': target = 'spe'; break; case 'acc': target = 'accuracy'; break; case 'evasiveness': target = 'evasion'; break; default: target = target.substr(7); } if (!(target in allBoosts)) return this.sendReplyBox("'" + Tools.escapeHTML(target.substr(7)) + "' is not a recognized stat."); if (!searches['boost']) searches['boost'] = {}; if ((searches['boost'][target] && isNotSearch) || (searches['boost'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a stat boost.'); searches['boost'][target] = !isNotSearch; continue; } var oldTarget = target; if (target.charAt(target.length - 1) === 's') target = target.substr(0, target.length - 1); switch (target) { case 'toxic': target = 'tox'; break; case 'poison': target = 'psn'; break; case 'burn': target = 'brn'; break; case 'paralyze': target = 'par'; break; case 'freeze': target = 'frz'; break; case 'sleep': target = 'slp'; break; case 'confuse': target = 'confusion'; break; case 'trap': target = 'partiallytrapped'; break; case 'flinche': target = 'flinch'; break; } if (target in allStatus) { if (!searches['status']) searches['status'] = {}; if ((searches['status'][target] && isNotSearch) || (searches['status'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a status.'); searches['status'][target] = !isNotSearch; continue; } if (target in allVolatileStatus) { if (!searches['volatileStatus']) searches['volatileStatus'] = {}; if ((searches['volatileStatus'][target] && isNotSearch) || (searches['volatileStatus'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a volitile status.'); searches['volatileStatus'][target] = !isNotSearch; continue; } return this.sendReplyBox("'" + Tools.escapeHTML(oldTarget) + "' could not be found in any of the search categories."); } if (showAll && Object.size(searches) === 0 && !targetMon) return this.sendReplyBox("No search parameters other than 'all' were found. Try '/help movesearch' for more information on this command."); var dex = {}; if (targetMon) { for (var move in lsetData) { dex[move] = Tools.getMove(move); } } else { for (var move in Tools.data.Movedex) { dex[move] = Tools.getMove(move); } delete dex.magikarpsrevenge; } for (var search in searches) { switch (search) { case 'type': case 'category': for (var move in dex) { if (searches[search][String(dex[move][search])] === false) { delete dex[move]; } else if (Object.count(searches[search], true) > 0 && !searches[search][String(dex[move][search])]) delete dex[move]; } break; case 'flags': for (var flag in searches[search]) { for (var move in dex) { if (flag !== 'secondary') { if ((!dex[move].flags[flag] && searches[search][flag]) || (dex[move].flags[flag] && !searches[search][flag])) delete dex[move]; } else { if (searches[search][flag]) { if (!dex[move].secondary && !dex[move].secondaries) delete dex[move]; } else { if (dex[move].secondary && dex[move].secondaries) delete dex[move]; } } } } break; case 'recovery': for (var move in dex) { var hasRecovery = (dex[move].drain || dex[move].flags.heal); if ((!hasRecovery && searches[search]) || (hasRecovery && !searches[search])) delete dex[move]; } break; case 'property': for (var prop in searches[search]) { for (var move in dex) { if (typeof searches[search][prop].less === "number") { if (dex[move][prop] === true) { delete dex[move]; continue; } if (dex[move][prop] > searches[search][prop].less) { delete dex[move]; continue; } } if (typeof searches[search][prop].greater === "number") { if (dex[move][prop] === true) { if (dex[move].category === "Status") delete dex[move]; continue; } if (dex[move][prop] < searches[search][prop].greater) { delete dex[move]; continue; } } } } break; case 'boost': for (var boost in searches[search]) { for (var move in dex) { if (dex[move].boosts) { if ((dex[move].boosts[boost] > 0 && searches[search][boost]) || (dex[move].boosts[boost] < 1 && !searches[search][boost])) continue; } else if (dex[move].secondary && dex[move].secondary.self && dex[move].secondary.self.boosts) { if ((dex[move].secondary.self.boosts[boost] > 0 && searches[search][boost]) || (dex[move].secondary.self.boosts[boost] < 1 && !searches[search][boost])) continue; } delete dex[move]; } } break; case 'status': case 'volatileStatus': for (var searchStatus in searches[search]) { for (var move in dex) { if (dex[move][search] !== searchStatus) { if (!dex[move].secondaries) { if (!dex[move].secondary) { if (searches[search][searchStatus]) delete dex[move]; } else { if ((dex[move].secondary[search] !== searchStatus && searches[search][searchStatus]) || (dex[move].secondary[search] === searchStatus && !searches[search][searchStatus])) delete dex[move]; } } else { var hasSecondary = false; for (var i = 0; i < dex[move].secondaries.length; i++) { if (dex[move].secondaries[i][search] === searchStatus) hasSecondary = true; } if ((!hasSecondary && searches[search][searchStatus]) || (hasSecondary && !searches[search][searchStatus])) delete dex[move]; } } else { if (!searches[search][searchStatus]) delete dex[move]; } } } break; default: return this.sendReplyBox("Something broke! PM SolarisFox here or on the Smogon forums with the command you tried."); } } var results = []; for (var move in dex) { results.push(dex[move].name); } var resultsStr = targetMon ? ("<font color=#999999>Matching moves found in learnset for</font> " + targetMon + ":<br>") : ""; if (results.length > 0) { if (showAll || results.length <= output + 5) { results.sort(); resultsStr += results.join(", "); } else { resultsStr += results.slice(0, output).join(", ") + ", and " + string(results.length - output) + " more. <font color=#999999>Redo the search with 'all' as a search parameter to show all results.</font>"; } } else { resultsStr = "No moves found."; } return this.sendReplyBox(resultsStr); }, movesearchhelp: ["/movesearch [parameter], [parameter], [parameter], ... - Searches for moves that fulfill the selected criteria.", "Search categories are: type, category, flag, status inflicted, type boosted, and numeric range for base power, pp, and accuracy.", "Types must be followed by ' type', e.g., 'dragon type'.", "Stat boosts must be preceded with 'boosts ', e.g., 'boosts attack' searches for moves that boost the attack stat.", "Inequality ranges use the characters '>' and '<' though they behave as '≥' and '≤', e.g., 'bp > 100' searches for all moves equal to and greater than 100 base power.", "Parameters can be excluded through the use of '!', e.g., !water type' excludes all water type moves.", "If a Pokemon is included as a parameter, moves will be searched from it's movepool.", "The order of the parameters does not matter."], learnset: 'learn', learnall: 'learn', learn5: 'learn', g6learn: 'learn', rbylearn: 'learn', gsclearn: 'learn', advlearn: 'learn', dpplearn: 'learn', bw2learn: 'learn', learn: function (target, room, user, connection, cmd) { if (!target) return this.parse('/help learn'); if (!this.canBroadcast()) return; var lsetData = {set:{}}; var targets = target.split(','); var template = Tools.getTemplate(targets[0]); var move = {}; var problem; var format = {rby:'gen1ou', gsc:'gen2ou', adv:'gen3ou', dpp:'gen4ou', bw2:'gen5ou'}[cmd.substring(0, 3)]; var all = (cmd === 'learnall'); if (cmd === 'learn5') lsetData.set.level = 5; if (cmd === 'g6learn') lsetData.format = {noPokebank: true}; if (!template.exists) { return this.sendReply("Pokemon '" + template.id + "' not found."); } if (targets.length < 2) { return this.sendReply("You must specify at least one move."); } for (var i = 1, len = targets.length; i < len; ++i) { move = Tools.getMove(targets[i]); if (!move.exists) { return this.sendReply("Move '" + move.id + "' not found."); } problem = TeamValidator.checkLearnsetSync(format, move, template.species, lsetData); if (problem) break; } var buffer = template.name + (problem ? " <span class=\"message-learn-cannotlearn\">can't</span> learn " : " <span class=\"message-learn-canlearn\">can</span> learn ") + (targets.length > 2 ? "these moves" : move.name); if (format) buffer += ' on ' + cmd.substring(0, 3).toUpperCase(); if (!problem) { var sourceNames = {E:"egg", S:"event", D:"dream world"}; if (lsetData.sources || lsetData.sourcesBefore) buffer += " only when obtained from:<ul class=\"message-learn-list\">"; if (lsetData.sources) { var sources = lsetData.sources.sort(); var prevSource; var prevSourceType; var prevSourceCount = 0; for (var i = 0, len = sources.length; i < len; ++i) { var source = sources[i]; if (source.substr(0, 2) === prevSourceType) { if (prevSourceCount < 0) { buffer += ": " + source.substr(2); } else if (all || prevSourceCount < 3) { buffer += ", " + source.substr(2); } else if (prevSourceCount === 3) { buffer += ", ..."; } ++prevSourceCount; continue; } prevSourceType = source.substr(0, 2); prevSourceCount = source.substr(2) ? 0 : -1; buffer += "<li>gen " + source.charAt(0) + " " + sourceNames[source.charAt(1)]; if (prevSourceType === '5E' && template.maleOnlyHidden) buffer += " (cannot have hidden ability)"; if (source.substr(2)) buffer += ": " + source.substr(2); } } if (lsetData.sourcesBefore) { if (!(cmd.substring(0, 3) in {'rby':1, 'gsc':1})) { buffer += "<li>any generation before " + (lsetData.sourcesBefore + 1); } else if (!lsetData.sources) { buffer += "<li>gen " + lsetData.sourcesBefore; } } buffer += "</ul>"; } this.sendReplyBox(buffer); }, learnhelp: ["/learn [pokemon], [move, move, ...] - Displays how a Pokemon can learn the given moves, if it can at all.", "!learn [pokemon], [move, move, ...] - Show everyone that information. Requires: + % @ & ~"], weaknesses: 'weakness', weak: 'weakness', resist: 'weakness', weakness: function (target, room, user) { if (!target) return this.parse('/help weakness'); if (!this.canBroadcast()) return; target = target.trim(); var targets = target.split(/ ?[,\/ ] ?/); var pokemon = Tools.getTemplate(target); var type1 = Tools.getType(targets[0]); var type2 = Tools.getType(targets[1]); if (pokemon.exists) { target = pokemon.species; } else if (type1.exists && type2.exists && type1 !== type2) { pokemon = {types: [type1.id, type2.id]}; target = type1.id + "/" + type2.id; } else if (type1.exists) { pokemon = {types: [type1.id]}; target = type1.id; } else { return this.sendReplyBox("" + Tools.escapeHTML(target) + " isn't a recognized type or pokemon."); } var weaknesses = []; var resistances = []; var immunities = []; Object.keys(Tools.data.TypeChart).forEach(function (type) { var notImmune = Tools.getImmunity(type, pokemon); if (notImmune) { var typeMod = Tools.getEffectiveness(type, pokemon); switch (typeMod) { case 1: weaknesses.push(type); break; case 2: weaknesses.push("<b>" + type + "</b>"); break; case -1: resistances.push(type); break; case -2: resistances.push("<b>" + type + "</b>"); break; } } else { immunities.push(type); } }); var buffer = []; buffer.push(pokemon.exists ? "" + target + ' (ignoring abilities):' : '' + target + ':'); buffer.push('<span class="message-effect-weak">Weaknesses</span>: ' + (weaknesses.join(', ') || '<font color=#999999>None</font>')); buffer.push('<span class="message-effect-resist">Resistances</span>: ' + (resistances.join(', ') || '<font color=#999999>None</font>')); buffer.push('<span class="message-effect-immune">Immunities</span>: ' + (immunities.join(', ') || '<font color=#999999>None</font>')); this.sendReplyBox(buffer.join('<br>')); }, weaknesshelp: ["/weakness [pokemon] - Provides a Pokemon's resistances, weaknesses, and immunities, ignoring abilities.", "/weakness [type 1]/[type 2] - Provides a type or type combination's resistances, weaknesses, and immunities, ignoring abilities.", "!weakness [pokemon] - Shows everyone a Pokemon's resistances, weaknesses, and immunities, ignoring abilities. Requires: + % @ & ~", "!weakness [type 1]/[type 2] - Shows everyone a type or type combination's resistances, weaknesses, and immunities, ignoring abilities. Requires: + % @ & ~"], eff: 'effectiveness', type: 'effectiveness', matchup: 'effectiveness', effectiveness: function (target, room, user) { var targets = target.split(/[,/]/).slice(0, 2); if (targets.length !== 2) return this.sendReply("Attacker and defender must be separated with a comma."); var searchMethods = {'getType':1, 'getMove':1, 'getTemplate':1}; var sourceMethods = {'getType':1, 'getMove':1}; var targetMethods = {'getType':1, 'getTemplate':1}; var source, defender, foundData, atkName, defName; for (var i = 0; i < 2; ++i) { var method; for (method in searchMethods) { foundData = Tools[method](targets[i]); if (foundData.exists) break; } if (!foundData.exists) return this.parse('/help effectiveness'); if (!source && method in sourceMethods) { if (foundData.type) { source = foundData; atkName = foundData.name; } else { source = foundData.id; atkName = foundData.id; } searchMethods = targetMethods; } else if (!defender && method in targetMethods) { if (foundData.types) { defender = foundData; defName = foundData.species + " (not counting abilities)"; } else { defender = {types: [foundData.id]}; defName = foundData.id; } searchMethods = sourceMethods; } } if (!this.canBroadcast()) return; var factor = 0; if (Tools.getImmunity(source, defender) || source.ignoreImmunity && (source.ignoreImmunity === true || source.ignoreImmunity[source.type])) { var totalTypeMod = 0; if (source.effectType !== 'Move' || source.category === 'Status' || source.basePower || source.basePowerCallback) { for (var i = 0; i < defender.types.length; i++) { var baseMod = Tools.getEffectiveness(source, defender.types[i]); var moveMod = source.onEffectiveness && source.onEffectiveness.call(Tools, baseMod, defender.types[i], source); totalTypeMod += typeof moveMod === 'number' ? moveMod : baseMod; } } factor = Math.pow(2, totalTypeMod); } this.sendReplyBox("" + atkName + " is " + factor + "x effective against " + defName + "."); }, effectivenesshelp: ["/effectiveness [attack], [defender] - Provides the effectiveness of a move or type on another type or a Pokémon.", "!effectiveness [attack], [defender] - Shows everyone the effectiveness of a move or type on another type or a Pokémon."], cover: 'coverage', coverage: function (target, room, user) { if (!this.canBroadcast()) return; if (!target) return this.parse("/help coverage"); var targets = target.split(/[,+]/); var sources = []; var dispTable = false; var bestCoverage = {}; for (var type in Tools.data.TypeChart) { // This command uses -5 to designate immunity bestCoverage[type] = -5; } for (var i = 0; i < targets.length; i++) { var move = targets[i].trim().capitalize(); if (move === 'Table' || move === 'All') { if (this.broadcasting) return this.sendReplyBox("The full table cannot be broadcast."); dispTable = true; continue; } var eff; if (move in Tools.data.TypeChart) { sources.push(move); for (var type in bestCoverage) { if (!Tools.getImmunity(move, type) && !move.ignoreImmunity) continue; eff = Tools.getEffectiveness(move, type); if (eff > bestCoverage[type]) bestCoverage[type] = eff; } continue; } move = Tools.getMove(move); if (move.exists) { if (!move.basePower && !move.basePowerCallback) continue; sources.push(move); for (var type in bestCoverage) { if (!Tools.getImmunity(move.type, type) && !move.ignoreImmunity) continue; var baseMod = Tools.getEffectiveness(move, type); var moveMod = move.onEffectiveness && move.onEffectiveness.call(Tools, baseMod, type, move); eff = typeof moveMod === 'number' ? moveMod : baseMod; if (eff > bestCoverage[type]) bestCoverage[type] = eff; } continue; } return this.sendReply("No type or move '" + targets[i] + "' found."); } if (sources.length === 0) return this.sendReply("No moves using a type table for determining damage were specified."); if (sources.length > 4) return this.sendReply("Specify a maximum of 4 moves or types."); // converts to fractional effectiveness, 0 for immune for (var type in bestCoverage) { if (bestCoverage[type] === -5) { bestCoverage[type] = 0; continue; } bestCoverage[type] = Math.pow(2, bestCoverage[type]); } if (!dispTable) { var buffer = []; var superEff = []; var neutral = []; var resists = []; var immune = []; for (var type in bestCoverage) { switch (bestCoverage[type]) { case 0: immune.push(type); break; case 0.25: case 0.5: resists.push(type); break; case 1: neutral.push(type); break; case 2: case 4: superEff.push(type); break; default: throw new Error("/coverage effectiveness of " + bestCoverage[type] + " from parameters: " + target); } } buffer.push('Coverage for ' + sources.join(' + ') + ':'); buffer.push('<b><font color=#559955>Super Effective</font></b>: ' + (superEff.join(', ') || '<font color=#999999>None</font>')); buffer.push('<span class="message-effect-resist">Neutral</span>: ' + (neutral.join(', ') || '<font color=#999999>None</font>')); buffer.push('<span class="message-effect-weak">Resists</span>: ' + (resists.join(', ') || '<font color=#999999>None</font>')); buffer.push('<span class="message-effect-immune">Immunities</span>: ' + (immune.join(', ') || '<font color=#999999>None</font>')); return this.sendReplyBox(buffer.join('<br>')); } else { var buffer = '<div class="scrollable"><table cellpadding="1" width="100%"><tr><th></th>'; var icon = {}; for (var type in Tools.data.TypeChart) { icon[type] = '<img src="http://play.pokemonshowdown.com/sprites/types/' + type + '.png" width="32" height="14">'; // row of icons at top buffer += '<th>' + icon[type] + '</th>'; } buffer += '</tr>'; for (var type1 in Tools.data.TypeChart) { // assembles the rest of the rows buffer += '<tr><th>' + icon[type1] + '</th>'; for (var type2 in Tools.data.TypeChart) { var typing; var cell = '<th '; var bestEff = -5; if (type1 === type2) { // when types are the same it's considered pure type typing = type1; bestEff = bestCoverage[type1]; } else { typing = type1 + "/" + type2; for (var i = 0; i < sources.length; i++) { var move = sources[i]; var curEff = 0; if ((!Tools.getImmunity((move.type || move), type1) || !Tools.getImmunity((move.type || move), type2)) && !move.ignoreImmunity) continue; var baseMod = Tools.getEffectiveness(move, type1); var moveMod = move.onEffectiveness && move.onEffectiveness.call(Tools, baseMod, type1, move); curEff += typeof moveMod === 'number' ? moveMod : baseMod; baseMod = Tools.getEffectiveness(move, type2); moveMod = move.onEffectiveness && move.onEffectiveness.call(Tools, baseMod, type2, move); curEff += typeof moveMod === 'number' ? moveMod : baseMod; if (curEff > bestEff) bestEff = curEff; } if (bestEff === -5) { bestEff = 0; } else { bestEff = Math.pow(2, bestEff); } } switch (bestEff) { case 0: cell += 'bgcolor=#666666 title="' + typing + '"><font color=#000000>' + bestEff + '</font>'; break; case 0.25: case 0.5: cell += 'bgcolor=#AA5544 title="' + typing + '"><font color=#660000>' + bestEff + '</font>'; break; case 1: cell += 'bgcolor=#6688AA title="' + typing + '"><font color=#000066>' + bestEff + '</font>'; break; case 2: case 4: cell += 'bgcolor=#559955 title="' + typing + '"><font color=#003300>' + bestEff + '</font>'; break; default: throw new Error("/coverage effectiveness of " + bestEff + " from parameters: " + target); } cell += '</th>'; buffer += cell; } } buffer += '</table></div>'; this.sendReplyBox('Coverage for ' + sources.join(' + ') + ':<br>' + buffer); } }, coveragehelp: ["/coverage [move 1], [move 2] ... - Provides the best effectiveness match-up against all defending types for given moves or attacking types", "!coverage [move 1], [move 2] ... - Shows this information to everyone.", "Adding the parameter 'all' or 'table' will display the information with a table of all type combinations."], /********************************************************* * Informational commands *********************************************************/ uptime: function (target, room, user) { if (!this.canBroadcast()) return; var uptime = process.uptime(); var uptimeText; if (uptime > 24 * 60 * 60) { var uptimeDays = Math.floor(uptime / (24 * 60 * 60)); uptimeText = uptimeDays + " " + (uptimeDays === 1 ? "day" : "days"); var uptimeHours = Math.floor(uptime / (60 * 60)) - uptimeDays * 24; if (uptimeHours) uptimeText += ", " + uptimeHours + " " + (uptimeHours === 1 ? "hour" : "hours"); } else { uptimeText = uptime.seconds().duration(); } this.sendReplyBox("Uptime: <b>" + uptimeText + "</b>"); }, groups: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "+ <b>Voice</b> - They can use ! commands like !groups, and talk during moderated chat<br />" + "% <b>Driver</b> - The above, and they can mute. Global % can also lock users and check for alts<br />" + "@ <b>Moderator</b> - The above, and they can ban users<br />" + "&amp; <b>Leader</b> - The above, and they can promote to moderator and force ties<br />" + "# <b>Room Owner</b> - They are leaders of the room and can almost totally control it<br />" + "~ <b>Administrator</b> - They can do anything, like change what this message says" ); }, groupshelp: ["/groups - Explains what the + % @ & next to people's names mean.", "!groups - Show everyone that information. Requires: + % @ & ~"], repo: 'opensource', repository: 'opensource', git: 'opensource', opensource: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "Pokemon Showdown is open source:<br />" + "- Language: JavaScript (Node.js)<br />" + "- <a href=\"https://github.com/Zarel/Pokemon-Showdown/commits/master\">What's new?</a><br />" + "- <a href=\"https://github.com/Zarel/Pokemon-Showdown\">Server source code</a><br />" + "- <a href=\"https://github.com/Zarel/Pokemon-Showdown-Client\">Client source code</a>" ); }, opensourcehelp: ["/opensource - Links to PS's source code repository.", "!opensource - Show everyone that information. Requires: + % @ & ~"], staff: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox("<a href=\"https://www.smogon.com/sim/staff_list\">Pokemon Showdown Staff List</a>"); }, avatars: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('You can <button name="avatars">change your avatar</button> by clicking on it in the <button name="openOptions"><i class="icon-cog"></i> Options</button> menu in the upper right. Custom avatars are only obtainable by staff.'); }, avatarshelp: ["/avatars - Explains how to change avatars.", "!avatars - Show everyone that information. Requires: + % @ & ~"], introduction: 'intro', intro: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "New to competitive pokemon?<br />" + "- <a href=\"https://www.smogon.com/sim/ps_guide\">Beginner's Guide to Pokémon Showdown</a><br />" + "- <a href=\"https://www.smogon.com/dp/articles/intro_comp_pokemon\">An introduction to competitive Pokémon</a><br />" + "- <a href=\"https://www.smogon.com/bw/articles/bw_tiers\">What do 'OU', 'UU', etc mean?</a><br />" + "- <a href=\"https://www.smogon.com/xyhub/tiers\">What are the rules for each format? What is 'Sleep Clause'?</a>" ); }, introhelp: ["/intro - Provides an introduction to competitive pokemon.", "!intro - Show everyone that information. Requires: + % @ & ~"], mentoring: 'smogintro', smogonintro: 'smogintro', smogintro: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "Welcome to Smogon's official simulator! Here are some useful links to <a href=\"https://www.smogon.com/mentorship/\">Smogon\'s Mentorship Program</a> to help you get integrated into the community:<br />" + "- <a href=\"https://www.smogon.com/mentorship/primer\">Smogon Primer: A brief introduction to Smogon's subcommunities</a><br />" + "- <a href=\"https://www.smogon.com/mentorship/introductions\">Introduce yourself to Smogon!</a><br />" + "- <a href=\"https://www.smogon.com/mentorship/profiles\">Profiles of current Smogon Mentors</a><br />" + "- <a href=\"http://mibbit.com/#mentor@irc.synirc.net\">#mentor: the Smogon Mentorship IRC channel</a>" ); }, calculator: 'calc', calc: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "Pokemon Showdown! damage calculator. (Courtesy of Honko)<br />" + "- <a href=\"https://pokemonshowdown.com/damagecalc/\">Damage Calculator</a>" ); }, calchelp: ["/calc - Provides a link to a damage calculator", "!calc - Shows everyone a link to a damage calculator. Requires: + % @ & ~"], capintro: 'cap', cap: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "An introduction to the Create-A-Pokemon project:<br />" + "- <a href=\"https://www.smogon.com/cap/\">CAP project website and description</a><br />" + "- <a href=\"https://www.smogon.com/forums/showthread.php?t=48782\">What Pokemon have been made?</a><br />" + "- <a href=\"https://www.smogon.com/forums/forums/311\">Talk about the metagame here</a><br />" + "- <a href=\"https://www.smogon.com/forums/threads/3512318/#post-5594694\">Sample XY CAP teams</a>" ); }, caphelp: ["/cap - Provides an introduction to the Create-A-Pokemon project.", "!cap - Show everyone that information. Requires: + % @ & ~"], gennext: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "NEXT (also called Gen-NEXT) is a mod that makes changes to the game:<br />" + "- <a href=\"https://github.com/Zarel/Pokemon-Showdown/blob/master/mods/gennext/README.md\">README: overview of NEXT</a><br />" + "Example replays:<br />" + "- <a href=\"https://replay.pokemonshowdown.com/gennextou-120689854\">Zergo vs Mr Weegle Snarf</a><br />" + "- <a href=\"https://replay.pokemonshowdown.com/gennextou-130756055\">NickMP vs Khalogie</a>" ); }, om: 'othermetas', othermetas: function (target, room, user) { if (!this.canBroadcast()) return; target = toId(target); var buffer = ""; var matched = false; if (target === 'all' && this.broadcasting) { return this.sendReplyBox("You cannot broadcast informatiom about all Other Metagames at once."); } if (!target || target === 'all') { matched = true; buffer += "- <a href=\"https://www.smogon.com/tiers/om/\">Other Metagames Hub</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3505031/\">Other Metagames Index</a><br />"; } if (target === 'all' || target === 'anythinggoes' || target === 'ag') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3523229/\">Anything Goes</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3535064/\">Anything Goes Viability Ranking</a><br />"; } if (target === 'all' || target === 'smogondoublesuu' || target === 'doublesuu') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3516968/\">Doubles UU</a><br />"; } if (target === 'all' || target === 'smogontriples' || target === 'triples') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3511522/\">Smogon Triples</a><br />"; } if (target === 'all' || target === 'omofthemonth' || target === 'omotm' || target === 'month') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3481155/\">Other Metagame of the Month</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3505227/\">Current OMotM: 2v2 Doubles</a><br />"; } if (target === 'all' || target === 'seasonal') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3491902/\">Seasonal Ladder</a><br />"; } if (target === 'all' || target === 'balancedhackmons' || target === 'bh') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3489849/\">Balanced Hackmons</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3515725/\">Balanced Hackmons Suspect Discussion</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3525676/\">Balanced Hackmons Viability Ranking</a><br />"; } if (target === 'all' || target === '1v1') { matched = true; if (target !== 'all') buffer += "Bring three Pokémon to Team Preview and choose one to battle.<br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3496773/\">1v1</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3536109/\">1v1 Viability Ranking</a><br />"; } if (target === 'all' || target === 'monotype') { matched = true; if (target !== 'all') buffer += "All Pokémon on a team must share a type.<br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3493087/\">Monotype</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3517737/\">Monotype Viability Ranking</a><br />"; } if (target === 'all' || target === 'tiershift' || target === 'ts') { matched = true; if (target !== 'all') buffer += "Pokémon below OU/BL get all their stats boosted. UU/BL2 get +5, RU/BL3 get +10, and NU or lower get +15.<br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3532973/\">Tier Shift</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3536719/\">Tier Shift Viability Ranking</a><br />"; } if (target === 'all' || target === 'pu') { matched = true; if (target !== 'all') buffer += "The unofficial tier below NU.<br />"; buffer += "- <a href=\"http://www.smogon.com/forums/forums/pu.327/\">PU</a><br />"; } if (target === 'all' || target === 'inversebattle' || target === 'inverse') { matched = true; if (target !== 'all') buffer += "Battle with an inverted type chart.<br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3518146/\">Inverse Battle</a><br />"; } if (target === 'all' || target === 'almostanyability' || target === 'aaa') { matched = true; if (target !== 'all') buffer += "Pokémon can use any ability, barring the few that are banned.<br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3528058/\">Almost Any Ability</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3517258/\">Almost Any Ability Viability Ranking</a><br />"; } if (target === 'all' || target === 'stabmons') { matched = true; if (target !== 'all') buffer += "Pokémon can use any move of their typing, in addition to the moves they can normally learn.<br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3493081/\">STABmons</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3512215/\">STABmons Viability Ranking</a><br />"; } if (target === 'all' || target === 'lcuu') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3523929/\">LC UU</a><br />"; } if (target === 'all' || target === 'averagemons') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3526481/\">Averagemons</a><br />"; } if (target === 'all' || target === 'classichackmons' || target === 'hackmons' || target === 'ch') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3521887/\">Classic Hackmons</a><br />"; } if (target === 'all' || target === 'hiddentype' || target === 'ht') { matched = true; if (target !== 'all') buffer += "Pokémon have an added type determined by their IVs. Same as the Hidden Power type.<br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3516349/\">Hidden Type</a><br />"; } if (target === 'all' || target === 'middlecup' || target === 'mc') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3524287/\">Middle Cup</a><br />"; } if (target === 'all' || target === 'outheorymon' || target === 'theorymon') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3536615/\">OU Theorymon</a><br />"; } if (!matched) { return this.sendReply("The Other Metas entry '" + target + "' was not found. Try /othermetas or /om for general help."); } this.sendReplyBox(buffer); }, othermetashelp: ["/om - Provides links to information on the Other Metagames.", "!om - Show everyone that information. Requires: + % @ & ~"], /*formats: 'formathelp', formatshelp: 'formathelp', formathelp: function (target, room, user) { if (!this.canBroadcast()) return; if (this.broadcasting && (room.id === 'lobby' || room.battle)) return this.sendReply("This command is too spammy to broadcast in lobby/battles"); var buf = []; var showAll = (target === 'all'); for (var id in Tools.data.Formats) { var format = Tools.data.Formats[id]; if (!format) continue; if (format.effectType !== 'Format') continue; if (!format.challengeShow) continue; if (!showAll && !format.searchShow) continue; buf.push({ name: format.name, gameType: format.gameType || 'singles', mod: format.mod, searchShow: format.searchShow, desc: format.desc || 'No description.' }); } this.sendReplyBox( "Available Formats: (<strong>Bold</strong> formats are on ladder.)<br />" + buf.map(function (data) { var str = ""; // Bold = Ladderable. str += (data.searchShow ? "<strong>" + data.name + "</strong>" : data.name) + ": "; str += "(" + (!data.mod || data.mod === 'base' ? "" : data.mod + " ") + data.gameType + " format) "; str += data.desc; return str; }).join("<br />") ); },*/ roomhelp: function (target, room, user) { if (room.id === 'lobby' || room.battle) return this.sendReply("This command is too spammy for lobby/battles."); if (!this.canBroadcast()) return; this.sendReplyBox( "Room drivers (%) can use:<br />" + "- /warn OR /k <em>username</em>: warn a user and show the Pokemon Showdown rules<br />" + "- /mute OR /m <em>username</em>: 7 minute mute<br />" + "- /hourmute OR /hm <em>username</em>: 60 minute mute<br />" + "- /unmute <em>username</em>: unmute<br />" + "- /announce OR /wall <em>message</em>: make an announcement<br />" + "- /modlog <em>username</em>: search the moderator log of the room<br />" + "- /modnote <em>note</em>: adds a moderator note that can be read through modlog<br />" + "<br />" + "Room moderators (@) can also use:<br />" + "- /roomban OR /rb <em>username</em>: bans user from the room<br />" + "- /roomunban <em>username</em>: unbans user from the room<br />" + "- /roomvoice <em>username</em>: appoint a room voice<br />" + "- /roomdevoice <em>username</em>: remove a room voice<br />" + "- /modchat <em>[off/autoconfirmed/+]</em>: set modchat level<br />" + "<br />" + "Room owners (#) can also use:<br />" + "- /roomintro <em>intro</em>: sets the room introduction that will be displayed for all users joining the room<br />" + "- /rules <em>rules link</em>: set the room rules link seen when using /rules<br />" + "- /roommod, /roomdriver <em>username</em>: appoint a room moderator/driver<br />" + "- /roomdemod, /roomdedriver <em>username</em>: remove a room moderator/driver<br />" + "- /modchat <em>[%/@/#]</em>: set modchat level<br />" + "- /declare <em>message</em>: make a large blue declaration to the room<br />" + "- !htmlbox <em>HTML code</em>: broadcasts a box of HTML code to the room<br />" + "- !showimage <em>[url], [width], [height]</em>: shows an image to the room<br />" + "<br />" + "More detailed help can be found in the <a href=\"https://www.smogon.com/sim/roomauth_guide\">roomauth guide</a><br />" + "</div>" ); }, restarthelp: function (target, room, user) { if (room.id === 'lobby' && !this.can('lockdown')) return false; if (!this.canBroadcast()) return; this.sendReplyBox( "The server is restarting. Things to know:<br />" + "- We wait a few minutes before restarting so people can finish up their battles<br />" + "- The restart itself will take around 0.6 seconds<br />" + "- Your ladder ranking and teams will not change<br />" + "- We are restarting to update Pokémon Showdown to a newer version" ); }, rule: 'rules', rules: function (target, room, user) { if (!target) { if (!this.canBroadcast()) return; this.sendReplyBox("Please follow the rules:<br />" + (room.rulesLink ? "- <a href=\"" + Tools.escapeHTML(room.rulesLink) + "\">" + Tools.escapeHTML(room.title) + " room rules</a><br />" : "") + "- <a href=\"https://pokemonshowdown.com/rules\">" + (room.rulesLink ? "Global rules" : "Rules") + "</a>"); return; } if (!this.can('roommod', null, room)) return; if (target.length > 100) { return this.sendReply("Error: Room rules link is too long (must be under 100 characters). You can use a URL shortener to shorten the link."); } room.rulesLink = target.trim(); this.sendReply("(The room rules link is now: " + target + ")"); if (room.chatRoomData) { room.chatRoomData.rulesLink = room.rulesLink; Rooms.global.writeChatRoomData(); } }, faq: function (target, room, user) { if (!this.canBroadcast()) return; target = target.toLowerCase(); var buffer = ""; var matched = false; if (target === 'all' && this.broadcasting) { return this.sendReplyBox("You cannot broadcast all FAQs at once."); } if (!target || target === 'all') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq\">Frequently Asked Questions</a><br />"; } if (target === 'all' || target === 'elo') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#elo\">Why did this user gain or lose so many points?</a><br />"; } if (target === 'all' || target === 'doubles' || target === 'triples' || target === 'rotation') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#doubles\">Can I play doubles/triples/rotation battles here?</a><br />"; } if (target === 'all' || target === 'restarts') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#restarts\">Why is the server restarting?</a><br />"; } if (target === 'all' || target === 'star' || target === 'player') { matched = true; buffer += '<a href="http://www.smogon.com/sim/faq#star">Why is there this star (&starf;) in front of my username?</a><br />'; } if (target === 'all' || target === 'staff') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/staff_faq\">Staff FAQ</a><br />"; } if (target === 'all' || target === 'autoconfirmed' || target === 'ac') { matched = true; buffer += "A user is autoconfirmed when they have won at least one rated battle and have been registered for a week or longer.<br />"; } if (target === 'all' || target === 'customavatar' || target === 'ca') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#customavatar\">How can I get a custom avatar?</a><br />"; } if (target === 'all' || target === 'pm') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#pm\">How can I send a user a private message?</a><br />"; } if (target === 'all' || target === 'challenge') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#challenge\">How can I battle a specific user?</a><br />"; } if (target === 'all' || target === 'gxe') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#gxe\">What does GXE mean?</a><br />"; } if (!matched) { return this.sendReply("The FAQ entry '" + target + "' was not found. Try /faq for general help."); } this.sendReplyBox(buffer); }, faqhelp: ["/faq [theme] - Provides a link to the FAQ. Add deviation, doubles, randomcap, restart, or staff for a link to these questions. Add all for all of them.", "!faq [theme] - Shows everyone a link to the FAQ. Add deviation, doubles, randomcap, restart, or staff for a link to these questions. Add all for all of them. Requires: + % @ & ~"], banlists: 'tiers', tier: 'tiers', tiers: function (target, room, user) { if (!this.canBroadcast()) return; target = toId(target); var buffer = ""; var matched = false; if (target === 'all' && this.broadcasting) { return this.sendReplyBox("You cannot broadcast information about all tiers at once."); } if (!target || target === 'all') { matched = true; buffer += "- <a href=\"https://www.smogon.com/tiers/\">Smogon Tiers</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/tiering-faq.3498332/\">Tiering FAQ</a><br />"; buffer += "- <a href=\"https://www.smogon.com/xyhub/tiers\">The banlists for each tier</a><br />"; } if (target === 'all' || target === 'overused' || target === 'ou') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3521201/\">OU Metagame Discussion</a><br />"; buffer += "- <a href=\"https://www.smogon.com/dex/xy/tags/ou/\">OU Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3526596/\">OU Viability Ranking</a><br />"; } if (target === 'all' || target === 'ubers' || target === 'uber') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3522911/\">Ubers Metagame Discussion</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3523419/\">Ubers Viability Ranking</a><br />"; } if (target === 'all' || target === 'underused' || target === 'uu') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3538856/\">np: UU Stage 3.1</a><br />"; buffer += "- <a href=\"https://www.smogon.com/dex/xy/tags/uu/\">UU Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3523649/\">UU Viability Ranking</a><br />"; } if (target === 'all' || target === 'rarelyused' || target === 'ru') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3537443/\">np: RU Stage 9</a><br />"; buffer += "- <a href=\"https://www.smogon.com/dex/xy/tags/ru/\">RU Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3538036/\">RU Viability Ranking</a><br />"; } if (target === 'all' || target === 'neverused' || target === 'nu') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3537418/\">np: NU Stage 6</a><br />"; buffer += "- <a href=\"https://www.smogon.com/dex/xy/tags/nu/\">NU Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3523692/\">NU Viability Ranking</a><br />"; } if (target === 'all' || target === 'littlecup' || target === 'lc') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3505710/\">LC Metagame Discussion</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3490462/\">LC Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3496013/\">LC Viability Ranking</a><br />"; } if (target === 'all' || target === 'doublesou' || target === 'doubles' || target === 'smogondoubles') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3525739/\">np: Doubles OU Stage 1.5</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3498688/\">Doubles OU Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3522814/\">Doubles OU Viability Ranking</a><br />"; } if (!matched) { return this.sendReply("The Tiers entry '" + target + "' was not found. Try /tiers for general help."); } this.sendReplyBox(buffer); }, analysis: 'smogdex', strategy: 'smogdex', smogdex: function (target, room, user) { if (!this.canBroadcast()) return; var targets = target.split(','); if (toId(targets[0]) === 'previews') return this.sendReplyBox("<a href=\"https://www.smogon.com/forums/threads/sixth-generation-pokemon-analyses-index.3494918/\">Generation 6 Analyses Index</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); var pokemon = Tools.getTemplate(targets[0]); var item = Tools.getItem(targets[0]); var move = Tools.getMove(targets[0]); var ability = Tools.getAbility(targets[0]); var atLeastOne = false; var generation = (targets[1] || 'xy').trim().toLowerCase(); var genNumber = 6; // var doublesFormats = {'vgc2012':1, 'vgc2013':1, 'vgc2014':1, 'doubles':1}; var doublesFormats = {}; var doublesFormat = (!targets[2] && generation in doublesFormats) ? generation : (targets[2] || '').trim().toLowerCase(); var doublesText = ''; if (generation === 'xy' || generation === 'xy' || generation === '6' || generation === 'six') { generation = 'xy'; } else if (generation === 'bw' || generation === 'bw2' || generation === '5' || generation === 'five') { generation = 'bw'; genNumber = 5; } else if (generation === 'dp' || generation === 'dpp' || generation === '4' || generation === 'four') { generation = 'dp'; genNumber = 4; } else if (generation === 'adv' || generation === 'rse' || generation === 'rs' || generation === '3' || generation === 'three') { generation = 'rs'; genNumber = 3; } else if (generation === 'gsc' || generation === 'gs' || generation === '2' || generation === 'two') { generation = 'gs'; genNumber = 2; } else if (generation === 'rby' || generation === 'rb' || generation === '1' || generation === 'one') { generation = 'rb'; genNumber = 1; } else { generation = 'xy'; } if (doublesFormat !== '') { // Smogon only has doubles formats analysis from gen 5 onwards. if (!(generation in {'bw':1, 'xy':1}) || !(doublesFormat in doublesFormats)) { doublesFormat = ''; } else { doublesText = {'vgc2012':"VGC 2012", 'vgc2013':"VGC 2013", 'vgc2014':"VGC 2014", 'doubles':"Doubles"}[doublesFormat]; doublesFormat = '/' + doublesFormat; } } // Pokemon if (pokemon.exists) { atLeastOne = true; if (genNumber < pokemon.gen) { return this.sendReplyBox("" + pokemon.name + " did not exist in " + generation.toUpperCase() + "!"); } // if (pokemon.tier === 'CAP') generation = 'cap'; if (pokemon.tier === 'CAP') return this.sendReply("CAP is not currently supported by Smogon Strategic Pokedex."); var illegalStartNums = {'351':1, '421':1, '487':1, '493':1, '555':1, '647':1, '648':1, '649':1, '681':1}; if (pokemon.isMega || pokemon.num in illegalStartNums) pokemon = Tools.getTemplate(pokemon.baseSpecies); var poke = pokemon.name.toLowerCase().replace(/\ /g, '_').replace(/[^a-z0-9\-\_]+/g, ''); this.sendReplyBox("<a href=\"https://www.smogon.com/dex/" + generation + "/pokemon/" + poke + doublesFormat + "\">" + generation.toUpperCase() + " " + doublesText + " " + pokemon.name + " analysis</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); } // Item if (item.exists && genNumber > 1 && item.gen <= genNumber) { atLeastOne = true; var itemName = item.name.toLowerCase().replace(' ', '_'); this.sendReplyBox("<a href=\"https://www.smogon.com/dex/" + generation + "/items/" + itemName + "\">" + generation.toUpperCase() + " " + item.name + " item analysis</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); } // Ability if (ability.exists && genNumber > 2 && ability.gen <= genNumber) { atLeastOne = true; var abilityName = ability.name.toLowerCase().replace(' ', '_'); this.sendReplyBox("<a href=\"https://www.smogon.com/dex/" + generation + "/abilities/" + abilityName + "\">" + generation.toUpperCase() + " " + ability.name + " ability analysis</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); } // Move if (move.exists && move.gen <= genNumber) { atLeastOne = true; var moveName = move.name.toLowerCase().replace(' ', '_'); this.sendReplyBox("<a href=\"https://www.smogon.com/dex/" + generation + "/moves/" + moveName + "\">" + generation.toUpperCase() + " " + move.name + " move analysis</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); } if (!atLeastOne) { return this.sendReplyBox("Pokemon, item, move, or ability not found for generation " + generation.toUpperCase() + "."); } }, smogdexhelp: ["/analysis [pokemon], [generation] - Links to the Smogon University analysis for this Pokemon in the given generation.", "!analysis [pokemon], [generation] - Shows everyone this link. Requires: + % @ & ~"], register: function () { if (!this.canBroadcast()) return; this.sendReplyBox('You will be prompted to register upon winning a rated battle. Alternatively, there is a register button in the <button name="openOptions"><i class="icon-cog"></i> Options</button> menu in the upper right.'); }, /********************************************************* * Miscellaneous commands *********************************************************/ potd: function (target, room, user) { if (!this.can('potd')) return false; Config.potd = target; Simulator.SimulatorProcess.eval('Config.potd = \'' + toId(target) + '\''); if (target) { if (Rooms.lobby) Rooms.lobby.addRaw("<div class=\"broadcast-blue\"><b>The Pokemon of the Day is now " + target + "!</b><br />This Pokemon will be guaranteed to show up in random battles.</div>"); this.logModCommand("The Pokemon of the Day was changed to " + target + " by " + user.name + "."); } else { if (Rooms.lobby) Rooms.lobby.addRaw("<div class=\"broadcast-blue\"><b>The Pokemon of the Day was removed!</b><br />No pokemon will be guaranteed in random battles.</div>"); this.logModCommand("The Pokemon of the Day was removed by " + user.name + "."); } }, spammode: function (target, room, user) { if (!this.can('ban')) return false; // NOTE: by default, spammode does nothing; it's up to you to set stricter filters // in config for chatfilter/hostfilter. Put this above the spammode filters: /* if (!Config.spammode) return; if (Config.spammode < Date.now()) { delete Config.spammode; return; } */ if (target === 'off' || target === 'false') { if (Config.spammode) { delete Config.spammode; this.privateModCommand("(" + user.name + " turned spammode OFF.)"); } else { this.sendReply("Spammode is already off."); } } else if (!target || target === 'on' || target === 'true') { if (Config.spammode) { this.privateModCommand("(" + user.name + " renewed spammode for half an hour.)"); } else { this.privateModCommand("(" + user.name + " turned spammode ON for half an hour.)"); } Config.spammode = Date.now() + 30 * 60 * 1000; } else { this.sendReply("Unrecognized spammode setting."); } }, roll: 'dice', dice: function (target, room, user) { if (!target || target.match(/[^d\d\s\-\+HL]/i)) return this.parse('/help dice'); if (!this.canBroadcast()) return; // ~30 is widely regarded as the sample size required for sum to be a Gaussian distribution. // This also sets a computation time constraint for safety. var maxDice = 40; var diceQuantity = 1; var diceDataStart = target.indexOf('d'); if (diceDataStart >= 0) { diceQuantity = Number(target.slice(0, diceDataStart)); target = target.slice(diceDataStart + 1); if (!Number.isInteger(diceQuantity) || diceQuantity <= 0 || diceQuantity > maxDice) return this.sendReply("The amount of dice rolled should be a natural number up to " + maxDice + "."); } var offset = 0; var removeOutlier = 0; var modifierData = target.match(/[\-\+]/); if (modifierData) { switch (target.slice(modifierData.index).trim().toLowerCase()) { case '-l': removeOutlier = -1; break; case '-h': removeOutlier = +1; break; default: offset = Number(target.slice(modifierData.index)); if (isNaN(offset)) return this.parse('/help dice'); if (!Number.isSafeInteger(offset)) return this.sendReply("The specified offset must be an integer up to " + Number.MAX_SAFE_INTEGER + "."); } if (removeOutlier && diceQuantity <= 1) return this.sendReply("More than one dice should be rolled before removing outliers."); target = target.slice(0, modifierData.index); } var diceFaces = 6; if (target.length) { diceFaces = Number(target); if (!Number.isSafeInteger(diceFaces) || diceFaces <= 0) { return this.sendReply("Rolled dice must have a natural amount of faces up to " + Number.MAX_SAFE_INTEGER + "."); } } if (diceQuantity > 1) { // Make sure that we can deal with high rolls if (!Number.isSafeInteger(offset < 0 ? diceQuantity * diceFaces : diceQuantity * diceFaces + offset)) { return this.sendReply("The maximum sum of rolled dice must be lower or equal than " + Number.MAX_SAFE_INTEGER + "."); } } var maxRoll = 0; var minRoll = Number.MAX_SAFE_INTEGER; var trackRolls = diceQuantity * (('' + diceFaces).length + 1) <= 60; var rolls = []; var rollSum = 0; for (var i = 0; i < diceQuantity; ++i) { var curRoll = Math.floor(Math.random() * diceFaces) + 1; rollSum += curRoll; if (curRoll > maxRoll) maxRoll = curRoll; if (curRoll < minRoll) minRoll = curRoll; if (trackRolls) rolls.push(curRoll); } // Apply modifiers if (removeOutlier > 0) { rollSum -= maxRoll; } else if (removeOutlier < 0) { rollSum -= minRoll; } if (offset) rollSum += offset; // Reply with relevant information var offsetFragment = ""; if (offset) offsetFragment += (offset > 0 ? "+" + offset : offset); if (diceQuantity === 1) return this.sendReplyBox("Roll (1 - " + diceFaces + ")" + offsetFragment + ": " + rollSum); var sumFragment = "<br />Sum" + offsetFragment + (removeOutlier ? " except " + (removeOutlier > 0 ? "highest" : "lowest") : ""); return this.sendReplyBox("" + diceQuantity + " rolls (1 - " + diceFaces + ")" + (trackRolls ? ": " + rolls.join(", ") : "") + sumFragment + ": " + rollSum); }, dicehelp: ["/dice [max number] - Randomly picks a number between 1 and the number you choose.", "/dice [number of dice]d[number of sides] - Simulates rolling a number of dice, e.g., /dice 2d4 simulates rolling two 4-sided dice.", "/dice [number of dice]d[number of sides][+/-][offset] - Simulates rolling a number of dice and adding an offset to the sum, e.g., /dice 2d6+10: two standard dice are rolled; the result lies between 12 and 22.", "/dice [number of dice]d[number of sides]-[H/L] - Simulates rolling a number of dice with removal of extreme values, e.g., /dice 3d8-L: rolls three 8-sided dice; the result ignores the lowest value."], pr: 'pickrandom', pick: 'pickrandom', pickrandom: function (target, room, user) { var options = target.split(','); if (options.length < 2) return this.parse('/help pick'); if (!this.canBroadcast()) return false; return this.sendReplyBox('<em>We randomly picked:</em> ' + Tools.escapeHTML(options.sample().trim())); }, pickrandomhelp: ["/pick [option], [option], ... - Randomly selects an item from a list containing 2 or more elements."], showimage: function (target, room, user) { if (!target) return this.parse('/help showimage'); if (!this.can('declare', null, room)) return false; if (!this.canBroadcast()) return; var targets = target.split(','); if (targets.length !== 3) { return this.parse('/help showimage'); } this.sendReply('|raw|<img src="' + Tools.escapeHTML(targets[0]) + '" alt="" width="' + toId(targets[1]) + '" height="' + toId(targets[2]) + '" />'); }, showimagehelp: ["/showimage [url], [width], [height] - Show an image. Requires: # & ~"], htmlbox: function (target, room, user, connection, cmd, message) { if (!target) return this.parse('/help htmlbox'); if (!this.canHTML(target)) return; if (room.id === 'development') { if (!this.can('announce', null, room)) return; if (message.charAt(0) === '!') this.broadcasting = true; } else { if (!this.can('declare', null, room)) return; if (!this.canBroadcast('!htmlbox')) return; } this.sendReplyBox(target); }, htmlboxhelp: ["/htmlbox [message] - Displays a message, parsing HTML code contained. Requires: ~ # with global authority"], sdt: 'seasonaldata', sdata: 'seasonaldata', seasonaldata: function (target, room, user) { if (!this.canBroadcast()) return; var buffer = '|raw|'; var targetId = toId(target); switch (targetId) { case 'cura': case 'recover': buffer += '<ul class="utilichart"><li class="result"><a data-name="Cura"><span class="col movenamecol">Cura</span> <span class="col typecol"></span> <span class="col labelcol"></span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Heals the active team by 20%.</span> </a></li><li></li></ul>'; break; case 'curaga': case 'softboiled': buffer += '<ul class="utilichart"><li class="result"><a data-name="Curaga"><span class="col movenamecol">Curaga</span> <span class="col typecol"></span> <span class="col labelcol"></span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Heals the active team by 33%.</span> </a></li><li></li></ul>'; break; case 'wildgrowth': case 'reflect': buffer += '<ul class="utilichart"><li class="result"><a data-name="Wild Growth"><span class="col movenamecol">Wild Growth</span> <span class="col typecol"></span> <span class="col labelcol"></span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Heals the team by 12.5% each turn for 5 turns.</span> </a></li><li></li></ul>'; break; case 'powershield': case 'acupressure': buffer += '<ul class="utilichart"><li class="result"><a data-name="Power Shield"><span class="col movenamecol">Power Shield</span> <span class="col typecol"></span> <span class="col labelcol"></span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">The target will be healed by 25% of the next damage received.</span> </a></li><li></li></ul>'; break; case 'rejuvenation': case 'holdhands': buffer += '<ul class="utilichart"><li class="result"><a data-name="Rejuvenation"><span class="col movenamecol">Rejuvenation</span> <span class="col typecol"></span> <span class="col labelcol"></span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">The target will be healed by 18% each turn for 3 turns.</span> </a></li><li></li></ul>'; break; case 'fairyward': case 'luckychant': buffer += '<ul class="utilichart"><li class="result"><a data-name="Fairy Ward"><span class="col movenamecol">Fairy Ward</span> <span class="col typecol"></span> <span class="col labelcol"></span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Prevents status and reduce damage by 5% for all the team for 3 turns.</span> </a></li><li></li></ul>'; break; case 'taunt': case 'followme': buffer += '<ul class="utilichart"><li class="result"><a data-name="Taunt"><span class="col movenamecol">Taunt</span> <span class="col typecol"></span> <span class="col labelcol"></span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Will redirect all attacks to user for three turns.</span> </a></li><li></li></ul>'; break; case 'sacrifice': case 'meditate': buffer += '<ul class="utilichart"><li class="result"><a data-name="Sacrifice"><span class="col movenamecol">Sacrifice</span> <span class="col typecol"></span> <span class="col labelcol"></span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Will redirect all team damage to user for 4 turns.</span> </a></li><li></li></ul>'; break; case 'cooperation': case 'helpinghand': buffer += '<ul class="utilichart"><li class="result"><a data-name="Cooperation"><span class="col movenamecol">Cooperation</span> <span class="col typecol"></span> <span class="col labelcol"></span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Switches positions with target.</span> </a></li><li></li></ul>'; break; case 'slowdown': case 'spite': buffer += '<ul class="utilichart"><li class="result"><a data-name="Slow Down"><span class="col movenamecol">Slow Down</span> <span class="col typecol"></span> <span class="col labelcol"></span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Removes 8 PP. Lowers damage by 15%. Gets disabled after use.</span> </a></li><li></li></ul>'; break; case 'healingtouch': case 'aromaticmist': buffer += '<ul class="utilichart"><li class="result"><a data-name="Healing Touch"><span class="col movenamecol">Healing Touch</span> <span class="col typecol"></span> <span class="col labelcol"></span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Heals target by 60% of its max HP.</span> </a></li><li></li></ul>'; break; case 'penance': case 'healbell': buffer += '<ul class="utilichart"><li class="result"><a data-name="Penance"><span class="col movenamecol">Penance</span> <span class="col typecol"></span> <span class="col labelcol"></span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Heals all team by 12.5% and places a shield that will heal them for 6.15% upon being hit.</span> </a></li><li></li></ul>'; break; case 'stop': case 'fakeout': buffer += '<ul class="utilichart"><li class="result"><a data-name="Stop"><span class="col movenamecol">Stop</span> <span class="col typecol"></span> <span class="col labelcol"></span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Target won\'t move. Has priority. User is disabled after use.</span> </a></li><li></li></ul>'; break; case 'laststand': case 'endure': buffer += '<ul class="utilichart"><li class="result"><a data-name="Last Stand"><span class="col movenamecol">Last Stand</span> <span class="col typecol"></span> <span class="col labelcol"></span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">User will survive the next hit. Damage taken is halved for the turn. User is disabled after use.</span> </a></li><li></li></ul>'; break; case 'barkskin': case 'withdraw': buffer += '<ul class="utilichart"><li class="result"><a data-name="Barkskin"><span class="col movenamecol">Barkskin</span> <span class="col typecol"></span> <span class="col labelcol"></span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Reduces damage taken by 25% by 2 turns.</span> </a></li><li></li></ul>'; break; case 'punishment': case 'seismictoss': buffer += '<ul class="utilichart"><li class="result"><a data-name="Punishment"><span class="col movenamecol">Punishment</span> <span class="col typecol"></span> <span class="col labelcol"></span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Base damage is 33% of user\'s current HP.</span> </a></li><li></li></ul>'; break; case 'flamestrike': case 'flamethrower': buffer += '<ul class="utilichart"><li class="result"><a data-name="Flamestrike"><span class="col movenamecol">Flamestrike</span> <span class="col typecol"></span> <span class="col labelcol"><em>Power</em><br />30%</span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Base damage is 40% if the target is burned.</span> </a></li><li></li></ul>'; break; case 'conflagration': case 'fireblast': buffer += '<ul class="utilichart"><li class="result"><a data-name="Conflagration"><span class="col movenamecol">Conflagration</span> <span class="col typecol"></span> <span class="col labelcol"><em>Power</em><br />20%</span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Burns target.</span> </a></li><li></li></ul>'; break; case 'moonfire': case 'thunderbolt': buffer += '<ul class="utilichart"><li class="result"><a data-name="Moonfire"><span class="col movenamecol">Moonfire</span> <span class="col typecol"></span> <span class="col labelcol"><em>Power</em><br />20%</span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Applies Moonfire for 4 turns, it deals 6% damage.</span> </a></li><li></li></ul>'; break; case 'starfire': case 'thunder': buffer += '<ul class="utilichart"><li class="result"><a data-name="Starfire"><span class="col movenamecol">Starfire</span> <span class="col typecol"></span> <span class="col labelcol"><em>Power</em><br />30%</span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Base damage is 40% if the target is moonfired.</span> </a></li><li></li></ul>'; break; case 'corruption': case 'toxic': buffer += '<ul class="utilichart"><li class="result"><a data-name="Corruption"><span class="col movenamecol">Corruption</span> <span class="col typecol"></span> <span class="col labelcol"></span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Deals 10% damage every turn for 4 turns.</span> </a></li><li></li></ul>'; break; case 'soulleech': case 'leechseed': buffer += '<ul class="utilichart"><li class="result"><a data-name="Soul Leech"><span class="col movenamecol">Soul Leech</span> <span class="col typecol"></span> <span class="col labelcol"></span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Drains 8% HP every turn for 4 turns.</span> </a></li><li></li></ul>'; break; case 'icelance': case 'icebeam': buffer += '<ul class="utilichart"><li class="result"><a data-name="Ice Lance"><span class="col movenamecol">Ice Lance</span> <span class="col typecol"></span> <span class="col labelcol"><em>Power</em><br />30%</span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Base damage is 40% if the target is chilled.</span> </a></li><li></li></ul>'; break; case 'frostbite': case 'freezeshock': buffer += '<ul class="utilichart"><li class="result"><a data-name="Frostbite"><span class="col movenamecol">Frostbite</span> <span class="col typecol"></span> <span class="col labelcol"><em>Power</em><br />20%</span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Chills target. It will be slower.</span> </a></li><li></li></ul>'; break; case 'hurricane': case 'aircutter': buffer += '<ul class="utilichart"><li class="result"><a data-name="Hurricane"><span class="col movenamecol">Hurricane</span> <span class="col typecol"></span> <span class="col labelcol"><em>Power</em><br />20%</span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Damage all adjacent foes.</span> </a></li><li></li></ul>'; break; case 'storm': case 'muddywater': buffer += '<ul class="utilichart"><li class="result"><a data-name="Storm"><span class="col movenamecol">Storm</span> <span class="col typecol"></span> <span class="col labelcol"><em>Power</em><br />20%</span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Damage all adjacent foes.</span> </a></li><li></li></ul>'; break; case 'fury': case 'furyswipes': buffer += '<ul class="utilichart"><li class="result"><a data-name="Fury"><span class="col movenamecol">Fury</span> <span class="col typecol"></span> <span class="col labelcol"><em>Power</em><br />15%</span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Disables user. Next use will have 100% base power.</span> </a></li><li></li></ul>'; break; case 'garrote': case 'scratch': buffer += '<ul class="utilichart"><li class="result"><a data-name="Garrote"><span class="col movenamecol">Garrote</span> <span class="col typecol"></span> <span class="col labelcol"><em>Power</em><br />20%</span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Causes bleeding. It deals 6.15% damage for 5 turns.</span> </a></li><li></li></ul>'; break; case 'poisongas': case 'smog': buffer += '<ul class="utilichart"><li class="result"><a data-name="Poison Gas"><span class="col movenamecol">Poison Gas</span> <span class="col typecol"></span> <span class="col labelcol"></span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Poisons the target.</span> </a></li><li></li></ul>'; break; case 'mutilate': case 'slash': buffer += '<ul class="utilichart"><li class="result"><a data-name="Mutilate"><span class="col movenamecol">Mutilate</span> <span class="col typecol"></span> <span class="col labelcol"><em>Power</em><br />27%</span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Increases power by 10% or 20% if target is psn or/and bld.</span> </a></li><li></li></ul>'; break; case 'sacredshield': case 'matblock': buffer += '<ul class="utilichart"><li class="result"><a data-name="Sacred Shield"><span class="col movenamecol">Sacred Shield</span> <span class="col typecol"></span> <span class="col labelcol"></span> <span class="col widelabelcol"></span> <span class="col pplabelcol"></span> <span class="col movedesccol">Shields team greatly, losses HP.</span> </a></li><li></li></ul>'; break; default: buffer = "No Pokemon, item, move, ability or nature named '" + target + "' was found on this seasonal."; } if (targetId === 'evasion' || targetId === 'protect') { return this.parse('/data protect'); } else if (!targetId) { return this.sendReply("Please specify a valid Pokemon, item, move, ability or nature in this seasonal."); } else { this.sendReply(buffer); } }, seasonaldatahelp: ["/seasonaldata [pokemon/item/move/ability] - Get details on this pokemon/item/move/ability/nature for the current seasonal.", "!seasonaldata [pokemon/item/move/ability] - Show everyone these details. Requires: + % @ & ~"] };
import Models from './models'; import Output from './output/index'; import Base from './base'; import to from 'to-js'; import { uniqueId } from 'lodash'; import Documents from './documents'; import DocumentsStream from './documents-stream'; import { success } from 'log-symbols'; /// @name Fakeit /// @page api /// @description /// This class is used to generate fake data in `json`, `cson`, `csv`, `yml`, `yaml` formats. /// You can have it output idividual files or you can connect to a data base and store the files there. /// @arg {object} options [{}] Here are the defaults /// ``` /// options = { /// inputs: '', // @todo remove /// exclude: '', // @todo remove /// // a fixed number of documents to generate /// count: null, /// // Base options /// root: process.cwd(), /// seed: 0, /// babel_config: '+(.babelrc|package.json)', /// log: true, /// verbose: false, /// timestamp: true, /// } /// ``` /* istanbul ignore next: These are already tested in other files */ export default class Fakeit extends Base { constructor(options = {}) { super(options); this.documents = {}; this.globals = {}; } async generate(models, output_options = {}) { if (to.type(models) === 'object') { output_options = models; models = models.models; } if (!models) { return; } const label = uniqueId('fakeit'); this.time(label); const model = new Models(this.options); const output = new Output(this.options, output_options); output.prepare(); await model.registerModels(models); // calculate the total # of dependencies, if it is 0 and we're using Couchbase, // we can leverage streams to output the data. let total_dependants = model.models.forEach((value) => { total_dependants += value.dependants.length; }); await output.preparing; let result, documents; // only use streams if outputting to couchbase, the user has asked for it and there aren't any dependants if ( output_options.output === 'couchbase' && output_options.useStreams && !total_dependants ) { // we're outtputting to couchbase and there aren't any dependants use streams documents = new DocumentsStream(this.options, this.globals, model.inputs, output); } else { documents = new Documents(this.options, this.documents, this.globals, model.inputs); documents.on('data', (data) => output.output(data)); } result = await documents.build(model.models); delete model.inputs; await output.finalize(); const time = this.timeEnd(label); if (this.options.verbose) { console.log(`${success} Finished generating ${documents.total} documents in ${time}`); } return result; } }
var classthewizardplusplus_1_1anna_1_1sound_1_1_p_c_m_data_bits = [ [ "Types", "classthewizardplusplus_1_1anna_1_1sound_1_1_p_c_m_data_bits.html#a9f3fb864f916af859dc9e72e89e85e69", [ [ "BIT_8", "classthewizardplusplus_1_1anna_1_1sound_1_1_p_c_m_data_bits.html#a9f3fb864f916af859dc9e72e89e85e69af8f20decb363fdb60f2c1045e4605d17", null ], [ "BIT_16", "classthewizardplusplus_1_1anna_1_1sound_1_1_p_c_m_data_bits.html#a9f3fb864f916af859dc9e72e89e85e69aeadfa4a3e177e8b67c6e1732ee1e9d30", null ] ] ] ];
import path from 'path'; import fs from 'fs'; import babel from 'rollup-plugin-babel'; import nodeResolve from 'rollup-plugin-node-resolve'; import commonjs from 'rollup-plugin-commonjs'; let pkg = JSON.parse(fs.readFileSync('./package.json')); let external = Object.keys(pkg.peerDependencies || {}).concat(Object.keys(pkg.dependencies || {})); export default { entry: 'src/index.js', dest: pkg.main, sourceMap: path.resolve(pkg.main), moduleName: pkg.amdName, format: 'umd', external, plugins: [ babel({ babelrc: false, comments: false, exclude: 'node_modules/**', presets: [ 'es2015-loose-rollup', 'stage-0' ], plugins: [ 'transform-class-properties', ['transform-react-jsx', { pragma: 'h' }] ] }), nodeResolve({ jsnext: true, main: true, skip: external }), commonjs({ include: 'node_modules/**', exclude: '**/*.css' }) ] };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isYyyymmddDate; /** * Check if is a valid yyyy.mm.dd date * This will match : yyyy.mm.dd | yyyy/mm/dd | yyyy-mm-dd | yyyy mm dd * @param {String} date The date to check * @return {Boolean} true if is valid, false if not * @example js * import isYyyymmddDate from 'coffeekraken-sugar/js/utils/is/yyyymmddDate' * if (isYyyymmddDate('2018.12.25')) { * // do something cool * } * * @author Olivier Bossel <olivier.bossel@gmail.com> (https://olivierbossel.com) */ function isYyyymmddDate(date) { return (/^\d{4}[\-\/\s\.]?((((0[13578])|(1[02]))[\-\/\s\.]?(([0-2][0-9])|(3[01])))|(((0[469])|(11))[\-\/\s\.]?(([0-2][0-9])|(30)))|(02[\-\/\s\.]?[0-2][0-9]))$/.test(date) ); }
'use strict'; var fs = require('fs') const Headers = //read the files from the log dir fs.readdir('logs/', (err, files) => { if (err) throw err //If only header in last sync, notify fs.stat('logs/' + files[files.length -1], (err,stats) => { if (err) throw err if (stats.size == 107) { console.log("Error: Most recent pull only returned header") return true } else { return false } }) }) module.exports.headers = Headers
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _underscore = require('underscore'); var _underscore2 = _interopRequireDefault(_underscore); var _reactDimensions = require('react-dimensions'); var _reactDimensions2 = _interopRequireDefault(_reactDimensions); var _reactImmutableRenderMixin = require('react-immutable-render-mixin'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } // For more info about this read ReadMe.md function getDefaultProps() { return { defaultValue: '', placeholder: 'Search...', searchIcon: 'fa fa-search fa-fw', clearIcon: 'fa fa-times fa-fw', onSearch: null, onEnter: null, throttle: 160, // milliseconds sendEmpty: true, minLength: 3, autoComplete: 'off', uniqueId: null }; } /** * A Component that render a search field which return the written string every props.trottle miliseconds as a parameter * in a function of onSearch, only if the length is bigger than props.minlength. Get clean each time the Scape key is down/up or the * clear button is cliked. * * Simple example usage: * * <SeachField * onSearch={value => console.log(value)} * /> * ``` */ var SearchField = function (_React$Component) { _inherits(SearchField, _React$Component); function SearchField(props) { _classCallCheck(this, SearchField); var _this = _possibleConstructorReturn(this, (SearchField.__proto__ || Object.getPrototypeOf(SearchField)).call(this, props)); _this.state = { showClear: false, inputValue: '' }; return _this; } _createClass(SearchField, [{ key: 'componentWillMount', value: function componentWillMount() { var _this2 = this; this.onChange = function (e) { var value = undefined; e.preventDefault(); // Scape key if (e.keyCode == 27) { _this2.clearField(e); return; } // Enter key if (e.keyCode == 13) { if (typeof _this2.props.onEnter == 'function') { _this2.props.onEnter.call(_this2); } } // If there is a call to the update functions and to send the search filter then reset it. if (_this2.tout) { clearTimeout(_this2.tout); } value = _this2.getInputValue(); if (value.length >= _this2.props.minLength || _this2.props.sendEmpty && !value.length) { _this2.tout = setTimeout(function () { value = _this2.getInputValue(); _this2.updateClear(value); _this2.sendFilter(value); }, _this2.props.throttle); } }; } }, { key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps, nextState) { var stateChanged = !(0, _reactImmutableRenderMixin.shallowEqualImmutable)(this.state, nextState); var propsChanged = !(0, _reactImmutableRenderMixin.shallowEqualImmutable)(this.props, nextProps); var somethingChanged = propsChanged || stateChanged; if (propsChanged) { if (nextProps.defaultValue != this.props.defaultValue) { this.updateClear(nextProps.defaultValue); this.setState({ inputValue: nextProps.defaultValue }); this.getInput().value = nextProps.defaultValue; return false; } } if (stateChanged) { if (nextState.inputValue != this.state.inputValue) { this.sendFilter(nextState.inputValue); return false; } } return somethingChanged; } }, { key: 'componentDidUpdate', value: function componentDidUpdate(prevProps, prevState) { var el = this.getInput(); if (el) { el.focus(); } } }, { key: 'componentDidMount', value: function componentDidMount() { if (this.props.defaultValue || this.props.sendEmpty) { this.sendFilter(this.props.defaultValue); } this.updateClear(this.props.defaultValue); } /** * Get the value of the search input field. * * @return (String) searchValue Search field value */ }, { key: 'getInputValue', value: function getInputValue() { var el = this.getInput(); if (el) { return el.value; } return this.props.defaultValue; } /** * Get a ref to the search field input * * @return (object) el A ref to the search field input */ }, { key: 'getInput', value: function getInput() { var el = this.el || null; if (!el) { this.el = this.refs.propersearch_field; return this.el; } return el; } /** * Clear the search field */ }, { key: 'clearField', value: function clearField(e) { e.preventDefault(); var el = this.getInput(); if (el) { el.value = ''; } this.sendFilter(null); this.updateClear(null); } /** * Update the show state of the component to show / hide the clear button. * * @param (String) value Search field value */ }, { key: 'updateClear', value: function updateClear(value) { var show = false; if (value && value.length) { show = true; } if (this.state.showClear != show) { this.setState({ showClear: show }); } } /** * Send the value in the search field to the function onSearch if this was set up in the props. * * @param (String) value Search field value */ }, { key: 'sendFilter', value: function sendFilter(value) { if (typeof this.props.onSearch == 'function') { this.props.onSearch.call(this, value); } } }, { key: 'render', value: function render() { var className = 'proper-search-field', clearBtn = null; var uniqueId = undefined; if (this.props.className) { className += ' ' + this.props.className; } if (this.props.uniqueId) { uniqueId = this.props.uniqueId; } else { uniqueId = _underscore2['default'].uniqueId('search-'); } if (this.state.showClear) { clearBtn = _react2['default'].createElement( 'button', { className: 'btn btn-clear btn-small btn-xs', onClick: this.clearField.bind(this), ref: 'clear' }, ' ', _react2['default'].createElement('i', { className: this.props.clearIcon }) ); } return _react2['default'].createElement( 'div', { className: className, id: uniqueId }, _react2['default'].createElement( 'div', { className: 'proper-search-input' }, _react2['default'].createElement('i', { className: this.props.searchIcon + ' ' + 'proper-search-field-icon' }), _react2['default'].createElement('input', { ref: 'propersearch_field', className: 'proper-search-input-field', type: 'text', autoComplete: this.props.autoComplete, placeholder: this.props.placeholder, defaultValue: this.props.defaultValue, onKeyUp: this.onChange, style: { maxWidth: this.props.containerWidth - 5, boxSizing: 'border-box' } }), clearBtn ) ); } }]); return SearchField; }(_react2['default'].Component); ; SearchField.defaultProps = getDefaultProps(); var toExport = process.env.NODE_ENV === 'Test' ? SearchField : (0, _reactDimensions2['default'])()(SearchField); exports['default'] = toExport; module.exports = exports['default'];
var newObject = new Object; newObject.name = "Ram"; newObject.roll = 32; newObject.year = 2050; console.log(newObject.name); // JavaScript way of creating objects : name value pair var nvpObject = {name: "Rahim", roll: 33}; console.log(nvpObject.name); // Object has properties and methods var nvpObject = {name: "Antoni", roll: 34}; console.log(nvpObject.name); function processObj () { console.log(nvpObject.name + "has a roll number of " + nvpObject.roll); } nvpObject.newMeth = processObj; // use method of nvpObject nvpObject.newMeth()
/*! @license Firebase v4.5.0 Build: rev-f49c8b5 Terms: https://firebase.google.com/terms/ */ /** * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; //# sourceMappingURL=remote_document_cache.js.map
{ var ancestors = []; for (; treeScope; treeScope = treeScope.parent) { ancestors.push(treeScope); } return ancestors; }
define(function () { function FilterEdiStatus(bezl) { // FilterEdiStatus, will hide the table rows that are not in the correct filter status. var tr, td, div; //Get bezl rows in mainTable. tr = $(bezl.container.nativeElement).find("#mainTable tr") // Loop through all rows for(var i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName("td")[0]; if(td) { div = td.getElementsByTagName("div") ediStatus = div[8].innerHTML; //If not the correct edi status, hide the row. if(ediStatus.toUpperCase().indexOf(bezl.vars.filterEdiStatus.toUpperCase()) > -1) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } //Get bezl rows in mainTableMobile. tr = $(bezl.container.nativeElement).find("#mainTableMobile tr") // Loop through all rows for(var i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName("td"); if(td.length > 0) { ediStatus = td[6].innerHTML; //If not the correct edi status, hide the row. if(ediStatus.toUpperCase().indexOf(bezl.vars.filterEdiStatus.toUpperCase()) > -1) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } //Make buttons visible/invisible. if (bezl.vars.filterEdiStatus == 'H'){ var div = document.getElementById('btnDelete'); div.style.display = ''; var div = document.getElementById('btnApprove'); div.style.display = ''; var div = document.getElementById('btnDeleteMobile'); div.style.display = ''; var div = document.getElementById('btnApproveMobile'); div.style.display = ''; } else if (bezl.vars.filterEdiStatus == 'A' || bezl.vars.filterEdiStatus == 'D'){ var div = document.getElementById('btnDelete'); div.style.display = 'none'; var div = document.getElementById('btnApprove'); div.style.display = 'none'; var div = document.getElementById('btnDeleteMobile'); div.style.display = 'none'; var div = document.getElementById('btnApproveMobile'); div.style.display = 'none'; } //Loop through user for user rights. for (var key in bezl.vars.user.USER_DOCS){ var obj = bezl.vars.user.USER_DOCS[key]; if (obj["DOCUMENT_TYPE"] == '945'){ for (var prop in obj) { switch (prop.toString()){ case "MODIFY_DOC": if (obj[prop] == false){ //Make buttons visible/invisible. var div = document.getElementById('btnApprove'); div.style.display = 'none'; var div = document.getElementById('btnDelete'); div.style.display = 'none'; var div = document.getElementById('btnApproveMobile'); div.style.display = 'none'; var div = document.getElementById('btnDeleteMobile'); div.style.display = 'none'; } } } } } } function SelectAll(bezl) { for (var key in bezl.vars.main){ var obj = bezl.vars.main[key]; if (obj['EDI_STATUS'] == bezl.vars.filterEdiStatus){ obj['APPROVE'] = true; } } } function SelectNone(bezl) { for (var key in bezl.vars.main){ var obj = bezl.vars.main[key]; if (obj['EDI_STATUS'] == bezl.vars.filterEdiStatus){ obj['APPROVE'] = false; } } } function RunQuery (bezl, queryName) { switch (queryName) { case "GetUserSettings": var user; //Get the current login user. user = bezl.env.currentUser; bezl.dataService.add('user','brdb','EDI','GetUserSettings', { "QueryName": "GetUserSettings", "Connection": bezl.vars.config.sqlConnection, "Parameters": [ { "Key": "@EMAIL", "Value": user }, ] },0); break; case "GetDashHeaderData": // Pull in the header data for the logged in user var parameters = [], parameterCount = 0; parameters[parameterCount] = { "Key": "@DOC_TYPE", "Value": '945' }; parameterCount = parameterCount + 1; parameters[parameterCount] = { "Key": "@SEARCHVALUE", "Value": bezl.vars.search }; parameterCount = parameterCount + 1; parameters[parameterCount] = { "Key": "@SITE_ID", "Value": bezl.vars.config.siteId }; parameterCount = parameterCount + 1; //Get User ID. for (var key in bezl.vars.user.USERS){ var obj = bezl.vars.user.USERS[key]; for (var prop in obj){ switch (prop.toString()){ case "EDI_SL_USER_ID": parameters[parameterCount] = { "Key": "@USER_ID", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; case "ENABLED": parameters[parameterCount] = { "Key": "@USER_ENABLED", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; } } } //Loop through user for user rights. for (var key in bezl.vars.user.USER_DOCS){ var obj = bezl.vars.user.USER_DOCS[key]; if (obj["DOCUMENT_TYPE"] == '945'){ for (var prop in obj) { switch (prop.toString()){ case "DELETE_DATE": parameters[parameterCount] = { "Key": "@USER_DOCS_DELETE_DATE", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; case "IS_ENABLED": parameters[parameterCount] = { "Key": "@USER_DOCS_IS_ENABLED", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; case "MODIFY_DOC": parameters[parameterCount] = { "Key": "@USER_DOCS_MODIFY_DOC", "Value": obj[prop] }; parameterCount = parameterCount + 1; if (obj[prop] == false){ //Make buttons visible/invisible. var div = document.getElementById('btnApprove'); div.style.display = 'none'; var div = document.getElementById('btnDelete'); div.style.display = 'none'; var div = document.getElementById('btnApproveMobile'); div.style.display = 'none'; var div = document.getElementById('btnDeleteMobile'); div.style.display = 'none'; } else { //Make buttons visible/invisible. var div = document.getElementById('btnApprove'); div.style.display = ''; var div = document.getElementById('btnDelete'); div.style.display = ''; var div = document.getElementById('btnApproveMobile'); div.style.display = ''; var div = document.getElementById('btnDeleteMobile'); div.style.display = ''; } break; case "VIEW_DOC": parameters[parameterCount] = { "Key": "@USER_DOCS_VIEW_DOC", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; } } } } bezl.dataService.add('main','brdb','EDI','GetDashHeaderData', { "QueryName": "GetDashHeaderData", "Connection": bezl.vars.config.sqlConnection, "Parameters": parameters },0); break; case "GetViewDetails": // Pull in the header data for the logged in user bezl.dataService.add('viewdetails','brdb','EDI','GetViewDetails', { "QueryName": "GetViewDetails", "Connection": bezl.vars.config.sqlConnection, "Parameters": [ { "Key": "@HEADER_ID", "Value": bezl.vars.EDI_SL_DASH_HEADER_ID } ] },0); //Make buttons visible/invisible. if (bezl.vars.filterEdiStatus == 'H'){ var div = document.getElementById('btnRevalidate'); div.style.display = ''; var div = document.getElementById('btnSave'); div.style.display = ''; var div = document.getElementById('btnRevalidateMobile'); div.style.display = ''; var div = document.getElementById('btnSaveMobile'); div.style.display = ''; } else if (bezl.vars.filterEdiStatus == 'A' || bezl.vars.filterEdiStatus == 'D'){ var div = document.getElementById('btnRevalidate'); div.style.display = 'none'; var div = document.getElementById('btnSave'); div.style.display = 'none'; var div = document.getElementById('btnRevalidateMobile'); div.style.display = 'none'; var div = document.getElementById('btnSaveMobile'); div.style.display = 'none'; } //Loop through user for user rights. for (var key in bezl.vars.user.USER_DOCS){ var obj = bezl.vars.user.USER_DOCS[key]; if (obj["DOCUMENT_TYPE"] == '945'){ for (var prop in obj) { switch (prop.toString()){ case "MODIFY_DOC": if (obj[prop] == false){ //Make buttons visible/invisible. var div = document.getElementById('btnRevalidate'); div.style.display = 'none'; var div = document.getElementById('btnSave'); div.style.display = 'none'; var div = document.getElementById('btnRevalidateMobile'); div.style.display = 'none'; var div = document.getElementById('btnSaveMobile'); div.style.display = 'none'; } break; } } } } break; case "GetViewFile": // Pull in the header data for the logged in user bezl.dataService.add('viewfile','brdb','EDI','GetViewFile', { "QueryName": "GetViewFile", "Connection": bezl.vars.config.sqlConnection, "Parameters": [ { "Key": "@HEADER_ID", "Value": bezl.vars.EDI_SL_DASH_HEADER_ID } ] },0); break; case "Revalidate": var parameters = [], parameterCount = 0 //Loop through header for header information. for (var key in bezl.vars.viewdetails.HEADER){ var obj = bezl.vars.viewdetails.HEADER[key]; for (var prop in obj) { switch (prop.toString()){ case "DESIRED_SHIP_DATE": parameters[parameterCount] = { "Key": "@DESIRED_SHIP_DATE", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; case "DOCUMENT_TYPE": parameters[parameterCount] = { "Key": "@DOCUMENT_TYPE", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; case "EDI_DIRECTION": parameters[parameterCount] = { "Key": "@EDI_DIRECTION", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; case "EDI_SL_FILE_ID": parameters[parameterCount] = { "Key": "@EDI_SL_FILE_ID", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; case "EDI_SL_DASH_HEADER_ID": parameters[parameterCount] = { "Key": "@HEADER_ID", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; case "ORDER_STATUS": parameters[parameterCount] = { "Key": "@ORDER_STATUS", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; case "SHIP_VIA": parameters[parameterCount] = { "Key": "@SHIP_VIA", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; case "SHIPTO_ID": parameters[parameterCount] = { "Key": "@SHIPTO_ID", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; } } } //Loop through overrides for override information. for (var key in bezl.vars.viewdetails.OVERRIDES){ var obj = bezl.vars.viewdetails.OVERRIDES[key]; for (var prop in obj) { parameters[parameterCount] = { "Key": "@OVERRIDES_" + prop.toString(), "Value": obj[prop] }; parameterCount = parameterCount + 1; } } //Loop through overrides for override information. for (var key in bezl.vars.viewdetails.ITEMS){ var obj = bezl.vars.viewdetails.ITEMS[key]; for (var prop in obj) { parameters[parameterCount] = { "Key": "@ITEMS_" + prop.toString(), "Value": obj[prop] }; parameterCount = parameterCount + 1; } } // Pull in the header data for the logged in user bezl.dataService.add('viewdetails','brdb','EDI','Revalidate', { "QueryName": "Revalidate", "Connection": bezl.vars.config.sqlConnection, "Parameters": parameters },0); break; case "Save": var parameters = [], parameterCount = 0 //Loop through header for header information. for (var key in bezl.vars.viewdetails.HEADER){ var obj = bezl.vars.viewdetails.HEADER[key]; for (var prop in obj) { switch (prop.toString()){ case "DESIRED_SHIP_DATE": parameters[parameterCount] = { "Key": "@DESIRED_SHIP_DATE", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; case "DOCUMENT_TYPE": parameters[parameterCount] = { "Key": "@DOCUMENT_TYPE", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; case "EDI_SL_FILE_ID": parameters[parameterCount] = { "Key": "@EDI_SL_FILE_ID", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; case "EDI_SL_DASH_HEADER_ID": parameters[parameterCount] = { "Key": "@HEADER_ID", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; case "ORDER_STATUS": parameters[parameterCount] = { "Key": "@ORDER_STATUS", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; case "SHIP_VIA": parameters[parameterCount] = { "Key": "@SHIP_VIA", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; case "SHIPTO_ID": parameters[parameterCount] = { "Key": "@SHIPTO_ID", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; } } } //Loop through overrides for override information. for (var key in bezl.vars.viewdetails.OVERRIDES){ var obj = bezl.vars.viewdetails.OVERRIDES[key]; for (var prop in obj) { parameters[parameterCount] = { "Key": "@OVERRIDES_" + prop.toString(), "Value": obj[prop] }; parameterCount = parameterCount + 1; } } //Loop through overrides for override information. for (var key in bezl.vars.viewdetails.ITEMS){ var obj = bezl.vars.viewdetails.ITEMS[key]; for (var prop in obj) { parameters[parameterCount] = { "Key": "@ITEMS_" + prop.toString(), "Value": obj[prop] }; parameterCount = parameterCount + 1; } } // Pull in the header data for the logged in user bezl.dataService.add('viewdetails','brdb','EDI','SaveDetails', { "QueryName": "SaveDetails", "Connection": bezl.vars.config.sqlConnection, "Parameters": parameters },0); break; case "Delete": var parameters = [], parameterCount = 0 //Loop through header for header information. for (var key in bezl.vars.main){ var obj = bezl.vars.main[key]; for (var prop in obj) { switch (prop.toString()){ case "APPROVE": parameters[parameterCount] = { "Key": "@APPROVE", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; case "EDI_SL_DASH_HEADER_ID": parameters[parameterCount] = { "Key": "@HEADER_ID", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; } } } parameters[parameterCount] = { "Key": "@DOC_TYPE", "Value": '945' }; parameterCount = parameterCount + 1; parameters[parameterCount] = { "Key": "@SEARCHVALUE", "Value": bezl.vars.search }; parameterCount = parameterCount + 1; parameters[parameterCount] = { "Key": "@SITE_ID", "Value": bezl.vars.config.siteId }; parameterCount = parameterCount + 1; //Get User ID. for (var key in bezl.vars.user.USERS){ var obj = bezl.vars.user.USERS[key]; for (var prop in obj){ switch (prop.toString()){ case "EDI_SL_USER_ID": parameters[parameterCount] = { "Key": "@USER_ID", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; case "ENABLED": parameters[parameterCount] = { "Key": "@USER_ENABLED", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; } } } // Pull in the header data for the logged in user bezl.dataService.add('main','brdb','EDI','Delete', { "QueryName": "Delete", "Connection": bezl.vars.config.sqlConnection, "Parameters": parameters },0); break; case "Approve": var parameters = [], parameterCount = 0, approve = false; parameters[parameterCount] = { "Key": "@DOC_TYPE", "Value": '945' }; parameterCount = parameterCount + 1; parameters[parameterCount] = { "Key": "@EDI_DIRECTION", "Value": 'I' }; parameterCount = parameterCount + 1; //Loop through header for header information. for (var key in bezl.vars.main){ var obj = bezl.vars.main[key]; for (var prop in obj) { if (prop.toString() == "APPROVE"){ approve = obj[prop]; } } if (approve == true){ for (var prop in obj) { switch (prop.toString()){ case "APPROVE": parameters[parameterCount] = { "Key": "@APPROVE", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; case "EDI_SL_DASH_HEADER_ID": parameters[parameterCount] = { "Key": "@HEADER_ID", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; case "EDI_SL_FILE_ID": parameters[parameterCount] = { "Key": "@FILE_ID", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; case "CUSTOMER_PO_REF": parameters[parameterCount] = { "Key": "@CUSTOMER_PO_REF", "Value": obj[prop] }; parameterCount = parameterCount + 1; break; } } // Pull in the header data for the logged in user bezl.dataService.add('approve','brdb','EDI','Approve', { "QueryName": "Approve", "Connection": bezl.vars.config.sqlConnection, "Parameters": parameters },0); for (var key in parameters){ var parameterobj = parameters[key]; if (parameterobj.Key == "@APPROVE"){ parameterobj.Value = "Completed"; } } approve = false; } } break; } } function FilterBy(bezl) { // Filter, will hide the table rows that are not in the filter. var tr, td, div, found, ediStatus; //Get bezl rows in mainTable. tr = $(bezl.container.nativeElement).find("#mainTable tr") // Loop through all rows for(var i = 0; i < tr.length; i++) { found = false; for(var j = 0; j < tr[i].cells.length; j++) { td = tr[i].getElementsByTagName("td")[j]; if(td) { div = td.getElementsByTagName("div") ediStatus = div[8].innerHTML; //If not the correct edi status, hide the row. if(td.innerHTML.toUpperCase().indexOf(bezl.vars.filter.toUpperCase()) > -1 && ediStatus.toUpperCase().indexOf(bezl.vars.filterEdiStatus.toUpperCase()) > -1) { found = true; } } } if (found || i == 0) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } //Get bezl rows in mainTableMobile. tr = $(bezl.container.nativeElement).find("#mainTableMobile tr") // Loop through all rows for(var i = 0; i < tr.length; i++) { found = false; td = tr[i].getElementsByTagName("td"); if(td.length > 0) { ediStatus = td[6].innerHTML; for(var k = 0; k < td.length; k++){ //If not the correct edi status, hide the row. if(td[k].innerHTML.toUpperCase().indexOf(bezl.vars.filter.toUpperCase()) > -1 && ediStatus.toUpperCase().indexOf(bezl.vars.filterEdiStatus.toUpperCase()) > -1) { found = true; } } } if (found || i == 0) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } function Sort(bezl, sortColumn) { // If the previous sort column was picked, make it the opposite sort if (bezl.vars.sortCol == sortColumn) { if (bezl.vars.sort == "desc") { bezl.vars.sort = "asc"; } else { bezl.vars.sort = "desc"; } } else { bezl.vars.sort = "asc"; } // Store the sort column so the UI can reflect it bezl.vars.sortCol = sortColumn; // Test for numeric sort columns, date sort columns, otherwise sort alphabetic if (sortColumn == "APPROVE") { if (bezl.vars.sort == "asc") { bezl.vars.main.sort(function (a, b) { var A = a[sortColumn] || Number.MAX_SAFE_INTEGER; var B = b[sortColumn] || Number.MAX_SAFE_INTEGER; return A - B; }); } else { bezl.vars.Orders.sort(function (a, b) { var A = a[sortColumn] || Number.MAX_SAFE_INTEGER; var B = b[sortColumn] || Number.MAX_SAFE_INTEGER; return B - A; }); } } else if (sortColumn == "DESIRED_SHIP_DATE" || sortColumn == "ORDER_DATE" || sortColumn == "CHANGE_DATE") { if (bezl.vars.sort == "asc") { bezl.vars.main.sort(function (a, b) { var A = Date.parse(a[sortColumn]) || Number.MAX_SAFE_INTEGER; var B = Date.parse(b[sortColumn]) || Number.MAX_SAFE_INTEGER; return A - B; }); } else { bezl.vars.main.sort(function (a, b) { var A = Date.parse(a[sortColumn]) || Number.MAX_SAFE_INTEGER * -1; var B = Date.parse(b[sortColumn]) || Number.MAX_SAFE_INTEGER * -1; return B - A; }); } } else { if (bezl.vars.sort == "asc") { bezl.vars.main.sort(function(a, b) { if (a[sortColumn] == null){ return -1 } if (b[sortColumn] == null){ return 1; } var A = a[sortColumn].toUpperCase(); // ignore upper and lowercase var B = b[sortColumn].toUpperCase(); // ignore upper and lowercase if (A < B) { return -1; } if (A > B) { return 1; } // names must be equal return 0; }); } else { bezl.vars.main.sort(function(a, b) { if (a[sortColumn] == null){ return 1 } if (b[sortColumn] == null){ return -1; } var A = a[sortColumn].toUpperCase(); // ignore upper and lowercase var B = b[sortColumn].toUpperCase(); // ignore upper and lowercase if (A > B) { return -1; } if (A < B) { return 1; } // names must be equal return 0; }); } } } return { filterEdiStatus: FilterEdiStatus, selectAll: SelectAll, selectNone: SelectNone, runQuery: RunQuery, filterBy: FilterBy, sort: Sort } });
'use strict'; //Dependences service used to communicate Dependences REST endpoints angular.module('dependences').factory('Dependences', ['$resource', function($resource) { return $resource('dependences/:dependenceId', { dependenceId: '@_id' }, { update: { method: 'PUT' } }); } ]);
// All symbols in the `Ogham` script as per Unicode v7.0.0: [ '\u1680', '\u1681', '\u1682', '\u1683', '\u1684', '\u1685', '\u1686', '\u1687', '\u1688', '\u1689', '\u168A', '\u168B', '\u168C', '\u168D', '\u168E', '\u168F', '\u1690', '\u1691', '\u1692', '\u1693', '\u1694', '\u1695', '\u1696', '\u1697', '\u1698', '\u1699', '\u169A', '\u169B', '\u169C' ];
'use strict'; /* https://github.com/angular/protractor/blob/master/docs/toc.md */ describe('my app', function() { browser.get('index.html'); it('should automatically redirect to /view1 when location hash/fragment is empty', function() { expect(browser.getLocationAbsUrl()).toMatch("/view1"); }); });
/* eslint-disable no-console */ import fs from 'fs' import { resolve } from 'path' import { Dir } from '../config.js' import transformFiles from './transform-files.js' import CleanCss from 'clean-css' transformFiles(resolve(Dir.dist, 'css'), {}, ({ filename, sourcePath, destinationPath }) => { const filePath = resolve(sourcePath, filename) const minified = new CleanCss({ rebase: false }).minify([filePath]) fs.writeFile(resolve(destinationPath, filename), minified.styles, err => { if(err) return console.log(err) const efficiency = Math.round (Number(minified.stats.efficiency) * 100 ) console.log('\x1b[1m%s\x1b[0m', `${efficiency}%`, `smaller: ${filePath}`) }) })
(function () { angular .module('app') .factory('tokenInjector', tokenInjector) function tokenInjector($injector, $q) { const count = {} return { // 正常情况下,XSRF 不正确会触发该错误 // 从而触发跳转到登录页面 // TODO 全局提示弹框 responseError(rejection) { if (rejection.status === 401) { console.log(rejection.data.message) setTimeout(() => document.location.replace('/'), 1000) return $q.reject(rejection) } else if ((rejection.status === 404 || rejection.status === -1) && (rejection.data === null || rejection.data.success !== undefined) && count[rejection.config.url] === undefined) { count[rejection.config.url] = true const $http = $injector.get('$http') return $http(rejection.config) } return $q.reject(rejection) }, } } }())
'use strict'; var async = require('async'), plugins = require('../plugins'), db = require('../database'); (function(Entity) { require('./entity/create')(Entity); require('./entity/patch')(Entity); require('./entity/delete')(Entity); Entity.getSwaggerCacheInfo = function(callback) { db.getObjectField('global', 'swagger:refresh', function(err, needsRefresh) { callback(err, needsRefresh ? needsRefresh : "true"); }); }; Entity.setSwaggerCacheInfo = function(value, callback) { db.setObjectField('global', 'swagger:refresh', value, callback); }; Entity.getEntityField = function(uid, field, callback) { Entity.getEntityFields(uid, [field], function(err, entity) { callback(err, entity ? entity[field] : null); }); }; Entity.getEntityFields = function(uid, fields, callback) { Entity.getMultipleEntityFields([uid], fields, function(err, entities) { callback(err, entities ? entities[0] : null); }); }; //Entity.getScopeEntityFields = function(uid, fields, callback) { // Entity.getMultipleScopeEntityFields([uid], fields, function(err, entities) { // callback(err, entities ? entities[0] : null); // }); //}; Entity.getMultipleEntityFields = function(uids, fields, callback) { var fieldsToRemove = []; function addField(field) { if (fields.indexOf(field) === -1) { fields.push(field); fieldsToRemove.push(field); } } if (!Array.isArray(uids) || !uids.length) { return callback(null, []); } var keys = uids.map(function(uid) { return 'entity:' + uid; }); addField('uid'); db.getObjectsFields(keys, fields, function(err, entities) { if (err) { return callback(err); } modifyEntityData(entities, fieldsToRemove, callback); }); }; //Entity.getMultipleScopeEntityFields = function(uids, fields, callback) { // var fieldsToRemove = []; // function addField(field) { // if (fields.indexOf(field) === -1) { // fields.push(field); // fieldsToRemove.push(field); // } // } // // if (!Array.isArray(uids) || !uids.length) { // return callback(null, []); // } // // var keys = uids.map(function(uid) { // return 'scopeentity:' + uid; // }); // // addField('uid'); // // db.getObjectsFields(keys, fields, function(err, entities) { // if (err) { // return callback(err); // } // // modifyScopeEntityData(entities, fieldsToRemove, callback); // }); //}; Entity.getEntityData = function(uid, callback) { Entity.getEntitiesData([uid], function(err, entities) { callback(err, entities ? entities[0] : null); }); }; Entity.getEntitiesData = function(uids, callback) { if (!Array.isArray(uids) || !uids.length) { return callback(null, []); } var keys = uids.map(function(uid) { return 'entity:' + uid; }); db.getObjects(keys, function(err, entities) { if (err) { return callback(err); } modifyEntityData(entities, [], callback); }); }; function modifyEntityData(entities, fieldsToRemove, callback) { entities.forEach(function(entity) { if (!entity) { return; } for(var i=0; i<fieldsToRemove.length; ++i) { entity[fieldsToRemove[i]] = undefined; } }); plugins.fireHook('filter:entities.get', entities, callback); } //function modifyScopeEntityData(entities, fieldsToRemove, callback) { // entities.forEach(function(entity) { // if (!entity) { // return; // } // // for(var i=0; i<fieldsToRemove.length; ++i) { // entity[fieldsToRemove[i]] = undefined; // } // }); // // plugins.fireHook('filter:entities.get', entities, callback); //} Entity.setEntityField = function(uid, field, value, callback) { plugins.fireHook('action:user.set', field, value, 'set'); db.setObjectField('entity:' + uid, field, value, callback); }; //Entity.setScopeEntityField = function(uid, field, value, callback) { // plugins.fireHook('action:user.set', field, value, 'set'); // db.setObjectField('scopeentity:' + uid, field, value, callback); //}; Entity.setEntityFields = function(uid, data, callback) { for (var field in data) { if (data.hasOwnProperty(field)) { plugins.fireHook('action:entity.set', field, data[field], 'set'); } } db.setObject('entity:' + uid, data, callback); }; Entity.getEntities = function(uids, callback) { async.parallel({ entityData: function(next) { Entity.getMultipleEntityFields(uids, ['uid', 'name', 'displayName', 'definition', 'tags', 'domain', 'createdate', 'updatedate', 'entityviews'], next); } }, function(err, results) { if (err) { return callback(err); } results.entityData.forEach(function(entity, index) { if (!entity) { return; } if(entity.definition != null && entity.definition != 'undefined' && typeof entity.definition === 'string') { entity.definition = JSON.parse(entity.definition); } }); callback(err, results.entityData); }); }; //Entity.getScopeEntities = function(uids, callback) { // async.parallel({ // entityData: function(next) { // Entity.getMultipleScopeEntityFields(uids, ['uid', 'name', 'displayName', 'definition', 'tags', 'domain', 'createdate', 'updatedate', 'entityviews'], next); // } // }, function(err, results) { // if (err) { // return callback(err); // } // // results.entityData.forEach(function(entity, index) { // if (!entity) { // return; // } // console.log(entity.definition); // if(entity.definition != null && entity.definition != 'undefined' && typeof entity.definition === 'string') { // entity.definition = JSON.parse(entity.definition); // } // }); // callback(err, results.entityData); // }); //}; Entity.getAllEntities = function(callback) { db.getObjectValues('entityname:uid', function(err, uids) { Entity.getEntities(uids, function(err, entitiesData) { if(err) { return callback(err); } callback(err, entitiesData); }); }); }; //Entity.getAllScopeEntities = function(callback) { // db.getObjectValues('scopeentityname:uid', function(err, uids) { // Entity.getScopeEntities(uids, function(err, entitiesData) { // if(err) { // return callback(err); // } // callback(err, entitiesData); // }); // }); //}; Entity.getAllEntityFields = function(fields, callback) { db.getObjectValues('entityname:uid', function(err, uids) { Entity.getMultipleEntityFields(uids, fields, function(err, entitiesData) { if(err) { return callback(err); } callback(err, entitiesData); }); }); }; //Entity.getAllScopeEntityFields = function(fields, callback) { // db.getObjectValues('scopeentityname:uid', function(err, uids) { // Entity.getMultipleScopeEntityFields(uids, fields, function(err, entitiesData) { // if(err) { // return callback(err); // } // callback(err, entitiesData); // }); // }); //}; Entity.exists = function(name, callback) { Entity.getUidByName(name, function(err, exists) { callback(err, !! exists); }); }; Entity.count = function(callback) { db.getObjectField('global', 'entityCount', function(err, count) { callback(err, count ? count : 0); }); }; Entity.getUidByName = function(name, callback) { db.getObjectField('entityname:uid', name, callback); }; //Entity.getScopeUidByName = function(name, callback) { // db.getObjectField('scopeentityname:uid', name, callback); //}; Entity.getNamesByUids = function(uids, callback) { Entity.getMultipleEntityFields(uids, ['name'], function(err, entities) { if (err) { return callback(err); } entities = entities.map(function(entity) { return entity.name; }); callback(null, entities); }); }; }(exports));
var request = require('supertest'); var app = require('../app'); var models = require('../models'); describe('registration', function() { var agent = request.agent(app); before('Make sure all tables exist', function(done) { app.db.sequelize.sync({force: true}) .then(function() { done(); }); }); it('should refuse access to registration', function(done) { agent.get('/registration/register') .expect(401) .end(done); }); it('should login', function(done) { agent.post('/auth/login') .send({'email': 'usera@regcfp'}) .expect(200) .expect('Welcome usera@regcfp') .end(done); }); it('should show registration form', function(done) { agent.get('/registration/register') .expect(200) .expect(/name="name" value=""/) .expect(/Hide my name/) .end(done); }); it('should show prepended country', function(done) { agent.get('/registration/register') .expect(200) .expect(/<select\s*name="field_country_pre"[^>]*>\s*<option[^>]*>prepended country<\/option>/m) .end(done); }); it('should show documentation HTML', function(done) { agent.get('/registration/register') .expect(200) .expect(/docentry/) .expect(/<h3>Documentation test html<\/h3>/) .end(done); }); it('should not show internal fields', function(done) { agent.get('/registration/register') .expect(200) .expect(function (res) { if (res.text.match('Internal')) throw new Error('Contains string "Internal".'); }) .end(done); }); it('should show form on empty name', function(done) { agent.post('/registration/register') .send({'name': ' '}) .expect(200) .expect(/name="name" value=""/) .expect(/Hide my name/) .end(done); }); it('should handle empty forms', function(done) { agent.post('/registration/register') .expect(200) .expect(/name="name" value=""/) .expect(/Hide my name/) .end(done); }); it('should ask amount', function(done) { agent.post('/registration/register') .send({'name': 'TestUser A'}) .send({'field_ircnick': 'testirc'}) .send({'is_public': 'true'}) .send({'field_shirtsize': 'M'}) .expect(200) .expect(/name="name" value=""/) .expect(/Please make sure you have filled all required fields./) .end(done); }); it('should allow registration', function(done) { agent.post('/registration/register') .send({'name': 'TestUser A'}) .send({'field_ircnick': 'testirc'}) .send({'is_public': 'true'}) .send({'currency': 'EUR'}) .send({'field_shirtsize': 'M'}) .send({'regfee': '0'}) .expect(200) .expect(/Thanks for registering/) .end(done); }); it('should prevent t-shirt selection change', function(done) { agent.post('/registration/register') .send({'name': 'TestUser A'}) .send({'field_ircnick': 'testirc'}) .send({'field_shirtsize': 'baby'}) .send({'is_public': 'true'}) .expect(200) .expect(/Please make sure you have filled all required fields./) .end(done); }); it('should list registrations', function(done) { agent.get('/registration/list') .expect(200) .expect(/TestUser A/) .expect(function (res) { if (res.text.match('[^\'"]usera@regcfp[^\'"]')) throw new Error('Mail should not be included!'); }) .expect(function (res) { if (res.text.match('Internal')) throw new Error('Internal fields should not be included!'); }) .end(done) }); it('list should not show documentation fields', function(done) { agent.get('/registration/list') .expect(200) .expect(function (res) { if (res.text.match('docentry')) throw new Error('String found!'); }) .end(done) }); it('should show filled in registration form', function(done) { agent.get('/registration/register') .expect(200) .expect(/name="name" value="TestUser A"/) .expect(/Hide my name/) .end(done); }); it('should allow updates', function(done) { agent.post('/registration/register') .send({'name': 'TestUser A'}) .send({'field_ircnick': 'testirc'}) // Not sending it defaults to false. And this adds another tested line. //.send({'is_public': 'false'}) .expect(200) .expect(/Your registration was updated, thank you/) .end(done); }); // Proof that this works to check the DB // it('country ends up in database', function(done) { // var res = agent.post('/registration/register') // .send({'name': 'TestUser A'}) // .send({'field_ircnick': 'testirc'}) // .send({'field_country': 'testing'}) // .expect(200) // .then(function() { // models.RegistrationInfo.count({'where' : { 'field' : 'country', 'value' : 'testing' }}) // .then(function (count) { // if (count == 0) // done(new Error('Field did not end ended up in database!')) // else // done(); // }); // }); // }); // it('documentation fields are ignored when storing into database', function(done) { // var res = agent.post('/registration/register') // .send({'name': 'TestUser A'}) // .send({'field_ircnick': 'testirc'}) // .send({'field_doc': 'testing'}) // .expect(200) // .then(function() { // models.RegistrationInfo.count({'where' : { 'field' : 'doc', 'value' : 'testing' }}) // .then(function (count) { // if (count != 0) // done(new Error('Field end ended up in database!')) // else // done(); // }); // }); // }); it('should show the payment form', function(done) { agent.get('/registration/pay') .expect(200) .expect(/Amount/) .end(done); }); it('should show payment form on blank', function(done) { agent.post('/registration/pay') .expect(200) .expect(/Amount/) .end(done); }); it('should show payment choice', function(done) { agent.post('/registration/pay') .send({'currency': 'EUR'}) .send({'regfee': '10'}) .expect(200) .expect(/paypal/) .expect(/onsite/) .end(done); }); it('should mark zero as onsite payment', function(done) { agent.post('/registration/pay/do') .send({'currency': 'EUR'}) .send({'regfee': '0'}) // Default is onsite, let's test that default //.send({'method': 'onsite'}) .expect(200) .expect(/asked to pay for your registration/) .end(done); }); it('should refuse non-zero payment', function(done) { agent.post('/registration/pay/do') .send({'currency': 'EUR'}) .send({'regfee': '10'}) .expect(402) .end(done); }); it('should accept non-zero onsite payment', function(done) { agent.post('/registration/pay/do') .send({'currency': 'EUR'}) .send({'regfee': '10'}) .send({'method': 'onsite'}) .expect(200) .expect(/asked to pay for your registration/) .end(done); }); it('should accept second non-zero onsite payment', function(done) { agent.post('/registration/pay/do') .send({'currency': 'EUR'}) .send({'regfee': '10'}) .send({'method': 'onsite'}) .expect(200) .expect(/asked to pay for your registration/) .end(done); }); it('should no longer list user', function(done) { agent.get('/registration/list') .expect(200) .expect(/<\/tr>\n<\/table>/) .end(done) }); // Test admin stuff it('logout second user', function(done) { agent.post('/auth/logout') .expect(200) .expect('Logged out') .end(done); }); it('should login as admin', function(done) { agent.post('/auth/login') .send({'email': 'admin@regcfp'}) .expect(200) .expect('Welcome admin@regcfp') .end(done); }); it('register admin', function(done) { agent.post('/authg/register') .send({'origin': '/papers/submit'}) .send({'fullname': 'Admin'}) .end(done); }); it('should allow registration by admin', function(done) { agent.post('/registration/register') .send({'name': 'Admin'}) .send({'field_ircnick': 'adminnick'}) .send({'field_shirtsize': 'M'}) .send({'is_public': 'true'}) .send({'currency': 'EUR'}) .send({'regfee': '0'}) .expect(200) .expect(/Thanks for registering/) .end(done); }); it('should list all info for admin (except payment)', function(done) { agent.get('/registration/admin/list') .expect(200) .expect(/TestUser A/) .expect(/testirc/) .expect(/usera@regcfp/) .expect(/Admin/) .expect(/adminnick/) .expect(/Internal/) .expect(function (res) { if (res.text.match('Paid')) throw new Error('String "Paid" found!'); }) .end(done); }); // Desk system it('should show desk', function(done) { agent.get('/desk') .expect(200) .expect(/TestUser A/) .expect(/Admin/) .end(done); }); it('should show desk add', function(done) { agent.get('/desk/add') .expect(200) .expect(/Your name/) .end(done); }); it('should allow desk add', function(done) { agent.post('/desk/add') .send({'email': 'userc@regcfp'}) .send({'name': 'TestUser C'}) .send({'irc': 'test'}) .send({'gender': 'test'}) .send({'country': 'test'}) .send({'is_public': 'false'}) .expect(200) .expect(/Please return the laptop to the desk./) .end(done); }); it('should show added user', function(done) { agent.get('/desk') .expect(200) .expect(/TestUser A/) .expect(/Admin/) .expect(/TestUser C/) .end(done); }); it('should accept payment add', function(done) { agent.post('/desk/payment/add') .send({'regid': '2'}) .send({'currency': 'EUR'}) .send({'amount': '25'}) .expect(302) .expect('Location', '/desk?added=2&amount=25') .end(done); }); it('should detect desk receipt requirement', function(done) { agent.get('/desk/receipt/?regid=2') .expect(200) .expect(/your payment of €25/) .end(done); }); it('should accept clear', function(done) { agent.post('/desk/payment/clear') .send({'regid': '2'}) .expect(302) .expect('Location', '/desk?cleared=2') .end(done); }); it('should accept markpaid', function(done) { agent.post('/desk/payment/markpaid') .send({'regid': '1'}) .expect(302) .expect('Location', '/desk?paid=1') .end(done); }); it('should show desk message new_id', function(done) { agent.get('/desk/?new_id=1') .expect(200) .expect(/Registration 1 was added/) .end(done); }); it('should show desk message paid', function(done) { agent.get('/desk/?paid=1') .expect(200) .expect(/Registration 1 was marked as paid/) .end(done); }); it('should show desk message cleared', function(done) { agent.get('/desk/?cleared=1') .expect(200) .expect(/Payments for 1 were cleared/) .end(done); }); it('should show desk message added', function(done) { agent.get('/desk/?added=1&amount=10') .expect(200) .expect(/Payment of 10 registered for 1/) .end(done); }); it('should show desk message printed', function(done) { agent.get('/desk/?printed=1') .expect(200) .expect(/Registration 1 was finished/) .expect(/Please finish a second one to print badges/) .end(done); }); it('should accept finish', function(done) { agent.post('/desk/finish') .send({'regid': '1'}) .send({'printed': '2'}) .expect(200) .expect(/Click here to print badge/) .end(done); }); it('should print badge', function(done) { agent.get('/desk/badge?regida=1&regidb=2') .expect(200) .expect(/%PDF-1./) .end(done); }); it('logout admin user', function(done) { agent.post('/auth/logout') .expect(200) .expect('Logged out') .end(done); }); it('should login as payment admin', function(done) { agent.post('/auth/login') .send({'email': 'payadm@regcfp'}) .expect(200) .expect('Welcome payadm@regcfp') .end(done); }); it('register payment admin', function(done) { agent.post('/authg/register') .send({'origin': '/papers/submit'}) .send({'fullname': 'Payment Admin'}) .end(done); }); it('should list all info for payment admin', function(done) { agent.get('/registration/admin/list') .expect(200) .expect(/TestUser A/) .expect(/testirc/) .expect(/Admin/) .expect(/adminnick/) .expect(/Internal/) .expect(/Paid/) .expect(/admin@regcfp/) .end(done); }); });
/** * Auto Input Text Direction is a little JavaScript function that detects the input language, * on html forms, and changes the input direction based on the language, i.e., right to left * for the Arabic language. * Copyright (C) 2010 Abdulrahman Alotaiba <http://www.mawqey.com/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //Arabic - Range: //0600–06FF var rtlChars = '\u0600-\u06FF'; //Arabic Supplement - Range: //0750–077F rtlChars += '\u0750-\u077F'; //Arabic Presentation Forms-A - Range: //FB50–FDFF rtlChars += '\uFB50-\uFDFF'; //Arabic Presentation Forms-B - Range: //FE70–FEFF rtlChars += '\uFE70-\uFEFF'; //ASCII Punctuation - Range: //0000-0020 var controlChars = '\u0000-\u0020'; //General Punctuation - Range //2000-200D controlChars += '\u2000-\u200D'; //Start Regular Expression magic var reRTL = new RegExp('^[' + controlChars + ']*[' + rtlChars + ']'); var reControl = new RegExp('^[' + controlChars + ']*$'); function detectDirection(input) { //Get the value of the input text var value = input.value; console.log(value); //Change the direction to rtl if the value matches one of the Arabic characters if ( value.match(reRTL) ) { input.dir = 'rtl'; input.style.textAlign = 'right'; console.log("rtl"); } //Don't do anything for control and punctuation characters else if( value.match(reControl) ) { return false; } //Change the direction to ltr for any other character that is not Arabic, or control. else { input.dir = 'ltr'; input.style.textAlign = 'left'; console.log("ltr"); } }
import assert from 'assert' import { default as buildDeclarations, buildSingleDeclaration, isArray } from '../../lib/utils/build-declarations' describe('buildDeclarations function', () => { it('should return a string with the css declarations', () => { const actual = buildDeclarations({ borderRadius: '2px', display: 'block', width: '100%' }) const expected = 'border-radius:2px;display:block;width:100%;' assert.strictEqual(actual, expected) }) it('should handle vendor prefixes generated by css-prefix', () => { const actual = buildDeclarations({ display: ['-webkit-flex', 'flex'] }) const expected = 'display:-webkit-flex;display:flex;' assert.strictEqual(actual, expected) }) it('should ignore declarations that include pseudo selectors', () => { const actual = buildDeclarations({ borderRadius: '2px', ':before': { content: '""', color: 'red' }, display: 'block', width: '100%' }) const expected = 'border-radius:2px;display:block;width:100%;' assert.strictEqual(actual, expected) }) it('should ignore media queries', () => { const actual = buildDeclarations({ borderRadius: '2px', '@media (min-width: 700px)': { color: 'red' }, display: 'block', width: '100%' }) const expected = 'border-radius:2px;display:block;width:100%;' assert.strictEqual(actual, expected) }) }) describe('buildSingleDeclaration function', () => { it('should return a valid css rule', () => { const actual = buildSingleDeclaration('borderRadius', '20px') const expected = 'border-radius:20px;' assert.strictEqual(actual, expected) }) }) describe('isArray function', () => { it('should return true', () => { assert(isArray([])) }) it('should return false', () => { assert(!isArray({})) assert(!isArray('')) assert(!isArray(12)) }) })
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { Parser: AcornParser } = require("acorn"); const { SyncBailHook, HookMap } = require("tapable"); const vm = require("vm"); const Parser = require("../Parser"); const StackedMap = require("../util/StackedMap"); const memorize = require("../util/memorize"); const BasicEvaluatedExpression = require("./BasicEvaluatedExpression"); /** @typedef {import("acorn").Options} AcornOptions */ /** @typedef {import("estree").ArrayExpression} ArrayExpressionNode */ /** @typedef {import("estree").BinaryExpression} BinaryExpressionNode */ /** @typedef {import("estree").BlockStatement} BlockStatementNode */ /** @typedef {import("estree").SequenceExpression} SequenceExpressionNode */ /** @typedef {import("estree").CallExpression} CallExpressionNode */ /** @typedef {import("estree").ClassDeclaration} ClassDeclarationNode */ /** @typedef {import("estree").ClassExpression} ClassExpressionNode */ /** @typedef {import("estree").Comment} CommentNode */ /** @typedef {import("estree").ConditionalExpression} ConditionalExpressionNode */ /** @typedef {import("estree").Declaration} DeclarationNode */ /** @typedef {import("estree").Expression} ExpressionNode */ /** @typedef {import("estree").Identifier} IdentifierNode */ /** @typedef {import("estree").IfStatement} IfStatementNode */ /** @typedef {import("estree").LabeledStatement} LabeledStatementNode */ /** @typedef {import("estree").Literal} LiteralNode */ /** @typedef {import("estree").LogicalExpression} LogicalExpressionNode */ /** @typedef {import("estree").ChainExpression} ChainExpressionNode */ /** @typedef {import("estree").MemberExpression} MemberExpressionNode */ /** @typedef {import("estree").MetaProperty} MetaPropertyNode */ /** @typedef {import("estree").MethodDefinition} MethodDefinitionNode */ /** @typedef {import("estree").ModuleDeclaration} ModuleDeclarationNode */ /** @typedef {import("estree").NewExpression} NewExpressionNode */ /** @typedef {import("estree").Node} AnyNode */ /** @typedef {import("estree").Program} ProgramNode */ /** @typedef {import("estree").Statement} StatementNode */ /** @typedef {import("estree").Super} SuperNode */ /** @typedef {import("estree").TaggedTemplateExpression} TaggedTemplateExpressionNode */ /** @typedef {import("estree").TemplateLiteral} TemplateLiteralNode */ /** @typedef {import("estree").ThisExpression} ThisExpressionNode */ /** @typedef {import("estree").UnaryExpression} UnaryExpressionNode */ /** @typedef {import("estree").VariableDeclarator} VariableDeclaratorNode */ /** @template T @typedef {import("tapable").AsArray<T>} AsArray<T> */ /** @typedef {import("../Parser").ParserState} ParserState */ /** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ /** @typedef {{declaredScope: ScopeInfo, freeName: string | true, tagInfo: TagInfo | undefined}} VariableInfoInterface */ /** @typedef {{ name: string | VariableInfo, rootInfo: string | VariableInfo, getMembers: () => string[] }} GetInfoResult */ const EMPTY_ARRAY = []; const ALLOWED_MEMBER_TYPES_CALL_EXPRESSION = 0b01; const ALLOWED_MEMBER_TYPES_EXPRESSION = 0b10; const ALLOWED_MEMBER_TYPES_ALL = 0b11; // Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API const parser = AcornParser; class VariableInfo { /** * @param {ScopeInfo} declaredScope scope in which the variable is declared * @param {string | true} freeName which free name the variable aliases, or true when none * @param {TagInfo | undefined} tagInfo info about tags */ constructor(declaredScope, freeName, tagInfo) { this.declaredScope = declaredScope; this.freeName = freeName; this.tagInfo = tagInfo; } } /** @typedef {string | ScopeInfo | VariableInfo} ExportedVariableInfo */ /** @typedef {LiteralNode | string | null | undefined} ImportSource */ /** @typedef {Omit<AcornOptions, "sourceType" | "ecmaVersion"> & { sourceType: "module" | "script" | "auto", ecmaVersion?: AcornOptions["ecmaVersion"] }} ParseOptions */ /** * @typedef {Object} TagInfo * @property {any} tag * @property {any} data * @property {TagInfo | undefined} next */ /** * @typedef {Object} ScopeInfo * @property {StackedMap<string, VariableInfo | ScopeInfo>} definitions * @property {boolean | "arrow"} topLevelScope * @property {boolean} inShorthand * @property {boolean} isStrict * @property {boolean} isAsmJs * @property {boolean} inTry */ const joinRanges = (startRange, endRange) => { if (!endRange) return startRange; if (!startRange) return endRange; return [startRange[0], endRange[1]]; }; const objectAndMembersToName = (object, membersReversed) => { let name = object; for (let i = membersReversed.length - 1; i >= 0; i--) { name = name + "." + membersReversed[i]; } return name; }; const getRootName = expression => { switch (expression.type) { case "Identifier": return expression.name; case "ThisExpression": return "this"; case "MetaProperty": return `${expression.meta.name}.${expression.property.name}`; default: return undefined; } }; /** @type {AcornOptions} */ const defaultParserOptions = { ranges: true, locations: true, ecmaVersion: "latest", sourceType: "module", allowAwaitOutsideFunction: true, onComment: null }; // regexp to match at least one "magic comment" const webpackCommentRegExp = new RegExp(/(^|\W)webpack[A-Z]{1,}[A-Za-z]{1,}:/); const EMPTY_COMMENT_OPTIONS = { options: null, errors: null }; class JavascriptParser extends Parser { /** * @param {"module" | "script" | "auto"} sourceType default source type */ constructor(sourceType = "auto") { super(); this.hooks = Object.freeze({ /** @type {HookMap<SyncBailHook<[UnaryExpressionNode], BasicEvaluatedExpression | undefined | null>>} */ evaluateTypeof: new HookMap(() => new SyncBailHook(["expression"])), /** @type {HookMap<SyncBailHook<[ExpressionNode], BasicEvaluatedExpression | undefined | null>>} */ evaluate: new HookMap(() => new SyncBailHook(["expression"])), /** @type {HookMap<SyncBailHook<[IdentifierNode | ThisExpressionNode | MemberExpressionNode | MetaPropertyNode], BasicEvaluatedExpression | undefined | null>>} */ evaluateIdentifier: new HookMap(() => new SyncBailHook(["expression"])), /** @type {HookMap<SyncBailHook<[IdentifierNode | ThisExpressionNode | MemberExpressionNode], BasicEvaluatedExpression | undefined | null>>} */ evaluateDefinedIdentifier: new HookMap( () => new SyncBailHook(["expression"]) ), /** @type {HookMap<SyncBailHook<[CallExpressionNode, BasicEvaluatedExpression | undefined], BasicEvaluatedExpression | undefined | null>>} */ evaluateCallExpressionMember: new HookMap( () => new SyncBailHook(["expression", "param"]) ), /** @type {HookMap<SyncBailHook<[ExpressionNode | DeclarationNode, number], boolean | void>>} */ isPure: new HookMap( () => new SyncBailHook(["expression", "commentsStartPosition"]) ), /** @type {SyncBailHook<[StatementNode | ModuleDeclarationNode], boolean | void>} */ preStatement: new SyncBailHook(["statement"]), /** @type {SyncBailHook<[StatementNode | ModuleDeclarationNode], boolean | void>} */ blockPreStatement: new SyncBailHook(["declaration"]), /** @type {SyncBailHook<[StatementNode | ModuleDeclarationNode], boolean | void>} */ statement: new SyncBailHook(["statement"]), /** @type {SyncBailHook<[IfStatementNode], boolean | void>} */ statementIf: new SyncBailHook(["statement"]), /** @type {SyncBailHook<[ExpressionNode, ClassExpressionNode | ClassDeclarationNode], boolean | void>} */ classExtendsExpression: new SyncBailHook(["expression", "statement"]), /** @type {SyncBailHook<[MethodDefinitionNode, ClassExpressionNode | ClassDeclarationNode], boolean | void>} */ classBodyElement: new SyncBailHook(["element", "statement"]), /** @type {HookMap<SyncBailHook<[LabeledStatementNode], boolean | void>>} */ label: new HookMap(() => new SyncBailHook(["statement"])), /** @type {SyncBailHook<[StatementNode, ImportSource], boolean | void>} */ import: new SyncBailHook(["statement", "source"]), /** @type {SyncBailHook<[StatementNode, ImportSource, string, string], boolean | void>} */ importSpecifier: new SyncBailHook([ "statement", "source", "exportName", "identifierName" ]), /** @type {SyncBailHook<[StatementNode], boolean | void>} */ export: new SyncBailHook(["statement"]), /** @type {SyncBailHook<[StatementNode, ImportSource], boolean | void>} */ exportImport: new SyncBailHook(["statement", "source"]), /** @type {SyncBailHook<[StatementNode, DeclarationNode], boolean | void>} */ exportDeclaration: new SyncBailHook(["statement", "declaration"]), /** @type {SyncBailHook<[StatementNode, DeclarationNode], boolean | void>} */ exportExpression: new SyncBailHook(["statement", "declaration"]), /** @type {SyncBailHook<[StatementNode, string, string, number | undefined], boolean | void>} */ exportSpecifier: new SyncBailHook([ "statement", "identifierName", "exportName", "index" ]), /** @type {SyncBailHook<[StatementNode, ImportSource, string, string, number | undefined], boolean | void>} */ exportImportSpecifier: new SyncBailHook([ "statement", "source", "identifierName", "exportName", "index" ]), /** @type {SyncBailHook<[VariableDeclaratorNode, StatementNode], boolean | void>} */ preDeclarator: new SyncBailHook(["declarator", "statement"]), /** @type {SyncBailHook<[VariableDeclaratorNode, StatementNode], boolean | void>} */ declarator: new SyncBailHook(["declarator", "statement"]), /** @type {HookMap<SyncBailHook<[DeclarationNode], boolean | void>>} */ varDeclaration: new HookMap(() => new SyncBailHook(["declaration"])), /** @type {HookMap<SyncBailHook<[DeclarationNode], boolean | void>>} */ varDeclarationLet: new HookMap(() => new SyncBailHook(["declaration"])), /** @type {HookMap<SyncBailHook<[DeclarationNode], boolean | void>>} */ varDeclarationConst: new HookMap(() => new SyncBailHook(["declaration"])), /** @type {HookMap<SyncBailHook<[DeclarationNode], boolean | void>>} */ varDeclarationVar: new HookMap(() => new SyncBailHook(["declaration"])), pattern: new HookMap(() => new SyncBailHook(["pattern"])), /** @type {HookMap<SyncBailHook<[ExpressionNode], boolean | void>>} */ canRename: new HookMap(() => new SyncBailHook(["initExpression"])), /** @type {HookMap<SyncBailHook<[ExpressionNode], boolean | void>>} */ rename: new HookMap(() => new SyncBailHook(["initExpression"])), /** @type {HookMap<SyncBailHook<[import("estree").AssignmentExpression], boolean | void>>} */ assign: new HookMap(() => new SyncBailHook(["expression"])), /** @type {HookMap<SyncBailHook<[import("estree").AssignmentExpression, string[]], boolean | void>>} */ assignMemberChain: new HookMap( () => new SyncBailHook(["expression", "members"]) ), /** @type {HookMap<SyncBailHook<[ExpressionNode], boolean | void>>} */ typeof: new HookMap(() => new SyncBailHook(["expression"])), /** @type {SyncBailHook<[ExpressionNode], boolean | void>} */ importCall: new SyncBailHook(["expression"]), /** @type {SyncBailHook<[ExpressionNode], boolean | void>} */ topLevelAwait: new SyncBailHook(["expression"]), /** @type {HookMap<SyncBailHook<[ExpressionNode], boolean | void>>} */ call: new HookMap(() => new SyncBailHook(["expression"])), /** Something like "a.b()" */ /** @type {HookMap<SyncBailHook<[CallExpressionNode, string[]], boolean | void>>} */ callMemberChain: new HookMap( () => new SyncBailHook(["expression", "members"]) ), /** Something like "a.b().c.d" */ /** @type {HookMap<SyncBailHook<[ExpressionNode, string[], CallExpressionNode, string[]], boolean | void>>} */ memberChainOfCallMemberChain: new HookMap( () => new SyncBailHook([ "expression", "calleeMembers", "callExpression", "members" ]) ), /** Something like "a.b().c.d()"" */ /** @type {HookMap<SyncBailHook<[ExpressionNode, string[], CallExpressionNode, string[]], boolean | void>>} */ callMemberChainOfCallMemberChain: new HookMap( () => new SyncBailHook([ "expression", "calleeMembers", "innerCallExpression", "members" ]) ), /** @type {SyncBailHook<[ChainExpressionNode], boolean | void>} */ optionalChaining: new SyncBailHook(["optionalChaining"]), /** @type {HookMap<SyncBailHook<[NewExpressionNode], boolean | void>>} */ new: new HookMap(() => new SyncBailHook(["expression"])), /** @type {HookMap<SyncBailHook<[ExpressionNode], boolean | void>>} */ expression: new HookMap(() => new SyncBailHook(["expression"])), /** @type {HookMap<SyncBailHook<[ExpressionNode, string[]], boolean | void>>} */ expressionMemberChain: new HookMap( () => new SyncBailHook(["expression", "members"]) ), /** @type {HookMap<SyncBailHook<[ExpressionNode, string[]], boolean | void>>} */ unhandledExpressionMemberChain: new HookMap( () => new SyncBailHook(["expression", "members"]) ), /** @type {SyncBailHook<[ExpressionNode], boolean | void>} */ expressionConditionalOperator: new SyncBailHook(["expression"]), /** @type {SyncBailHook<[ExpressionNode], boolean | void>} */ expressionLogicalOperator: new SyncBailHook(["expression"]), /** @type {SyncBailHook<[ProgramNode, CommentNode[]], boolean | void>} */ program: new SyncBailHook(["ast", "comments"]), /** @type {SyncBailHook<[ProgramNode, CommentNode[]], boolean | void>} */ finish: new SyncBailHook(["ast", "comments"]) }); this.sourceType = sourceType; /** @type {ScopeInfo} */ this.scope = undefined; /** @type {ParserState} */ this.state = undefined; this.comments = undefined; this.semicolons = undefined; /** @type {(StatementNode|ExpressionNode)[]} */ this.statementPath = undefined; this.prevStatement = undefined; this.currentTagData = undefined; this._initializeEvaluating(); } _initializeEvaluating() { this.hooks.evaluate.for("Literal").tap("JavascriptParser", _expr => { const expr = /** @type {LiteralNode} */ (_expr); switch (typeof expr.value) { case "number": return new BasicEvaluatedExpression() .setNumber(expr.value) .setRange(expr.range); case "bigint": return new BasicEvaluatedExpression() .setBigInt(expr.value) .setRange(expr.range); case "string": return new BasicEvaluatedExpression() .setString(expr.value) .setRange(expr.range); case "boolean": return new BasicEvaluatedExpression() .setBoolean(expr.value) .setRange(expr.range); } if (expr.value === null) { return new BasicEvaluatedExpression().setNull().setRange(expr.range); } if (expr.value instanceof RegExp) { return new BasicEvaluatedExpression() .setRegExp(expr.value) .setRange(expr.range); } }); this.hooks.evaluate.for("NewExpression").tap("JavascriptParser", _expr => { const expr = /** @type {NewExpressionNode} */ (_expr); const callee = expr.callee; if ( callee.type !== "Identifier" || callee.name !== "RegExp" || expr.arguments.length > 2 || this.getVariableInfo("RegExp") !== "RegExp" ) return; let regExp, flags; const arg1 = expr.arguments[0]; if (arg1) { if (arg1.type === "SpreadElement") return; const evaluatedRegExp = this.evaluateExpression(arg1); if (!evaluatedRegExp) return; regExp = evaluatedRegExp.asString(); if (!regExp) return; } else { return new BasicEvaluatedExpression() .setRegExp(new RegExp("")) .setRange(expr.range); } const arg2 = expr.arguments[1]; if (arg2) { if (arg2.type === "SpreadElement") return; const evaluatedFlags = this.evaluateExpression(arg2); if (!evaluatedFlags) return; if (!evaluatedFlags.isUndefined()) { flags = evaluatedFlags.asString(); if ( flags === undefined || !BasicEvaluatedExpression.isValidRegExpFlags(flags) ) return; } } return new BasicEvaluatedExpression() .setRegExp(flags ? new RegExp(regExp, flags) : new RegExp(regExp)) .setRange(expr.range); }); this.hooks.evaluate .for("LogicalExpression") .tap("JavascriptParser", _expr => { const expr = /** @type {LogicalExpressionNode} */ (_expr); const left = this.evaluateExpression(expr.left); if (!left) return; if (expr.operator === "&&") { const leftAsBool = left.asBool(); if (leftAsBool === false) return left.setRange(expr.range); if (leftAsBool !== true) return; } else if (expr.operator === "||") { const leftAsBool = left.asBool(); if (leftAsBool === true) return left.setRange(expr.range); if (leftAsBool !== false) return; } else if (expr.operator === "??") { const leftAsNullish = left.asNullish(); if (leftAsNullish === false) return left.setRange(expr.range); if (leftAsNullish !== true) return; } else return; const right = this.evaluateExpression(expr.right); if (!right) return; if (left.couldHaveSideEffects()) right.setSideEffects(); return right.setRange(expr.range); }); const valueAsExpression = (value, expr, sideEffects) => { switch (typeof value) { case "boolean": return new BasicEvaluatedExpression() .setBoolean(value) .setSideEffects(sideEffects) .setRange(expr.range); case "number": return new BasicEvaluatedExpression() .setNumber(value) .setSideEffects(sideEffects) .setRange(expr.range); case "bigint": return new BasicEvaluatedExpression() .setBigInt(value) .setSideEffects(sideEffects) .setRange(expr.range); case "string": return new BasicEvaluatedExpression() .setString(value) .setSideEffects(sideEffects) .setRange(expr.range); } }; this.hooks.evaluate .for("BinaryExpression") .tap("JavascriptParser", _expr => { const expr = /** @type {BinaryExpressionNode} */ (_expr); const handleConstOperation = fn => { const left = this.evaluateExpression(expr.left); if (!left || !left.isCompileTimeValue()) return; const right = this.evaluateExpression(expr.right); if (!right || !right.isCompileTimeValue()) return; const result = fn( left.asCompileTimeValue(), right.asCompileTimeValue() ); return valueAsExpression( result, expr, left.couldHaveSideEffects() || right.couldHaveSideEffects() ); }; const isAlwaysDifferent = (a, b) => (a === true && b === false) || (a === false && b === true); const handleTemplateStringCompare = (left, right, res, eql) => { const getPrefix = parts => { let value = ""; for (const p of parts) { const v = p.asString(); if (v !== undefined) value += v; else break; } return value; }; const getSuffix = parts => { let value = ""; for (let i = parts.length - 1; i >= 0; i--) { const v = parts[i].asString(); if (v !== undefined) value = v + value; else break; } return value; }; const leftPrefix = getPrefix(left.parts); const rightPrefix = getPrefix(right.parts); const leftSuffix = getSuffix(left.parts); const rightSuffix = getSuffix(right.parts); const lenPrefix = Math.min(leftPrefix.length, rightPrefix.length); const lenSuffix = Math.min(leftSuffix.length, rightSuffix.length); if ( leftPrefix.slice(0, lenPrefix) !== rightPrefix.slice(0, lenPrefix) || leftSuffix.slice(-lenSuffix) !== rightSuffix.slice(-lenSuffix) ) { return res .setBoolean(!eql) .setSideEffects( left.couldHaveSideEffects() || right.couldHaveSideEffects() ); } }; const handleStrictEqualityComparison = eql => { const left = this.evaluateExpression(expr.left); if (!left) return; const right = this.evaluateExpression(expr.right); if (!right) return; const res = new BasicEvaluatedExpression(); res.setRange(expr.range); const leftConst = left.isCompileTimeValue(); const rightConst = right.isCompileTimeValue(); if (leftConst && rightConst) { return res .setBoolean( eql === (left.asCompileTimeValue() === right.asCompileTimeValue()) ) .setSideEffects( left.couldHaveSideEffects() || right.couldHaveSideEffects() ); } if (left.isArray() && right.isArray()) { return res .setBoolean(!eql) .setSideEffects( left.couldHaveSideEffects() || right.couldHaveSideEffects() ); } if (left.isTemplateString() && right.isTemplateString()) { return handleTemplateStringCompare(left, right, res, eql); } const leftPrimitive = left.isPrimitiveType(); const rightPrimitive = right.isPrimitiveType(); if ( // Primitive !== Object or // compile-time object types are never equal to something at runtime (leftPrimitive === false && (leftConst || rightPrimitive === true)) || (rightPrimitive === false && (rightConst || leftPrimitive === true)) || // Different nullish or boolish status also means not equal isAlwaysDifferent(left.asBool(), right.asBool()) || isAlwaysDifferent(left.asNullish(), right.asNullish()) ) { return res .setBoolean(!eql) .setSideEffects( left.couldHaveSideEffects() || right.couldHaveSideEffects() ); } }; const handleAbstractEqualityComparison = eql => { const left = this.evaluateExpression(expr.left); if (!left) return; const right = this.evaluateExpression(expr.right); if (!right) return; const res = new BasicEvaluatedExpression(); res.setRange(expr.range); const leftConst = left.isCompileTimeValue(); const rightConst = right.isCompileTimeValue(); if (leftConst && rightConst) { return res .setBoolean( eql === // eslint-disable-next-line eqeqeq (left.asCompileTimeValue() == right.asCompileTimeValue()) ) .setSideEffects( left.couldHaveSideEffects() || right.couldHaveSideEffects() ); } if (left.isArray() && right.isArray()) { return res .setBoolean(!eql) .setSideEffects( left.couldHaveSideEffects() || right.couldHaveSideEffects() ); } if (left.isTemplateString() && right.isTemplateString()) { return handleTemplateStringCompare(left, right, res, eql); } }; if (expr.operator === "+") { const left = this.evaluateExpression(expr.left); if (!left) return; const right = this.evaluateExpression(expr.right); if (!right) return; const res = new BasicEvaluatedExpression(); if (left.isString()) { if (right.isString()) { res.setString(left.string + right.string); } else if (right.isNumber()) { res.setString(left.string + right.number); } else if ( right.isWrapped() && right.prefix && right.prefix.isString() ) { // "left" + ("prefix" + inner + "postfix") // => ("leftPrefix" + inner + "postfix") res.setWrapped( new BasicEvaluatedExpression() .setString(left.string + right.prefix.string) .setRange(joinRanges(left.range, right.prefix.range)), right.postfix, right.wrappedInnerExpressions ); } else if (right.isWrapped()) { // "left" + ([null] + inner + "postfix") // => ("left" + inner + "postfix") res.setWrapped( left, right.postfix, right.wrappedInnerExpressions ); } else { // "left" + expr // => ("left" + expr + "") res.setWrapped(left, null, [right]); } } else if (left.isNumber()) { if (right.isString()) { res.setString(left.number + right.string); } else if (right.isNumber()) { res.setNumber(left.number + right.number); } else { return; } } else if (left.isBigInt()) { if (right.isBigInt()) { res.setBigInt(left.bigint + right.bigint); } } else if (left.isWrapped()) { if (left.postfix && left.postfix.isString() && right.isString()) { // ("prefix" + inner + "postfix") + "right" // => ("prefix" + inner + "postfixRight") res.setWrapped( left.prefix, new BasicEvaluatedExpression() .setString(left.postfix.string + right.string) .setRange(joinRanges(left.postfix.range, right.range)), left.wrappedInnerExpressions ); } else if ( left.postfix && left.postfix.isString() && right.isNumber() ) { // ("prefix" + inner + "postfix") + 123 // => ("prefix" + inner + "postfix123") res.setWrapped( left.prefix, new BasicEvaluatedExpression() .setString(left.postfix.string + right.number) .setRange(joinRanges(left.postfix.range, right.range)), left.wrappedInnerExpressions ); } else if (right.isString()) { // ("prefix" + inner + [null]) + "right" // => ("prefix" + inner + "right") res.setWrapped(left.prefix, right, left.wrappedInnerExpressions); } else if (right.isNumber()) { // ("prefix" + inner + [null]) + 123 // => ("prefix" + inner + "123") res.setWrapped( left.prefix, new BasicEvaluatedExpression() .setString(right.number + "") .setRange(right.range), left.wrappedInnerExpressions ); } else if (right.isWrapped()) { // ("prefix1" + inner1 + "postfix1") + ("prefix2" + inner2 + "postfix2") // ("prefix1" + inner1 + "postfix1" + "prefix2" + inner2 + "postfix2") res.setWrapped( left.prefix, right.postfix, left.wrappedInnerExpressions && right.wrappedInnerExpressions && left.wrappedInnerExpressions .concat(left.postfix ? [left.postfix] : []) .concat(right.prefix ? [right.prefix] : []) .concat(right.wrappedInnerExpressions) ); } else { // ("prefix" + inner + postfix) + expr // => ("prefix" + inner + postfix + expr + [null]) res.setWrapped( left.prefix, null, left.wrappedInnerExpressions && left.wrappedInnerExpressions.concat( left.postfix ? [left.postfix, right] : [right] ) ); } } else { if (right.isString()) { // left + "right" // => ([null] + left + "right") res.setWrapped(null, right, [left]); } else if (right.isWrapped()) { // left + (prefix + inner + "postfix") // => ([null] + left + prefix + inner + "postfix") res.setWrapped( null, right.postfix, right.wrappedInnerExpressions && (right.prefix ? [left, right.prefix] : [left]).concat( right.wrappedInnerExpressions ) ); } else { return; } } if (left.couldHaveSideEffects() || right.couldHaveSideEffects()) res.setSideEffects(); res.setRange(expr.range); return res; } else if (expr.operator === "-") { return handleConstOperation((l, r) => l - r); } else if (expr.operator === "*") { return handleConstOperation((l, r) => l * r); } else if (expr.operator === "/") { return handleConstOperation((l, r) => l / r); } else if (expr.operator === "**") { return handleConstOperation((l, r) => l ** r); } else if (expr.operator === "===") { return handleStrictEqualityComparison(true); } else if (expr.operator === "==") { return handleAbstractEqualityComparison(true); } else if (expr.operator === "!==") { return handleStrictEqualityComparison(false); } else if (expr.operator === "!=") { return handleAbstractEqualityComparison(false); } else if (expr.operator === "&") { return handleConstOperation((l, r) => l & r); } else if (expr.operator === "|") { return handleConstOperation((l, r) => l | r); } else if (expr.operator === "^") { return handleConstOperation((l, r) => l ^ r); } else if (expr.operator === ">>>") { return handleConstOperation((l, r) => l >>> r); } else if (expr.operator === ">>") { return handleConstOperation((l, r) => l >> r); } else if (expr.operator === "<<") { return handleConstOperation((l, r) => l << r); } else if (expr.operator === "<") { return handleConstOperation((l, r) => l < r); } else if (expr.operator === ">") { return handleConstOperation((l, r) => l > r); } else if (expr.operator === "<=") { return handleConstOperation((l, r) => l <= r); } else if (expr.operator === ">=") { return handleConstOperation((l, r) => l >= r); } }); this.hooks.evaluate .for("UnaryExpression") .tap("JavascriptParser", _expr => { const expr = /** @type {UnaryExpressionNode} */ (_expr); const handleConstOperation = fn => { const argument = this.evaluateExpression(expr.argument); if (!argument || !argument.isCompileTimeValue()) return; const result = fn(argument.asCompileTimeValue()); return valueAsExpression( result, expr, argument.couldHaveSideEffects() ); }; if (expr.operator === "typeof") { switch (expr.argument.type) { case "Identifier": { const res = this.callHooksForName( this.hooks.evaluateTypeof, expr.argument.name, expr ); if (res !== undefined) return res; break; } case "MetaProperty": { const res = this.callHooksForName( this.hooks.evaluateTypeof, "import.meta", expr ); if (res !== undefined) return res; break; } case "MemberExpression": { const res = this.callHooksForExpression( this.hooks.evaluateTypeof, expr.argument, expr ); if (res !== undefined) return res; break; } case "ChainExpression": { const res = this.callHooksForExpression( this.hooks.evaluateTypeof, expr.argument.expression, expr ); if (res !== undefined) return res; break; } case "FunctionExpression": { return new BasicEvaluatedExpression() .setString("function") .setRange(expr.range); } } const arg = this.evaluateExpression(expr.argument); if (arg.isUnknown()) return; if (arg.isString()) { return new BasicEvaluatedExpression() .setString("string") .setRange(expr.range); } if (arg.isWrapped()) { return new BasicEvaluatedExpression() .setString("string") .setSideEffects() .setRange(expr.range); } if (arg.isUndefined()) { return new BasicEvaluatedExpression() .setString("undefined") .setRange(expr.range); } if (arg.isNumber()) { return new BasicEvaluatedExpression() .setString("number") .setRange(expr.range); } if (arg.isBigInt()) { return new BasicEvaluatedExpression() .setString("bigint") .setRange(expr.range); } if (arg.isBoolean()) { return new BasicEvaluatedExpression() .setString("boolean") .setRange(expr.range); } if (arg.isConstArray() || arg.isRegExp() || arg.isNull()) { return new BasicEvaluatedExpression() .setString("object") .setRange(expr.range); } if (arg.isArray()) { return new BasicEvaluatedExpression() .setString("object") .setSideEffects(arg.couldHaveSideEffects()) .setRange(expr.range); } } else if (expr.operator === "!") { const argument = this.evaluateExpression(expr.argument); if (!argument) return; const bool = argument.asBool(); if (typeof bool !== "boolean") return; return new BasicEvaluatedExpression() .setBoolean(!bool) .setSideEffects(argument.couldHaveSideEffects()) .setRange(expr.range); } else if (expr.operator === "~") { return handleConstOperation(v => ~v); } else if (expr.operator === "+") { return handleConstOperation(v => +v); } else if (expr.operator === "-") { return handleConstOperation(v => -v); } }); this.hooks.evaluateTypeof.for("undefined").tap("JavascriptParser", expr => { return new BasicEvaluatedExpression() .setString("undefined") .setRange(expr.range); }); /** * @param {string} exprType expression type name * @param {function(ExpressionNode): GetInfoResult | undefined} getInfo get info * @returns {void} */ const tapEvaluateWithVariableInfo = (exprType, getInfo) => { /** @type {ExpressionNode | undefined} */ let cachedExpression = undefined; /** @type {GetInfoResult | undefined} */ let cachedInfo = undefined; this.hooks.evaluate.for(exprType).tap("JavascriptParser", expr => { const expression = /** @type {MemberExpressionNode} */ (expr); const info = getInfo(expr); if (info !== undefined) { return this.callHooksForInfoWithFallback( this.hooks.evaluateIdentifier, info.name, name => { cachedExpression = expression; cachedInfo = info; }, name => { const hook = this.hooks.evaluateDefinedIdentifier.get(name); if (hook !== undefined) { return hook.call(expression); } }, expression ); } }); this.hooks.evaluate .for(exprType) .tap({ name: "JavascriptParser", stage: 100 }, expr => { const info = cachedExpression === expr ? cachedInfo : getInfo(expr); if (info !== undefined) { return new BasicEvaluatedExpression() .setIdentifier(info.name, info.rootInfo, info.getMembers) .setRange(expr.range); } }); }; tapEvaluateWithVariableInfo("Identifier", expr => { const info = this.getVariableInfo( /** @type {IdentifierNode} */ (expr).name ); if ( typeof info === "string" || (info instanceof VariableInfo && typeof info.freeName === "string") ) { return { name: info, rootInfo: info, getMembers: () => [] }; } }); tapEvaluateWithVariableInfo("ThisExpression", expr => { const info = this.getVariableInfo("this"); if ( typeof info === "string" || (info instanceof VariableInfo && typeof info.freeName === "string") ) { return { name: info, rootInfo: info, getMembers: () => [] }; } }); this.hooks.evaluate.for("MetaProperty").tap("JavascriptParser", expr => { const metaProperty = /** @type {MetaPropertyNode} */ (expr); return this.callHooksForName( this.hooks.evaluateIdentifier, getRootName(expr), metaProperty ); }); tapEvaluateWithVariableInfo("MemberExpression", expr => this.getMemberExpressionInfo( /** @type {MemberExpressionNode} */ (expr), ALLOWED_MEMBER_TYPES_EXPRESSION ) ); this.hooks.evaluate.for("CallExpression").tap("JavascriptParser", _expr => { const expr = /** @type {CallExpressionNode} */ (_expr); if ( expr.callee.type !== "MemberExpression" || expr.callee.property.type !== (expr.callee.computed ? "Literal" : "Identifier") ) { return; } // type Super also possible here const param = this.evaluateExpression( /** @type {ExpressionNode} */ (expr.callee.object) ); if (!param) return; const property = expr.callee.property.type === "Literal" ? `${expr.callee.property.value}` : expr.callee.property.name; const hook = this.hooks.evaluateCallExpressionMember.get(property); if (hook !== undefined) { return hook.call(expr, param); } }); this.hooks.evaluateCallExpressionMember .for("indexOf") .tap("JavascriptParser", (expr, param) => { if (!param.isString()) return; if (expr.arguments.length === 0) return; const [arg1, arg2] = expr.arguments; if (arg1.type === "SpreadElement") return; const arg1Eval = this.evaluateExpression(arg1); if (!arg1Eval.isString()) return; const arg1Value = arg1Eval.string; let result; if (arg2) { if (arg2.type === "SpreadElement") return; const arg2Eval = this.evaluateExpression(arg2); if (!arg2Eval.isNumber()) return; result = param.string.indexOf(arg1Value, arg2Eval.number); } else { result = param.string.indexOf(arg1Value); } return new BasicEvaluatedExpression() .setNumber(result) .setSideEffects(param.couldHaveSideEffects()) .setRange(expr.range); }); this.hooks.evaluateCallExpressionMember .for("replace") .tap("JavascriptParser", (expr, param) => { if (!param.isString()) return; if (expr.arguments.length !== 2) return; if (expr.arguments[0].type === "SpreadElement") return; if (expr.arguments[1].type === "SpreadElement") return; let arg1 = this.evaluateExpression(expr.arguments[0]); let arg2 = this.evaluateExpression(expr.arguments[1]); if (!arg1.isString() && !arg1.isRegExp()) return; const arg1Value = arg1.regExp || arg1.string; if (!arg2.isString()) return; const arg2Value = arg2.string; return new BasicEvaluatedExpression() .setString(param.string.replace(arg1Value, arg2Value)) .setSideEffects(param.couldHaveSideEffects()) .setRange(expr.range); }); ["substr", "substring", "slice"].forEach(fn => { this.hooks.evaluateCallExpressionMember .for(fn) .tap("JavascriptParser", (expr, param) => { if (!param.isString()) return; let arg1; let result, str = param.string; switch (expr.arguments.length) { case 1: if (expr.arguments[0].type === "SpreadElement") return; arg1 = this.evaluateExpression(expr.arguments[0]); if (!arg1.isNumber()) return; result = str[fn](arg1.number); break; case 2: { if (expr.arguments[0].type === "SpreadElement") return; if (expr.arguments[1].type === "SpreadElement") return; arg1 = this.evaluateExpression(expr.arguments[0]); const arg2 = this.evaluateExpression(expr.arguments[1]); if (!arg1.isNumber()) return; if (!arg2.isNumber()) return; result = str[fn](arg1.number, arg2.number); break; } default: return; } return new BasicEvaluatedExpression() .setString(result) .setSideEffects(param.couldHaveSideEffects()) .setRange(expr.range); }); }); /** * @param {"cooked" | "raw"} kind kind of values to get * @param {TemplateLiteralNode} templateLiteralExpr TemplateLiteral expr * @returns {{quasis: BasicEvaluatedExpression[], parts: BasicEvaluatedExpression[]}} Simplified template */ const getSimplifiedTemplateResult = (kind, templateLiteralExpr) => { /** @type {BasicEvaluatedExpression[]} */ const quasis = []; /** @type {BasicEvaluatedExpression[]} */ const parts = []; for (let i = 0; i < templateLiteralExpr.quasis.length; i++) { const quasiExpr = templateLiteralExpr.quasis[i]; const quasi = quasiExpr.value[kind]; if (i > 0) { const prevExpr = parts[parts.length - 1]; const expr = this.evaluateExpression( templateLiteralExpr.expressions[i - 1] ); const exprAsString = expr.asString(); if ( typeof exprAsString === "string" && !expr.couldHaveSideEffects() ) { // We can merge quasi + expr + quasi when expr // is a const string prevExpr.setString(prevExpr.string + exprAsString + quasi); prevExpr.setRange([prevExpr.range[0], quasiExpr.range[1]]); // We unset the expression as it doesn't match to a single expression prevExpr.setExpression(undefined); continue; } parts.push(expr); } const part = new BasicEvaluatedExpression() .setString(quasi) .setRange(quasiExpr.range) .setExpression(quasiExpr); quasis.push(part); parts.push(part); } return { quasis, parts }; }; this.hooks.evaluate .for("TemplateLiteral") .tap("JavascriptParser", _node => { const node = /** @type {TemplateLiteralNode} */ (_node); const { quasis, parts } = getSimplifiedTemplateResult("cooked", node); if (parts.length === 1) { return parts[0].setRange(node.range); } return new BasicEvaluatedExpression() .setTemplateString(quasis, parts, "cooked") .setRange(node.range); }); this.hooks.evaluate .for("TaggedTemplateExpression") .tap("JavascriptParser", _node => { const node = /** @type {TaggedTemplateExpressionNode} */ (_node); const tag = this.evaluateExpression(node.tag); if (tag.isIdentifier() && tag.identifier !== "String.raw") return; const { quasis, parts } = getSimplifiedTemplateResult( "raw", node.quasi ); return new BasicEvaluatedExpression() .setTemplateString(quasis, parts, "raw") .setRange(node.range); }); this.hooks.evaluateCallExpressionMember .for("concat") .tap("JavascriptParser", (expr, param) => { if (!param.isString() && !param.isWrapped()) return; let stringSuffix = null; let hasUnknownParams = false; const innerExpressions = []; for (let i = expr.arguments.length - 1; i >= 0; i--) { const arg = expr.arguments[i]; if (arg.type === "SpreadElement") return; const argExpr = this.evaluateExpression(arg); if ( hasUnknownParams || (!argExpr.isString() && !argExpr.isNumber()) ) { hasUnknownParams = true; innerExpressions.push(argExpr); continue; } const value = argExpr.isString() ? argExpr.string : "" + argExpr.number; const newString = value + (stringSuffix ? stringSuffix.string : ""); const newRange = [ argExpr.range[0], (stringSuffix || argExpr).range[1] ]; stringSuffix = new BasicEvaluatedExpression() .setString(newString) .setSideEffects( (stringSuffix && stringSuffix.couldHaveSideEffects()) || argExpr.couldHaveSideEffects() ) .setRange(newRange); } if (hasUnknownParams) { const prefix = param.isString() ? param : param.prefix; const inner = param.isWrapped() && param.wrappedInnerExpressions ? param.wrappedInnerExpressions.concat(innerExpressions.reverse()) : innerExpressions.reverse(); return new BasicEvaluatedExpression() .setWrapped(prefix, stringSuffix, inner) .setRange(expr.range); } else if (param.isWrapped()) { const postfix = stringSuffix || param.postfix; const inner = param.wrappedInnerExpressions ? param.wrappedInnerExpressions.concat(innerExpressions.reverse()) : innerExpressions.reverse(); return new BasicEvaluatedExpression() .setWrapped(param.prefix, postfix, inner) .setRange(expr.range); } else { const newString = param.string + (stringSuffix ? stringSuffix.string : ""); return new BasicEvaluatedExpression() .setString(newString) .setSideEffects( (stringSuffix && stringSuffix.couldHaveSideEffects()) || param.couldHaveSideEffects() ) .setRange(expr.range); } }); this.hooks.evaluateCallExpressionMember .for("split") .tap("JavascriptParser", (expr, param) => { if (!param.isString()) return; if (expr.arguments.length !== 1) return; if (expr.arguments[0].type === "SpreadElement") return; let result; const arg = this.evaluateExpression(expr.arguments[0]); if (arg.isString()) { result = param.string.split(arg.string); } else if (arg.isRegExp()) { result = param.string.split(arg.regExp); } else { return; } return new BasicEvaluatedExpression() .setArray(result) .setSideEffects(param.couldHaveSideEffects()) .setRange(expr.range); }); this.hooks.evaluate .for("ConditionalExpression") .tap("JavascriptParser", _expr => { const expr = /** @type {ConditionalExpressionNode} */ (_expr); const condition = this.evaluateExpression(expr.test); const conditionValue = condition.asBool(); let res; if (conditionValue === undefined) { const consequent = this.evaluateExpression(expr.consequent); const alternate = this.evaluateExpression(expr.alternate); if (!consequent || !alternate) return; res = new BasicEvaluatedExpression(); if (consequent.isConditional()) { res.setOptions(consequent.options); } else { res.setOptions([consequent]); } if (alternate.isConditional()) { res.addOptions(alternate.options); } else { res.addOptions([alternate]); } } else { res = this.evaluateExpression( conditionValue ? expr.consequent : expr.alternate ); if (condition.couldHaveSideEffects()) res.setSideEffects(); } res.setRange(expr.range); return res; }); this.hooks.evaluate .for("ArrayExpression") .tap("JavascriptParser", _expr => { const expr = /** @type {ArrayExpressionNode} */ (_expr); const items = expr.elements.map(element => { return ( element !== null && element.type !== "SpreadElement" && this.evaluateExpression(element) ); }); if (!items.every(Boolean)) return; return new BasicEvaluatedExpression() .setItems(items) .setRange(expr.range); }); this.hooks.evaluate .for("ChainExpression") .tap("JavascriptParser", _expr => { const expr = /** @type {ChainExpressionNode} */ (_expr); /** @type {ExpressionNode[]} */ const optionalExpressionsStack = []; /** @type {ExpressionNode|SuperNode} */ let next = expr.expression; while ( next.type === "MemberExpression" || next.type === "CallExpression" ) { if (next.type === "MemberExpression") { if (next.optional) { // SuperNode can not be optional optionalExpressionsStack.push( /** @type {ExpressionNode} */ (next.object) ); } next = next.object; } else { if (next.optional) { // SuperNode can not be optional optionalExpressionsStack.push( /** @type {ExpressionNode} */ (next.callee) ); } next = next.callee; } } while (optionalExpressionsStack.length > 0) { const expression = optionalExpressionsStack.pop(); const evaluated = this.evaluateExpression(expression); if (evaluated && evaluated.asNullish()) { return evaluated.setRange(_expr.range); } } return this.evaluateExpression(expr.expression); }); } getRenameIdentifier(expr) { const result = this.evaluateExpression(expr); if (result && result.isIdentifier()) { return result.identifier; } } /** * @param {ClassExpressionNode | ClassDeclarationNode} classy a class node * @returns {void} */ walkClass(classy) { if (classy.superClass) { if (!this.hooks.classExtendsExpression.call(classy.superClass, classy)) { this.walkExpression(classy.superClass); } } if (classy.body && classy.body.type === "ClassBody") { const wasTopLevel = this.scope.topLevelScope; for (const classElement of classy.body.body) { if (!this.hooks.classBodyElement.call(classElement, classy)) { if (classElement.type === "MethodDefinition") { this.scope.topLevelScope = false; this.walkMethodDefinition(classElement); this.scope.topLevelScope = wasTopLevel; } // TODO add support for ClassProperty here once acorn supports it } } } } walkMethodDefinition(methodDefinition) { if (methodDefinition.computed && methodDefinition.key) { this.walkExpression(methodDefinition.key); } if (methodDefinition.value) { this.walkExpression(methodDefinition.value); } } // Pre walking iterates the scope for variable declarations preWalkStatements(statements) { for (let index = 0, len = statements.length; index < len; index++) { const statement = statements[index]; this.preWalkStatement(statement); } } // Block pre walking iterates the scope for block variable declarations blockPreWalkStatements(statements) { for (let index = 0, len = statements.length; index < len; index++) { const statement = statements[index]; this.blockPreWalkStatement(statement); } } // Walking iterates the statements and expressions and processes them walkStatements(statements) { for (let index = 0, len = statements.length; index < len; index++) { const statement = statements[index]; this.walkStatement(statement); } } preWalkStatement(statement) { if (this.hooks.preStatement.call(statement)) return; switch (statement.type) { case "BlockStatement": this.preWalkBlockStatement(statement); break; case "DoWhileStatement": this.preWalkDoWhileStatement(statement); break; case "ForInStatement": this.preWalkForInStatement(statement); break; case "ForOfStatement": this.preWalkForOfStatement(statement); break; case "ForStatement": this.preWalkForStatement(statement); break; case "FunctionDeclaration": this.preWalkFunctionDeclaration(statement); break; case "IfStatement": this.preWalkIfStatement(statement); break; case "LabeledStatement": this.preWalkLabeledStatement(statement); break; case "SwitchStatement": this.preWalkSwitchStatement(statement); break; case "TryStatement": this.preWalkTryStatement(statement); break; case "VariableDeclaration": this.preWalkVariableDeclaration(statement); break; case "WhileStatement": this.preWalkWhileStatement(statement); break; case "WithStatement": this.preWalkWithStatement(statement); break; } } blockPreWalkStatement(statement) { if (this.hooks.blockPreStatement.call(statement)) return; switch (statement.type) { case "ImportDeclaration": this.blockPreWalkImportDeclaration(statement); break; case "ExportAllDeclaration": this.blockPreWalkExportAllDeclaration(statement); break; case "ExportDefaultDeclaration": this.blockPreWalkExportDefaultDeclaration(statement); break; case "ExportNamedDeclaration": this.blockPreWalkExportNamedDeclaration(statement); break; case "VariableDeclaration": this.blockPreWalkVariableDeclaration(statement); break; case "ClassDeclaration": this.blockPreWalkClassDeclaration(statement); break; } } walkStatement(statement) { this.statementPath.push(statement); if (this.hooks.statement.call(statement) !== undefined) { this.prevStatement = this.statementPath.pop(); return; } switch (statement.type) { case "BlockStatement": this.walkBlockStatement(statement); break; case "ClassDeclaration": this.walkClassDeclaration(statement); break; case "DoWhileStatement": this.walkDoWhileStatement(statement); break; case "ExportDefaultDeclaration": this.walkExportDefaultDeclaration(statement); break; case "ExportNamedDeclaration": this.walkExportNamedDeclaration(statement); break; case "ExpressionStatement": this.walkExpressionStatement(statement); break; case "ForInStatement": this.walkForInStatement(statement); break; case "ForOfStatement": this.walkForOfStatement(statement); break; case "ForStatement": this.walkForStatement(statement); break; case "FunctionDeclaration": this.walkFunctionDeclaration(statement); break; case "IfStatement": this.walkIfStatement(statement); break; case "LabeledStatement": this.walkLabeledStatement(statement); break; case "ReturnStatement": this.walkReturnStatement(statement); break; case "SwitchStatement": this.walkSwitchStatement(statement); break; case "ThrowStatement": this.walkThrowStatement(statement); break; case "TryStatement": this.walkTryStatement(statement); break; case "VariableDeclaration": this.walkVariableDeclaration(statement); break; case "WhileStatement": this.walkWhileStatement(statement); break; case "WithStatement": this.walkWithStatement(statement); break; } this.prevStatement = this.statementPath.pop(); } // Real Statements preWalkBlockStatement(statement) { this.preWalkStatements(statement.body); } walkBlockStatement(statement) { this.inBlockScope(() => { const body = statement.body; this.blockPreWalkStatements(body); this.walkStatements(body); }); } walkExpressionStatement(statement) { this.walkExpression(statement.expression); } preWalkIfStatement(statement) { this.preWalkStatement(statement.consequent); if (statement.alternate) { this.preWalkStatement(statement.alternate); } } walkIfStatement(statement) { const result = this.hooks.statementIf.call(statement); if (result === undefined) { this.walkExpression(statement.test); this.walkStatement(statement.consequent); if (statement.alternate) { this.walkStatement(statement.alternate); } } else { if (result) { this.walkStatement(statement.consequent); } else if (statement.alternate) { this.walkStatement(statement.alternate); } } } preWalkLabeledStatement(statement) { this.preWalkStatement(statement.body); } walkLabeledStatement(statement) { const hook = this.hooks.label.get(statement.label.name); if (hook !== undefined) { const result = hook.call(statement); if (result === true) return; } this.walkStatement(statement.body); } preWalkWithStatement(statement) { this.preWalkStatement(statement.body); } walkWithStatement(statement) { this.walkExpression(statement.object); this.walkStatement(statement.body); } preWalkSwitchStatement(statement) { this.preWalkSwitchCases(statement.cases); } walkSwitchStatement(statement) { this.walkExpression(statement.discriminant); this.walkSwitchCases(statement.cases); } walkTerminatingStatement(statement) { if (statement.argument) this.walkExpression(statement.argument); } walkReturnStatement(statement) { this.walkTerminatingStatement(statement); } walkThrowStatement(statement) { this.walkTerminatingStatement(statement); } preWalkTryStatement(statement) { this.preWalkStatement(statement.block); if (statement.handler) this.preWalkCatchClause(statement.handler); if (statement.finializer) this.preWalkStatement(statement.finializer); } walkTryStatement(statement) { if (this.scope.inTry) { this.walkStatement(statement.block); } else { this.scope.inTry = true; this.walkStatement(statement.block); this.scope.inTry = false; } if (statement.handler) this.walkCatchClause(statement.handler); if (statement.finalizer) this.walkStatement(statement.finalizer); } preWalkWhileStatement(statement) { this.preWalkStatement(statement.body); } walkWhileStatement(statement) { this.walkExpression(statement.test); this.walkStatement(statement.body); } preWalkDoWhileStatement(statement) { this.preWalkStatement(statement.body); } walkDoWhileStatement(statement) { this.walkStatement(statement.body); this.walkExpression(statement.test); } preWalkForStatement(statement) { if (statement.init) { if (statement.init.type === "VariableDeclaration") { this.preWalkStatement(statement.init); } } this.preWalkStatement(statement.body); } walkForStatement(statement) { this.inBlockScope(() => { if (statement.init) { if (statement.init.type === "VariableDeclaration") { this.blockPreWalkVariableDeclaration(statement.init); this.walkStatement(statement.init); } else { this.walkExpression(statement.init); } } if (statement.test) { this.walkExpression(statement.test); } if (statement.update) { this.walkExpression(statement.update); } const body = statement.body; if (body.type === "BlockStatement") { // no need to add additional scope this.blockPreWalkStatements(body.body); this.walkStatements(body.body); } else { this.walkStatement(body); } }); } preWalkForInStatement(statement) { if (statement.left.type === "VariableDeclaration") { this.preWalkVariableDeclaration(statement.left); } this.preWalkStatement(statement.body); } walkForInStatement(statement) { this.inBlockScope(() => { if (statement.left.type === "VariableDeclaration") { this.blockPreWalkVariableDeclaration(statement.left); this.walkVariableDeclaration(statement.left); } else { this.walkPattern(statement.left); } this.walkExpression(statement.right); const body = statement.body; if (body.type === "BlockStatement") { // no need to add additional scope this.blockPreWalkStatements(body.body); this.walkStatements(body.body); } else { this.walkStatement(body); } }); } preWalkForOfStatement(statement) { if (statement.await && this.scope.topLevelScope === true) { this.hooks.topLevelAwait.call(statement); } if (statement.left.type === "VariableDeclaration") { this.preWalkVariableDeclaration(statement.left); } this.preWalkStatement(statement.body); } walkForOfStatement(statement) { this.inBlockScope(() => { if (statement.left.type === "VariableDeclaration") { this.blockPreWalkVariableDeclaration(statement.left); this.walkVariableDeclaration(statement.left); } else { this.walkPattern(statement.left); } this.walkExpression(statement.right); const body = statement.body; if (body.type === "BlockStatement") { // no need to add additional scope this.blockPreWalkStatements(body.body); this.walkStatements(body.body); } else { this.walkStatement(body); } }); } // Declarations preWalkFunctionDeclaration(statement) { if (statement.id) { this.defineVariable(statement.id.name); } } walkFunctionDeclaration(statement) { const wasTopLevel = this.scope.topLevelScope; this.scope.topLevelScope = false; this.inFunctionScope(true, statement.params, () => { for (const param of statement.params) { this.walkPattern(param); } if (statement.body.type === "BlockStatement") { this.detectMode(statement.body.body); this.preWalkStatement(statement.body); this.walkStatement(statement.body); } else { this.walkExpression(statement.body); } }); this.scope.topLevelScope = wasTopLevel; } blockPreWalkImportDeclaration(statement) { const source = statement.source.value; this.hooks.import.call(statement, source); for (const specifier of statement.specifiers) { const name = specifier.local.name; switch (specifier.type) { case "ImportDefaultSpecifier": if ( !this.hooks.importSpecifier.call(statement, source, "default", name) ) { this.defineVariable(name); } break; case "ImportSpecifier": if ( !this.hooks.importSpecifier.call( statement, source, specifier.imported.name, name ) ) { this.defineVariable(name); } break; case "ImportNamespaceSpecifier": if (!this.hooks.importSpecifier.call(statement, source, null, name)) { this.defineVariable(name); } break; default: this.defineVariable(name); } } } enterDeclaration(declaration, onIdent) { switch (declaration.type) { case "VariableDeclaration": for (const declarator of declaration.declarations) { switch (declarator.type) { case "VariableDeclarator": { this.enterPattern(declarator.id, onIdent); break; } } } break; case "FunctionDeclaration": this.enterPattern(declaration.id, onIdent); break; case "ClassDeclaration": this.enterPattern(declaration.id, onIdent); break; } } blockPreWalkExportNamedDeclaration(statement) { let source; if (statement.source) { source = statement.source.value; this.hooks.exportImport.call(statement, source); } else { this.hooks.export.call(statement); } if (statement.declaration) { if ( !this.hooks.exportDeclaration.call(statement, statement.declaration) ) { this.preWalkStatement(statement.declaration); this.blockPreWalkStatement(statement.declaration); let index = 0; this.enterDeclaration(statement.declaration, def => { this.hooks.exportSpecifier.call(statement, def, def, index++); }); } } if (statement.specifiers) { for ( let specifierIndex = 0; specifierIndex < statement.specifiers.length; specifierIndex++ ) { const specifier = statement.specifiers[specifierIndex]; switch (specifier.type) { case "ExportSpecifier": { const name = specifier.exported.name; if (source) { this.hooks.exportImportSpecifier.call( statement, source, specifier.local.name, name, specifierIndex ); } else { this.hooks.exportSpecifier.call( statement, specifier.local.name, name, specifierIndex ); } break; } } } } } walkExportNamedDeclaration(statement) { if (statement.declaration) { this.walkStatement(statement.declaration); } } blockPreWalkExportDefaultDeclaration(statement) { this.preWalkStatement(statement.declaration); this.blockPreWalkStatement(statement.declaration); if ( statement.declaration.id && statement.declaration.type !== "FunctionExpression" && statement.declaration.type !== "ClassExpression" ) { this.hooks.exportSpecifier.call( statement, statement.declaration.id.name, "default", undefined ); } } walkExportDefaultDeclaration(statement) { this.hooks.export.call(statement); if ( statement.declaration.id && statement.declaration.type !== "FunctionExpression" && statement.declaration.type !== "ClassExpression" ) { if ( !this.hooks.exportDeclaration.call(statement, statement.declaration) ) { this.walkStatement(statement.declaration); } } else { // Acorn parses `export default function() {}` as `FunctionDeclaration` and // `export default class {}` as `ClassDeclaration`, both with `id = null`. // These nodes must be treated as expressions. if ( statement.declaration.type === "FunctionDeclaration" || statement.declaration.type === "ClassDeclaration" ) { this.walkStatement(statement.declaration); } else { this.walkExpression(statement.declaration); } if (!this.hooks.exportExpression.call(statement, statement.declaration)) { this.hooks.exportSpecifier.call( statement, statement.declaration, "default", undefined ); } } } blockPreWalkExportAllDeclaration(statement) { const source = statement.source.value; const name = statement.exported ? statement.exported.name : null; this.hooks.exportImport.call(statement, source); this.hooks.exportImportSpecifier.call(statement, source, null, name, 0); } preWalkVariableDeclaration(statement) { if (statement.kind !== "var") return; this._preWalkVariableDeclaration(statement, this.hooks.varDeclarationVar); } blockPreWalkVariableDeclaration(statement) { if (statement.kind === "var") return; const hookMap = statement.kind === "const" ? this.hooks.varDeclarationConst : this.hooks.varDeclarationLet; this._preWalkVariableDeclaration(statement, hookMap); } _preWalkVariableDeclaration(statement, hookMap) { for (const declarator of statement.declarations) { switch (declarator.type) { case "VariableDeclarator": { if (!this.hooks.preDeclarator.call(declarator, statement)) { this.enterPattern(declarator.id, (name, decl) => { let hook = hookMap.get(name); if (hook === undefined || !hook.call(decl)) { hook = this.hooks.varDeclaration.get(name); if (hook === undefined || !hook.call(decl)) { this.defineVariable(name); } } }); } break; } } } } walkVariableDeclaration(statement) { for (const declarator of statement.declarations) { switch (declarator.type) { case "VariableDeclarator": { const renameIdentifier = declarator.init && this.getRenameIdentifier(declarator.init); if (renameIdentifier && declarator.id.type === "Identifier") { const hook = this.hooks.canRename.get(renameIdentifier); if (hook !== undefined && hook.call(declarator.init)) { // renaming with "var a = b;" const hook = this.hooks.rename.get(renameIdentifier); if (hook === undefined || !hook.call(declarator.init)) { this.setVariable(declarator.id.name, renameIdentifier); } break; } } if (!this.hooks.declarator.call(declarator, statement)) { this.walkPattern(declarator.id); if (declarator.init) this.walkExpression(declarator.init); } break; } } } } blockPreWalkClassDeclaration(statement) { if (statement.id) { this.defineVariable(statement.id.name); } } walkClassDeclaration(statement) { this.walkClass(statement); } preWalkSwitchCases(switchCases) { for (let index = 0, len = switchCases.length; index < len; index++) { const switchCase = switchCases[index]; this.preWalkStatements(switchCase.consequent); } } walkSwitchCases(switchCases) { this.inBlockScope(() => { const len = switchCases.length; // we need to pre walk all statements first since we can have invalid code // import A from "module"; // switch(1) { // case 1: // console.log(A); // should fail at runtime // case 2: // const A = 1; // } for (let index = 0; index < len; index++) { const switchCase = switchCases[index]; if (switchCase.consequent.length > 0) { this.blockPreWalkStatements(switchCase.consequent); } } for (let index = 0; index < len; index++) { const switchCase = switchCases[index]; if (switchCase.test) { this.walkExpression(switchCase.test); } if (switchCase.consequent.length > 0) { this.walkStatements(switchCase.consequent); } } }); } preWalkCatchClause(catchClause) { this.preWalkStatement(catchClause.body); } walkCatchClause(catchClause) { this.inBlockScope(() => { // Error binding is optional in catch clause since ECMAScript 2019 if (catchClause.param !== null) { this.enterPattern(catchClause.param, ident => { this.defineVariable(ident); }); this.walkPattern(catchClause.param); } this.blockPreWalkStatement(catchClause.body); this.walkStatement(catchClause.body); }); } walkPattern(pattern) { switch (pattern.type) { case "ArrayPattern": this.walkArrayPattern(pattern); break; case "AssignmentPattern": this.walkAssignmentPattern(pattern); break; case "MemberExpression": this.walkMemberExpression(pattern); break; case "ObjectPattern": this.walkObjectPattern(pattern); break; case "RestElement": this.walkRestElement(pattern); break; } } walkAssignmentPattern(pattern) { this.walkExpression(pattern.right); this.walkPattern(pattern.left); } walkObjectPattern(pattern) { for (let i = 0, len = pattern.properties.length; i < len; i++) { const prop = pattern.properties[i]; if (prop) { if (prop.computed) this.walkExpression(prop.key); if (prop.value) this.walkPattern(prop.value); } } } walkArrayPattern(pattern) { for (let i = 0, len = pattern.elements.length; i < len; i++) { const element = pattern.elements[i]; if (element) this.walkPattern(element); } } walkRestElement(pattern) { this.walkPattern(pattern.argument); } walkExpressions(expressions) { for (const expression of expressions) { if (expression) { this.walkExpression(expression); } } } walkExpression(expression) { switch (expression.type) { case "ArrayExpression": this.walkArrayExpression(expression); break; case "ArrowFunctionExpression": this.walkArrowFunctionExpression(expression); break; case "AssignmentExpression": this.walkAssignmentExpression(expression); break; case "AwaitExpression": this.walkAwaitExpression(expression); break; case "BinaryExpression": this.walkBinaryExpression(expression); break; case "CallExpression": this.walkCallExpression(expression); break; case "ChainExpression": this.walkChainExpression(expression); break; case "ClassExpression": this.walkClassExpression(expression); break; case "ConditionalExpression": this.walkConditionalExpression(expression); break; case "FunctionExpression": this.walkFunctionExpression(expression); break; case "Identifier": this.walkIdentifier(expression); break; case "ImportExpression": this.walkImportExpression(expression); break; case "LogicalExpression": this.walkLogicalExpression(expression); break; case "MetaProperty": this.walkMetaProperty(expression); break; case "MemberExpression": this.walkMemberExpression(expression); break; case "NewExpression": this.walkNewExpression(expression); break; case "ObjectExpression": this.walkObjectExpression(expression); break; case "SequenceExpression": this.walkSequenceExpression(expression); break; case "SpreadElement": this.walkSpreadElement(expression); break; case "TaggedTemplateExpression": this.walkTaggedTemplateExpression(expression); break; case "TemplateLiteral": this.walkTemplateLiteral(expression); break; case "ThisExpression": this.walkThisExpression(expression); break; case "UnaryExpression": this.walkUnaryExpression(expression); break; case "UpdateExpression": this.walkUpdateExpression(expression); break; case "YieldExpression": this.walkYieldExpression(expression); break; } } walkAwaitExpression(expression) { if (this.scope.topLevelScope === true) this.hooks.topLevelAwait.call(expression); this.walkExpression(expression.argument); } walkArrayExpression(expression) { if (expression.elements) { this.walkExpressions(expression.elements); } } walkSpreadElement(expression) { if (expression.argument) { this.walkExpression(expression.argument); } } walkObjectExpression(expression) { for ( let propIndex = 0, len = expression.properties.length; propIndex < len; propIndex++ ) { const prop = expression.properties[propIndex]; if (prop.type === "SpreadElement") { this.walkExpression(prop.argument); continue; } if (prop.computed) { this.walkExpression(prop.key); } if (prop.shorthand && prop.value && prop.value.type === "Identifier") { this.scope.inShorthand = prop.value.name; this.walkIdentifier(prop.value); this.scope.inShorthand = false; } else { this.walkExpression(prop.value); } } } walkFunctionExpression(expression) { const wasTopLevel = this.scope.topLevelScope; this.scope.topLevelScope = false; const scopeParams = expression.params; // Add function name in scope for recursive calls if (expression.id) { scopeParams.push(expression.id.name); } this.inFunctionScope(true, scopeParams, () => { for (const param of expression.params) { this.walkPattern(param); } if (expression.body.type === "BlockStatement") { this.detectMode(expression.body.body); this.preWalkStatement(expression.body); this.walkStatement(expression.body); } else { this.walkExpression(expression.body); } }); this.scope.topLevelScope = wasTopLevel; } walkArrowFunctionExpression(expression) { const wasTopLevel = this.scope.topLevelScope; this.scope.topLevelScope = wasTopLevel ? "arrow" : false; this.inFunctionScope(false, expression.params, () => { for (const param of expression.params) { this.walkPattern(param); } if (expression.body.type === "BlockStatement") { this.detectMode(expression.body.body); this.preWalkStatement(expression.body); this.walkStatement(expression.body); } else { this.walkExpression(expression.body); } }); this.scope.topLevelScope = wasTopLevel; } /** * @param {SequenceExpressionNode} expression the sequence */ walkSequenceExpression(expression) { if (!expression.expressions) return; // We treat sequence expressions like statements when they are one statement level // This has some benefits for optimizations that only work on statement level const currentStatement = this.statementPath[this.statementPath.length - 1]; if ( currentStatement === expression || (currentStatement.type === "ExpressionStatement" && currentStatement.expression === expression) ) { const old = this.statementPath.pop(); for (const expr of expression.expressions) { this.statementPath.push(expr); this.walkExpression(expr); this.statementPath.pop(); } this.statementPath.push(old); } else { this.walkExpressions(expression.expressions); } } walkUpdateExpression(expression) { this.walkExpression(expression.argument); } walkUnaryExpression(expression) { if (expression.operator === "typeof") { const result = this.callHooksForExpression( this.hooks.typeof, expression.argument, expression ); if (result === true) return; if (expression.argument.type === "ChainExpression") { const result = this.callHooksForExpression( this.hooks.typeof, expression.argument.expression, expression ); if (result === true) return; } } this.walkExpression(expression.argument); } walkLeftRightExpression(expression) { this.walkExpression(expression.left); this.walkExpression(expression.right); } walkBinaryExpression(expression) { this.walkLeftRightExpression(expression); } walkLogicalExpression(expression) { const result = this.hooks.expressionLogicalOperator.call(expression); if (result === undefined) { this.walkLeftRightExpression(expression); } else { if (result) { this.walkExpression(expression.right); } } } walkAssignmentExpression(expression) { if (expression.left.type === "Identifier") { const renameIdentifier = this.getRenameIdentifier(expression.right); if (renameIdentifier) { if ( this.callHooksForInfo( this.hooks.canRename, renameIdentifier, expression.right ) ) { // renaming "a = b;" if ( !this.callHooksForInfo( this.hooks.rename, renameIdentifier, expression.right ) ) { this.setVariable( expression.left.name, this.getVariableInfo(renameIdentifier) ); } return; } } this.walkExpression(expression.right); this.enterPattern(expression.left, (name, decl) => { if (!this.callHooksForName(this.hooks.assign, name, expression)) { this.walkExpression(expression.left); } }); return; } if (expression.left.type.endsWith("Pattern")) { this.walkExpression(expression.right); this.enterPattern(expression.left, (name, decl) => { if (!this.callHooksForName(this.hooks.assign, name, expression)) { this.defineVariable(name); } }); this.walkPattern(expression.left); } else if (expression.left.type === "MemberExpression") { const exprName = this.getMemberExpressionInfo( expression.left, ALLOWED_MEMBER_TYPES_EXPRESSION ); if (exprName) { if ( this.callHooksForInfo( this.hooks.assignMemberChain, exprName.rootInfo, expression, exprName.getMembers() ) ) { return; } } this.walkExpression(expression.right); this.walkExpression(expression.left); } else { this.walkExpression(expression.right); this.walkExpression(expression.left); } } walkConditionalExpression(expression) { const result = this.hooks.expressionConditionalOperator.call(expression); if (result === undefined) { this.walkExpression(expression.test); this.walkExpression(expression.consequent); if (expression.alternate) { this.walkExpression(expression.alternate); } } else { if (result) { this.walkExpression(expression.consequent); } else if (expression.alternate) { this.walkExpression(expression.alternate); } } } walkNewExpression(expression) { const result = this.callHooksForExpression( this.hooks.new, expression.callee, expression ); if (result === true) return; this.walkExpression(expression.callee); if (expression.arguments) { this.walkExpressions(expression.arguments); } } walkYieldExpression(expression) { if (expression.argument) { this.walkExpression(expression.argument); } } walkTemplateLiteral(expression) { if (expression.expressions) { this.walkExpressions(expression.expressions); } } walkTaggedTemplateExpression(expression) { if (expression.tag) { this.walkExpression(expression.tag); } if (expression.quasi && expression.quasi.expressions) { this.walkExpressions(expression.quasi.expressions); } } walkClassExpression(expression) { this.walkClass(expression); } /** * @param {ChainExpressionNode} expression expression */ walkChainExpression(expression) { const result = this.hooks.optionalChaining.call(expression); if (result === undefined) { if (expression.expression.type === "CallExpression") { this.walkCallExpression(expression.expression); } else { this.walkMemberExpression(expression.expression); } } } _walkIIFE(functionExpression, options, currentThis) { const getVarInfo = argOrThis => { const renameIdentifier = this.getRenameIdentifier(argOrThis); if (renameIdentifier) { if ( this.callHooksForInfo( this.hooks.canRename, renameIdentifier, argOrThis ) ) { if ( !this.callHooksForInfo( this.hooks.rename, renameIdentifier, argOrThis ) ) { return this.getVariableInfo(renameIdentifier); } } } this.walkExpression(argOrThis); }; const { params, type } = functionExpression; const arrow = type === "ArrowFunctionExpression"; const renameThis = currentThis ? getVarInfo(currentThis) : null; const varInfoForArgs = options.map(getVarInfo); const wasTopLevel = this.scope.topLevelScope; this.scope.topLevelScope = wasTopLevel && arrow ? "arrow" : false; const scopeParams = params.filter( (identifier, idx) => !varInfoForArgs[idx] ); // Add function name in scope for recursive calls if (functionExpression.id) { scopeParams.push(functionExpression.id.name); } this.inFunctionScope(true, scopeParams, () => { if (renameThis && !arrow) { this.setVariable("this", renameThis); } for (let i = 0; i < varInfoForArgs.length; i++) { const varInfo = varInfoForArgs[i]; if (!varInfo) continue; if (!params[i] || params[i].type !== "Identifier") continue; this.setVariable(params[i].name, varInfo); } if (functionExpression.body.type === "BlockStatement") { this.detectMode(functionExpression.body.body); this.preWalkStatement(functionExpression.body); this.walkStatement(functionExpression.body); } else { this.walkExpression(functionExpression.body); } }); this.scope.topLevelScope = wasTopLevel; } walkImportExpression(expression) { let result = this.hooks.importCall.call(expression); if (result === true) return; this.walkExpression(expression.source); } walkCallExpression(expression) { if ( expression.callee.type === "MemberExpression" && expression.callee.object.type.endsWith("FunctionExpression") && !expression.callee.computed && (expression.callee.property.name === "call" || expression.callee.property.name === "bind") && expression.arguments.length > 0 ) { // (function(…) { }.call/bind(?, …)) this._walkIIFE( expression.callee.object, expression.arguments.slice(1), expression.arguments[0] ); } else if (expression.callee.type.endsWith("FunctionExpression")) { // (function(…) { }(…)) this._walkIIFE(expression.callee, expression.arguments, null); } else { if (expression.callee.type === "MemberExpression") { const exprInfo = this.getMemberExpressionInfo( expression.callee, ALLOWED_MEMBER_TYPES_CALL_EXPRESSION ); if (exprInfo && exprInfo.type === "call") { const result = this.callHooksForInfo( this.hooks.callMemberChainOfCallMemberChain, exprInfo.rootInfo, expression, exprInfo.getCalleeMembers(), exprInfo.call, exprInfo.getMembers() ); if (result === true) return; } } const callee = this.evaluateExpression(expression.callee); if (callee.isIdentifier()) { const result1 = this.callHooksForInfo( this.hooks.callMemberChain, callee.rootInfo, expression, callee.getMembers() ); if (result1 === true) return; const result2 = this.callHooksForInfo( this.hooks.call, callee.identifier, expression ); if (result2 === true) return; } if (expression.callee) { if (expression.callee.type === "MemberExpression") { // because of call context we need to walk the call context as expression this.walkExpression(expression.callee.object); if (expression.callee.computed === true) this.walkExpression(expression.callee.property); } else { this.walkExpression(expression.callee); } } if (expression.arguments) this.walkExpressions(expression.arguments); } } walkMemberExpression(expression) { const exprInfo = this.getMemberExpressionInfo( expression, ALLOWED_MEMBER_TYPES_ALL ); if (exprInfo) { switch (exprInfo.type) { case "expression": { const result1 = this.callHooksForInfo( this.hooks.expression, exprInfo.name, expression ); if (result1 === true) return; const members = exprInfo.getMembers(); const result2 = this.callHooksForInfo( this.hooks.expressionMemberChain, exprInfo.rootInfo, expression, members ); if (result2 === true) return; this.walkMemberExpressionWithExpressionName( expression, exprInfo.name, exprInfo.rootInfo, members.slice(), () => this.callHooksForInfo( this.hooks.unhandledExpressionMemberChain, exprInfo.rootInfo, expression, members ) ); return; } case "call": { const result = this.callHooksForInfo( this.hooks.memberChainOfCallMemberChain, exprInfo.rootInfo, expression, exprInfo.getCalleeMembers(), exprInfo.call, exprInfo.getMembers() ); if (result === true) return; // Fast skip over the member chain as we already called memberChainOfCallMemberChain // and call computed property are literals anyway this.walkExpression(exprInfo.call); return; } } } this.walkExpression(expression.object); if (expression.computed === true) this.walkExpression(expression.property); } walkMemberExpressionWithExpressionName( expression, name, rootInfo, members, onUnhandled ) { if (expression.object.type === "MemberExpression") { // optimize the case where expression.object is a MemberExpression too. // we can keep info here when calling walkMemberExpression directly const property = expression.property.name || `${expression.property.value}`; name = name.slice(0, -property.length - 1); members.pop(); const result = this.callHooksForInfo( this.hooks.expression, name, expression.object ); if (result === true) return; this.walkMemberExpressionWithExpressionName( expression.object, name, rootInfo, members, onUnhandled ); } else if (!onUnhandled || !onUnhandled()) { this.walkExpression(expression.object); } if (expression.computed === true) this.walkExpression(expression.property); } walkThisExpression(expression) { this.callHooksForName(this.hooks.expression, "this", expression); } walkIdentifier(expression) { this.callHooksForName(this.hooks.expression, expression.name, expression); } /** * @param {MetaPropertyNode} metaProperty meta property */ walkMetaProperty(metaProperty) { this.hooks.expression.for(getRootName(metaProperty)).call(metaProperty); } callHooksForExpression(hookMap, expr, ...args) { return this.callHooksForExpressionWithFallback( hookMap, expr, undefined, undefined, ...args ); } /** * @template T * @template R * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called * @param {MemberExpressionNode} expr expression info * @param {function(string, string | ScopeInfo | VariableInfo, function(): string[]): any} fallback callback when variable in not handled by hooks * @param {function(string): any} defined callback when variable is defined * @param {AsArray<T>} args args for the hook * @returns {R} result of hook */ callHooksForExpressionWithFallback( hookMap, expr, fallback, defined, ...args ) { const exprName = this.getMemberExpressionInfo( expr, ALLOWED_MEMBER_TYPES_EXPRESSION ); if (exprName !== undefined) { const members = exprName.getMembers(); return this.callHooksForInfoWithFallback( hookMap, members.length === 0 ? exprName.rootInfo : exprName.name, fallback && (name => fallback(name, exprName.rootInfo, exprName.getMembers)), defined && (() => defined(exprName.name)), ...args ); } } /** * @template T * @template R * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called * @param {string} name key in map * @param {AsArray<T>} args args for the hook * @returns {R} result of hook */ callHooksForName(hookMap, name, ...args) { return this.callHooksForNameWithFallback( hookMap, name, undefined, undefined, ...args ); } /** * @template T * @template R * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks that should be called * @param {ExportedVariableInfo} info variable info * @param {AsArray<T>} args args for the hook * @returns {R} result of hook */ callHooksForInfo(hookMap, info, ...args) { return this.callHooksForInfoWithFallback( hookMap, info, undefined, undefined, ...args ); } /** * @template T * @template R * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called * @param {ExportedVariableInfo} info variable info * @param {function(string): any} fallback callback when variable in not handled by hooks * @param {function(): any} defined callback when variable is defined * @param {AsArray<T>} args args for the hook * @returns {R} result of hook */ callHooksForInfoWithFallback(hookMap, info, fallback, defined, ...args) { let name; if (typeof info === "string") { name = info; } else { if (!(info instanceof VariableInfo)) { if (defined !== undefined) { return defined(); } return; } let tagInfo = info.tagInfo; while (tagInfo !== undefined) { const hook = hookMap.get(tagInfo.tag); if (hook !== undefined) { this.currentTagData = tagInfo.data; const result = hook.call(...args); this.currentTagData = undefined; if (result !== undefined) return result; } tagInfo = tagInfo.next; } if (info.freeName === true) { if (defined !== undefined) { return defined(); } return; } name = info.freeName; } const hook = hookMap.get(name); if (hook !== undefined) { const result = hook.call(...args); if (result !== undefined) return result; } if (fallback !== undefined) { return fallback(name); } } /** * @template T * @template R * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called * @param {string} name key in map * @param {function(string): any} fallback callback when variable in not handled by hooks * @param {function(): any} defined callback when variable is defined * @param {AsArray<T>} args args for the hook * @returns {R} result of hook */ callHooksForNameWithFallback(hookMap, name, fallback, defined, ...args) { return this.callHooksForInfoWithFallback( hookMap, this.getVariableInfo(name), fallback, defined, ...args ); } /** * @deprecated * @param {any} params scope params * @param {function(): void} fn inner function * @returns {void} */ inScope(params, fn) { const oldScope = this.scope; this.scope = { topLevelScope: oldScope.topLevelScope, inTry: false, inShorthand: false, isStrict: oldScope.isStrict, isAsmJs: oldScope.isAsmJs, definitions: oldScope.definitions.createChild() }; this.undefineVariable("this"); this.enterPatterns(params, (ident, pattern) => { this.defineVariable(ident); }); fn(); this.scope = oldScope; } inFunctionScope(hasThis, params, fn) { const oldScope = this.scope; this.scope = { topLevelScope: oldScope.topLevelScope, inTry: false, inShorthand: false, isStrict: oldScope.isStrict, isAsmJs: oldScope.isAsmJs, definitions: oldScope.definitions.createChild() }; if (hasThis) { this.undefineVariable("this"); } this.enterPatterns(params, (ident, pattern) => { this.defineVariable(ident); }); fn(); this.scope = oldScope; } inBlockScope(fn) { const oldScope = this.scope; this.scope = { topLevelScope: oldScope.topLevelScope, inTry: oldScope.inTry, inShorthand: false, isStrict: oldScope.isStrict, isAsmJs: oldScope.isAsmJs, definitions: oldScope.definitions.createChild() }; fn(); this.scope = oldScope; } detectMode(statements) { const isLiteral = statements.length >= 1 && statements[0].type === "ExpressionStatement" && statements[0].expression.type === "Literal"; if (isLiteral && statements[0].expression.value === "use strict") { this.scope.isStrict = true; } if (isLiteral && statements[0].expression.value === "use asm") { this.scope.isAsmJs = true; } } enterPatterns(patterns, onIdent) { for (const pattern of patterns) { if (typeof pattern !== "string") { this.enterPattern(pattern, onIdent); } else if (pattern) { onIdent(pattern); } } } enterPattern(pattern, onIdent) { if (!pattern) return; switch (pattern.type) { case "ArrayPattern": this.enterArrayPattern(pattern, onIdent); break; case "AssignmentPattern": this.enterAssignmentPattern(pattern, onIdent); break; case "Identifier": this.enterIdentifier(pattern, onIdent); break; case "ObjectPattern": this.enterObjectPattern(pattern, onIdent); break; case "RestElement": this.enterRestElement(pattern, onIdent); break; case "Property": if (pattern.shorthand && pattern.value.type === "Identifier") { this.scope.inShorthand = pattern.value.name; this.enterIdentifier(pattern.value, onIdent); this.scope.inShorthand = false; } else { this.enterPattern(pattern.value, onIdent); } break; } } enterIdentifier(pattern, onIdent) { if (!this.callHooksForName(this.hooks.pattern, pattern.name, pattern)) { onIdent(pattern.name, pattern); } } enterObjectPattern(pattern, onIdent) { for ( let propIndex = 0, len = pattern.properties.length; propIndex < len; propIndex++ ) { const prop = pattern.properties[propIndex]; this.enterPattern(prop, onIdent); } } enterArrayPattern(pattern, onIdent) { for ( let elementIndex = 0, len = pattern.elements.length; elementIndex < len; elementIndex++ ) { const element = pattern.elements[elementIndex]; this.enterPattern(element, onIdent); } } enterRestElement(pattern, onIdent) { this.enterPattern(pattern.argument, onIdent); } enterAssignmentPattern(pattern, onIdent) { this.enterPattern(pattern.left, onIdent); } /** * @param {ExpressionNode} expression expression node * @returns {BasicEvaluatedExpression | undefined} evaluation result */ evaluateExpression(expression) { try { const hook = this.hooks.evaluate.get(expression.type); if (hook !== undefined) { const result = hook.call(expression); if (result !== undefined) { if (result) { result.setExpression(expression); } return result; } } } catch (e) { console.warn(e); // ignore error } return new BasicEvaluatedExpression() .setRange(expression.range) .setExpression(expression); } parseString(expression) { switch (expression.type) { case "BinaryExpression": if (expression.operator === "+") { return ( this.parseString(expression.left) + this.parseString(expression.right) ); } break; case "Literal": return expression.value + ""; } throw new Error( expression.type + " is not supported as parameter for require" ); } parseCalculatedString(expression) { switch (expression.type) { case "BinaryExpression": if (expression.operator === "+") { const left = this.parseCalculatedString(expression.left); const right = this.parseCalculatedString(expression.right); if (left.code) { return { range: left.range, value: left.value, code: true, conditional: false }; } else if (right.code) { return { range: [ left.range[0], right.range ? right.range[1] : left.range[1] ], value: left.value + right.value, code: true, conditional: false }; } else { return { range: [left.range[0], right.range[1]], value: left.value + right.value, code: false, conditional: false }; } } break; case "ConditionalExpression": { const consequent = this.parseCalculatedString(expression.consequent); const alternate = this.parseCalculatedString(expression.alternate); const items = []; if (consequent.conditional) { items.push(...consequent.conditional); } else if (!consequent.code) { items.push(consequent); } else { break; } if (alternate.conditional) { items.push(...alternate.conditional); } else if (!alternate.code) { items.push(alternate); } else { break; } return { range: undefined, value: "", code: true, conditional: items }; } case "Literal": return { range: expression.range, value: expression.value + "", code: false, conditional: false }; } return { range: undefined, value: "", code: true, conditional: false }; } /** * @param {string | Buffer | PreparsedAst} source the source to parse * @param {ParserState} state the parser state * @returns {ParserState} the parser state */ parse(source, state) { let ast; let comments; const semicolons = new Set(); if (source === null) { throw new Error("source must not be null"); } if (Buffer.isBuffer(source)) { source = source.toString("utf-8"); } if (typeof source === "object") { ast = /** @type {ProgramNode} */ (source); comments = source.comments; } else { comments = []; ast = JavascriptParser._parse(source, { sourceType: this.sourceType, onComment: comments, onInsertedSemicolon: pos => semicolons.add(pos) }); } const oldScope = this.scope; const oldState = this.state; const oldComments = this.comments; const oldSemicolons = this.semicolons; const oldStatementPath = this.statementPath; const oldPrevStatement = this.prevStatement; this.scope = { topLevelScope: true, inTry: false, inShorthand: false, isStrict: false, isAsmJs: false, definitions: new StackedMap() }; /** @type {ParserState} */ this.state = state; this.comments = comments; this.semicolons = semicolons; this.statementPath = []; this.prevStatement = undefined; if (this.hooks.program.call(ast, comments) === undefined) { this.detectMode(ast.body); this.preWalkStatements(ast.body); this.blockPreWalkStatements(ast.body); this.walkStatements(ast.body); } this.hooks.finish.call(ast, comments); this.scope = oldScope; /** @type {ParserState} */ this.state = oldState; this.comments = oldComments; this.semicolons = oldSemicolons; this.statementPath = oldStatementPath; this.prevStatement = oldPrevStatement; return state; } evaluate(source) { const ast = JavascriptParser._parse("(" + source + ")", { sourceType: this.sourceType, locations: false }); if (ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement") { throw new Error("evaluate: Source is not a expression"); } return this.evaluateExpression(ast.body[0].expression); } /** * @param {ExpressionNode | DeclarationNode | null | undefined} expr an expression * @param {number} commentsStartPos source position from which annotation comments are checked * @returns {boolean} true, when the expression is pure */ isPure(expr, commentsStartPos) { if (!expr) return true; const result = this.hooks.isPure .for(expr.type) .call(expr, commentsStartPos); if (typeof result === "boolean") return result; switch (expr.type) { case "ClassDeclaration": case "ClassExpression": if (expr.body.type !== "ClassBody") return false; if (expr.superClass && !this.isPure(expr.superClass, expr.range[0])) { return false; } return expr.body.body.every(item => { switch (item.type) { // @ts-expect-error not yet supported by acorn case "ClassProperty": // TODO add test case once acorn supports it // Currently this is not parsable if (item.static) return this.isPure(item.value, item.range[0]); break; } return true; }); case "FunctionDeclaration": case "FunctionExpression": case "ArrowFunctionExpression": case "Literal": return true; case "VariableDeclaration": return expr.declarations.every(decl => this.isPure(decl.init, decl.range[0]) ); case "ConditionalExpression": return ( this.isPure(expr.test, commentsStartPos) && this.isPure(expr.consequent, expr.test.range[1]) && this.isPure(expr.alternate, expr.consequent.range[1]) ); case "SequenceExpression": return expr.expressions.every(expr => { const pureFlag = this.isPure(expr, commentsStartPos); commentsStartPos = expr.range[1]; return pureFlag; }); case "CallExpression": { const pureFlag = expr.range[0] - commentsStartPos > 12 && this.getComments([commentsStartPos, expr.range[0]]).some( comment => comment.type === "Block" && /^\s*(#|@)__PURE__\s*$/.test(comment.value) ); if (!pureFlag) return false; commentsStartPos = expr.callee.range[1]; return expr.arguments.every(arg => { if (arg.type === "SpreadElement") return false; const pureFlag = this.isPure(arg, commentsStartPos); commentsStartPos = arg.range[1]; return pureFlag; }); } } const evaluated = this.evaluateExpression(expr); return !evaluated.couldHaveSideEffects(); } getComments(range) { return this.comments.filter( comment => comment.range[0] >= range[0] && comment.range[1] <= range[1] ); } /** * @param {number} pos source code position * @returns {boolean} true when a semicolon has been inserted before this position, false if not */ isAsiPosition(pos) { if (this.prevStatement === undefined) return false; const currentStatement = this.statementPath[this.statementPath.length - 1]; return ( currentStatement.range[0] === pos && this.semicolons.has(this.prevStatement.range[1]) ); } isStatementLevelExpression(expr) { const currentStatement = this.statementPath[this.statementPath.length - 1]; return ( expr === currentStatement || (currentStatement.type === "ExpressionStatement" && currentStatement.expression === expr) ); } getTagData(name, tag) { const info = this.scope.definitions.get(name); if (info instanceof VariableInfo) { let tagInfo = info.tagInfo; while (tagInfo !== undefined) { if (tagInfo.tag === tag) return tagInfo.data; tagInfo = tagInfo.next; } } } tagVariable(name, tag, data) { const oldInfo = this.scope.definitions.get(name); /** @type {VariableInfo} */ let newInfo; if (oldInfo === undefined) { newInfo = new VariableInfo(this.scope, name, { tag, data, next: undefined }); } else if (oldInfo instanceof VariableInfo) { newInfo = new VariableInfo(oldInfo.declaredScope, oldInfo.freeName, { tag, data, next: oldInfo.tagInfo }); } else { newInfo = new VariableInfo(oldInfo, true, { tag, data, next: undefined }); } this.scope.definitions.set(name, newInfo); } defineVariable(name) { const oldInfo = this.scope.definitions.get(name); // Don't redefine variable in same scope to keep existing tags if (oldInfo instanceof VariableInfo && oldInfo.declaredScope === this.scope) return; this.scope.definitions.set(name, this.scope); } undefineVariable(name) { this.scope.definitions.delete(name); } isVariableDefined(name) { const info = this.scope.definitions.get(name); if (info === undefined) return false; if (info instanceof VariableInfo) { return info.freeName === true; } return true; } /** * @param {string} name variable name * @returns {ExportedVariableInfo} info for this variable */ getVariableInfo(name) { const value = this.scope.definitions.get(name); if (value === undefined) { return name; } else { return value; } } /** * @param {string} name variable name * @param {ExportedVariableInfo} variableInfo new info for this variable * @returns {void} */ setVariable(name, variableInfo) { if (typeof variableInfo === "string") { if (variableInfo === name) { this.scope.definitions.delete(name); } else { this.scope.definitions.set( name, new VariableInfo(this.scope, variableInfo, undefined) ); } } else { this.scope.definitions.set(name, variableInfo); } } parseCommentOptions(range) { const comments = this.getComments(range); if (comments.length === 0) { return EMPTY_COMMENT_OPTIONS; } let options = {}; let errors = []; for (const comment of comments) { const { value } = comment; if (value && webpackCommentRegExp.test(value)) { // try compile only if webpack options comment is present try { const val = vm.runInNewContext(`(function(){return {${value}};})()`); Object.assign(options, val); } catch (e) { e.comment = comment; errors.push(e); } } } return { options, errors }; } /** * @param {MemberExpressionNode} expression a member expression * @returns {{ members: string[], object: ExpressionNode | SuperNode }} member names (reverse order) and remaining object */ extractMemberExpressionChain(expression) { /** @type {AnyNode} */ let expr = expression; const members = []; while (expr.type === "MemberExpression") { if (expr.computed) { if (expr.property.type !== "Literal") break; members.push(`${expr.property.value}`); } else { if (expr.property.type !== "Identifier") break; members.push(expr.property.name); } expr = expr.object; } return { members, object: expr }; } /** * @param {string} varName variable name * @returns {{name: string, info: VariableInfo | string}} name of the free variable and variable info for that */ getFreeInfoFromVariable(varName) { const info = this.getVariableInfo(varName); let name; if (info instanceof VariableInfo) { name = info.freeName; if (typeof name !== "string") return undefined; } else if (typeof info !== "string") { return undefined; } else { name = info; } return { info, name }; } /** @typedef {{ type: "call", call: CallExpressionNode, calleeName: string, rootInfo: string | VariableInfo, getCalleeMembers: () => string[], name: string, getMembers: () => string[]}} CallExpressionInfo */ /** @typedef {{ type: "expression", rootInfo: string | VariableInfo, name: string, getMembers: () => string[]}} ExpressionExpressionInfo */ /** * @param {MemberExpressionNode} expression a member expression * @param {number} allowedTypes which types should be returned, presented in bit mask * @returns {CallExpressionInfo | ExpressionExpressionInfo | undefined} expression info */ getMemberExpressionInfo(expression, allowedTypes) { const { object, members } = this.extractMemberExpressionChain(expression); switch (object.type) { case "CallExpression": { if ((allowedTypes & ALLOWED_MEMBER_TYPES_CALL_EXPRESSION) === 0) return undefined; let callee = object.callee; let rootMembers = EMPTY_ARRAY; if (callee.type === "MemberExpression") { ({ object: callee, members: rootMembers } = this.extractMemberExpressionChain(callee)); } const rootName = getRootName(callee); if (!rootName) return undefined; const result = this.getFreeInfoFromVariable(rootName); if (!result) return undefined; const { info: rootInfo, name: resolvedRoot } = result; const calleeName = objectAndMembersToName(resolvedRoot, rootMembers); return { type: "call", call: object, calleeName, rootInfo, getCalleeMembers: memorize(() => rootMembers.reverse()), name: objectAndMembersToName(`${calleeName}()`, members), getMembers: memorize(() => members.reverse()) }; } case "Identifier": case "MetaProperty": case "ThisExpression": { if ((allowedTypes & ALLOWED_MEMBER_TYPES_EXPRESSION) === 0) return undefined; const rootName = getRootName(object); if (!rootName) return undefined; const result = this.getFreeInfoFromVariable(rootName); if (!result) return undefined; const { info: rootInfo, name: resolvedRoot } = result; return { type: "expression", name: objectAndMembersToName(resolvedRoot, members), rootInfo, getMembers: memorize(() => members.reverse()) }; } } } /** * @param {MemberExpressionNode} expression an expression * @returns {{ name: string, rootInfo: ExportedVariableInfo, getMembers: () => string[]}} name info */ getNameForExpression(expression) { return this.getMemberExpressionInfo( expression, ALLOWED_MEMBER_TYPES_EXPRESSION ); } /** * @param {string} code source code * @param {ParseOptions} options parsing options * @returns {ProgramNode} parsed ast */ static _parse(code, options) { const type = options ? options.sourceType : "module"; /** @type {AcornOptions} */ const parserOptions = { ...defaultParserOptions, allowReturnOutsideFunction: type === "script", ...options, sourceType: type === "auto" ? "module" : type }; /** @type {AnyNode} */ let ast; let error; let threw = false; try { ast = /** @type {AnyNode} */ (parser.parse(code, parserOptions)); } catch (e) { error = e; threw = true; } if (threw && type === "auto") { parserOptions.sourceType = "script"; if (!("allowReturnOutsideFunction" in options)) { parserOptions.allowReturnOutsideFunction = true; } if (Array.isArray(parserOptions.onComment)) { parserOptions.onComment.length = 0; } try { ast = /** @type {AnyNode} */ (parser.parse(code, parserOptions)); threw = false; } catch (e) { // we use the error from first parse try // so nothing to do here } } if (threw) { throw error; } return /** @type {ProgramNode} */ (ast); } } module.exports = JavascriptParser; module.exports.ALLOWED_MEMBER_TYPES_ALL = ALLOWED_MEMBER_TYPES_ALL; module.exports.ALLOWED_MEMBER_TYPES_EXPRESSION = ALLOWED_MEMBER_TYPES_EXPRESSION; module.exports.ALLOWED_MEMBER_TYPES_CALL_EXPRESSION = ALLOWED_MEMBER_TYPES_CALL_EXPRESSION;
/*! drawbit v1.0.0 2013-10-05 */ /*globals console:false */ (function (db) { 'use strict'; /** * Represents an Alphabit * @constructor * @param {Enum} options - Alphabit options * @return {Object} Exposed methods */ db.Alphabit = function Alphabit(options) { /** * Layer Canvas Element * @type {HTMLCanvasElement} */ var canvas, /** * Canvas Context * @type {CanvasRenderingContext2D} */ context, /** * Source image * @type {HTMLImage} */ source, /** * Processed letters * @type {Object} */ letters = {}, /** * Default Settings * @type {Enum} */ SETTINGS = { padding: 1, width: 7, height: 7, color: '0,0,0,255', image: 'img/alphabet.png', onComplete: function(){} }, /** * Available letters * @type {Array} */ LETTERS = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']; /** * @construcs db.Alphabit */ (function() { Object.extend(SETTINGS, options); canvas = document.createElement('canvas'); context = canvas.getContext('2d'); createSpecialCharacter('space'); createSpecialCharacter('delete'); addEventListeners(); }()); /** * Attach event handlers */ function addEventListeners() { source = document.createElement('img'); source.addEventListener('load', source_loadHandler); source.addEventListener('error', source_errorHandler); source.src = SETTINGS.image; } /** * Add special keys (scape, delete) * @param {String} key - The special char */ function createSpecialCharacter(key) { var i = 0, j = 0, colCollection = [], rowCollection = [], flag = 0; for ( ; i < SETTINGS.width; i++ ) { colCollection = []; for ( j = 0; j < SETTINGS.height; j++ ) { colCollection.push(flag); } rowCollection.push(colCollection); } letters[key] = rowCollection; } /** * Process alphabet image */ function process() { var i = 0, row = 0, col = 0, numLetter = 0, result = [], rowCollection = [], dataLength, flag = 0; canvas.width = source.width; canvas.height = source.height; // Draw image into canvas context.drawImage(source, 0, 0, source.width, source.height); var imageData = context.getImageData(0, 0, canvas.width, canvas.height).data; dataLength = imageData.length; for ( ; i < dataLength; i+=4 ) { // rgba flag = ([imageData[i], imageData[i+1], imageData[i+2], imageData[i+3]].toString() === SETTINGS.color) ? 1 : 0; // next col rowCollection.push(flag); col++; // next row if (col % SETTINGS.width === 0) { result.push(rowCollection); rowCollection = []; row++; // next letter if (row % (SETTINGS.height+SETTINGS.padding) === 0) { letters[LETTERS[numLetter]] = result; result = []; numLetter++; } } } if (typeof SETTINGS.onComplete === 'function') { SETTINGS.onComplete(); } } /** * Image loaded * @event */ function source_loadHandler(e) { process(); } /** * Image error * @event */ function source_errorHandler(e) { console.log("Error loading alphabet.png"); } // public methods and properties return letters; }; }(window.db = window.db || {})); /*globals console:false */ (function (db) { 'use strict'; /** * Represents the configuration * @constructor * @return {Object} Exposed methods */ db.Config = function(value) { /** * Configuration Data * @type {db.gui.Layers} */ var data; /** * @construcs db.Config */ (function () { parseConfig(); }()); /** * Parse config JSON file */ function parseConfig() { data = value; console.log("data: ", data); } // public methods and properties return { }; }; }(window.db = window.db || {})); (function (db) { 'use strict'; /** * Represents an Effect * @constructor * @param {db.Layer} target - The target Layer * @param {Enum} options - effect options * @return {Object} Exposed methods */ db.Effect = function(target, options, _time) { /** * Tile Identifier * @type {String} */ var id = 'tile', /** * Frame interval */ requestID, /** * Number of tiles finished * @type {Number} */ completedTiles = 0, /** * Tiles to be processed * @type {Array} */ tiles = [], /** * Checks if the all tiles has been completed * @type {Number} */ isCompleted, /** * Transition time * @type {Number} of miliseconds */ time = _time || 1000; /** * @construcs db.Effect */ (function () { var numTiles = target.tiles.length; while (numTiles-- > 0) { tiles.push(new db.effects[options.type](target.tiles[numTiles], target.context, options, time)); } if (options.delay) { setTimeout(start, options.delay); } else { start(); } }()); /** * Start transition */ function start() { requestID = window.requestAnimationFrame(render); } /** * Stop transition * @return {[type]} [description] */ function stop() { requestID = window.cancelAnimationFrame(requestID); } /** * Update / frame loop */ function render() { next(); if (requestID && !isCompleted) { window.requestAnimationFrame(render); } } /** * Render next frame */ function next() { var numTiles = tiles.length; if (completedTiles >= numTiles) { isCompleted = true; } while (numTiles-- > 0) { if (tiles[numTiles] && !tiles[numTiles].complete()) { tiles[numTiles].update(); if (tiles[numTiles] && tiles[numTiles].complete()) { completedTiles++; } } } } // public methods and properties return { id: id, next: next }; }; }(window.db = window.db || {})); (function (db) { 'use strict'; /** * @namespace Effects */ db.effects = db.effects || {}; /** * Represents a Fade Effect * @constructor * @param {db.Tile} Context - The tile * @param {CanvasRenderingContext2D} Context - The tile context (canvas) * @param {Enum} options - Tile options * @param {Number} time - Transition time * * @return {Object} Exposed methods */ db.effects.Fade = function(tile, context, options, time) { /** * Frame duration * @type {Float} */ var stepSize = 600 / time, /** * Transition completed * @type {Boolean} */ isCompleted, /** * Current alpha * @type {Number} */ alpha = 10; /** * @construcs db.Tile */ (function () { reset(); draw(); }()); /** * Reset effect * @private */ function reset() { isCompleted = false; alpha = 10; } /** * Draws a frame */ function draw() { context.clearRect(tile.x, tile.y, tile.width, tile.height); context.fillStyle = 'rgba(' + tile.color + ',' + alpha/10 + ')'; context.fillRect(tile.x, tile.y, tile.width, tile.height); if (alpha <= 0) { isCompleted = true; } alpha -= stepSize; } /** * Effect already completed? * @return {Boolean} */ function complete() { return isCompleted; } // public methods and properties return { update: draw, complete: complete }; }; }(window.db = window.db || {})); (function (db) { 'use strict'; /** * @namespace Effects */ db.effects = db.effects || {}; /** * Represents a Flip Effect * @constructor * @param {db.Tile} Context - The tile * @param {CanvasRenderingContext2D} Context - The tile context (canvas) * @param {Enum} options - Tile options * @param {Number} time - Transition time * * @return {Object} Exposed methods */ db.effects.Flip = function(tile, context, options, time) { /** * Delta * @type {Number} */ var delta = 0, /** * Previous bounds * @type {Object} */ initialBounds = {}, /** * Current bounds * @type {Object} */ bounds = {}, /** * Transition Speed * @type {Number} */ stepSize = 0.5, /** * Tile reachs the half transition * @type {Boolean} */ isFlipped, /** * Tile transition completed * @type {Boolean} */ isCompleted, /** * Current tile color * @type {String} */ currentColor = tile.color, /** * flipped * @type {Boolean} */ isBack = false ; /** * @construcs db.Tile */ (function () { reset(); draw(); initialBounds = JSON.stringify(bounds); }()); /** * Reset effect */ function reset() { bounds = { t: 0, b: 0, tl: 0, bl: 0, tr: 0, br: 0 }; context.fillStyle = isBack ? options.back : tile.color; delta = 0; isFlipped = false; isCompleted = false; } /** * Draws a frame * @type {Function} fnHalf - Flip ocurs */ function draw(fnHalf) { context.clearRect(tile.x, tile.y, tile.width, tile.height); // halfway if (!isFlipped && bounds.b < bounds.t) { if (currentColor === tile.color) { currentColor = options.back; } else { currentColor = tile.color; } context.fillStyle = currentColor; isFlipped = true; if (typeof fnHalf === 'function') { fnHalf(); } } if (!isFlipped) { bounds.t = tile.y + delta; bounds.b = tile.y + tile.height - delta; bounds.tl = tile.x; bounds.bl = tile.x + delta; bounds.tr = tile.x + tile.width; bounds.br = tile.x + tile.width - delta; } else { bounds.t = tile.y + tile.height - delta; bounds.b = tile.y + delta; bounds.tl = tile.x + tile.width - delta; bounds.bl = tile.x; bounds.br = tile.x + tile.width; bounds.tr = tile.x + delta; } context.beginPath(); context.moveTo(bounds.tl, bounds.t); // left edge context.lineTo(bounds.bl, bounds.b); // bottom edge context.lineTo(bounds.br, bounds.b); // right edge context.lineTo(bounds.tr, bounds.t); // top edge context.closePath(); context.fill(); if (isFlipped && initialBounds === JSON.stringify(bounds)) { isCompleted = true; isBack = true; } delta = delta + stepSize; } /** * Effect already completed? * @return {Boolean} */ function complete() { return isCompleted; } // public methods and properties return { update: draw, complete: complete }; }; }(window.db = window.db || {})); (function (db) { 'use strict'; /** * Represents a canvas grid * @constructor * @param {String} selector - The HTML selector * @param {Enum} options - Grid options * @return {Object} Exposed methods */ db.Grid = function(selector, options) { /** * Grid HTML Element * @type {HTMLElement} */ var element, /** * Grid Layers * @type {Array} */ layers = [], /** * Grid Width * @type {Number} */ width = 300, /** * Grid Height * @type {Number} */ height = 300; /** * @construcs db.Grid */ (function () { element = document.querySelector(selector); }()); /** * Creates a new layer */ function addLayer() { var layer = new db.Layer('layer_' + layers.length, width, height); element.appendChild(layer.element); layers.push(layer); db.Tools.layer = layer.id; } /** * Removes a selected layer * @return {[type]} [description] */ function removeLayer() { } /** * Gets a selected layer * @param {String} id - The layer name * @return {db.Layer} */ function getLayer(id) { var layer, i = 0, numLayers = layers.length; while(numLayers-- > 0) { if (layers[numLayers].id === id) { layer = layers[numLayers]; break; } } return layer; } // public methods and properties return { element: element, addLayer: addLayer, getLayer: getLayer, width: width, height: height }; }; }(window.db = window.db || {})); (function (db) { 'use strict'; /** * @namespace Graphical User Interface */ db.gui = db.gui || {}; /** * Represents the Graphical User Interface * @constructor * @return {Object} Exposed methods */ db.gui.App = function() { /** * App layers * @type {db.gui.Layers} */ var layers; /** * @construcs db.gui.App */ (function () { layers = new db.gui.Layers('.db-layers'); }()); // public methods and properties return { layers: layers }; }; }(window.db = window.db || {})); /*globals TouchEvent:false */ (function (db) { 'use strict'; /** * @namespace Graphical User Interface */ db.gui = db.gui || {}; /** * Represents the Layer IDE * @constructor * @param {String} selector - The layers DOM selector * @return {Object} Exposed methods */ db.gui.Layers = function(selector) { /** * Layer HTML Element * @type {HTMLElement} */ var element, /** * Current layer * @type {HTMLElement} */ current, /** * Layers collection * @type {Array} */ items = [] ; /** * @construcs db.Layer */ (function () { element = document.querySelector(selector + ' ul'); current = document.querySelector('h3 strong'); current.innerHTML = db.Tools.layer; items = element.querySelectorAll('li'); }()); /** * Adds a new layer * @param {String} label - The layer label */ function add(label) { var hyperlink = document.createElement('a'), listItem = document.createElement('li'); hyperlink.href = '#' + label; hyperlink.innerHTML = label; listItem.appendChild(hyperlink); element.appendChild(listItem); update(); } /** * Updates DOM * @private */ function update() { items = element.querySelectorAll('li a'); var numItems = items.length; while (numItems-- > 0) { items[numItems].removeEventListener(TouchEvent.CLICK, item_clickHandler); items[numItems].addEventListener(TouchEvent.CLICK, item_clickHandler); } current.innerHTML = db.Tools.layer; } function item_clickHandler(e) { e.preventDefault(); db.Tools.layer = e.currentTarget.getAttribute('href').replace('#',''); current.innerHTML = db.Tools.layer; } // public methods and properties return { add: add }; }; }(window.db = window.db || {})); (function (db) { 'use strict'; /** * Represents a Grid Layer * @constructor * @param {Enum} options - Tile options * @return {Object} Exposed methods */ db.Layer = function(id, width, height) { /** * Layer Canvas Element * @type {HTMLCanvasElement} */ var canvas, /** * Canvas Context * @type {CanvasRenderingContext2D} */ context, /** * Tiles collection * @type {Array} */ tiles = [], /** * Current horizontal position * @type {Number} */ currentX = 0, /** * Current vertical position * @type {Number} */ currentY = 0; /** * @construcs db.Layer */ (function () { canvas = document.createElement('canvas'); canvas.id = id; canvas.width = width; canvas.height = height; context = canvas.getContext('2d'); }()); /** * Checks if the ID exists into the tiles collection * @param {String} id - The tile identifier * @return {Number} The tile index * * @private */ function tileExists(id) { var tile, i = 0, numItems = tiles.length; while(numItems-- > 0) { if (tiles[numItems] && tiles[numItems].id === id) { tile = numItems; break; } } return tile; } /** * Draws a tile into the selected position (if it's available) * @param {Number} x Horizontal position * @param {Number} y Vertical position */ function draw(x, y) { var exists = tileExists('tile_' + x + '_' + y); if (!isNaN(exists)) { return; } var tile = new db.Tile(context, { x: x, y: y, color: db.Tools.color }); tiles.push(tile); } /** * Draws a set of tiles * @param {Array} path - The path as a Multi-dimensional array */ function drawPath(path) { var rows = path.length, cols = path[0] ? path[0].length : 0, currentPos, i = 0, j = 0, numFrame; // loop into rows for ( ; i < rows; i++) { // loop into columns for (j = 0 ; j < cols; j++) { currentPos = path[i][j]; if (currentPos === 1) { // round num numFrame = (0.5 + Math.random()*15) << 0; draw(currentX + j, currentY + i); } } } currentX += cols; // start new row if (currentX + cols > 30) { currentY += rows; currentX = 0; } } /** * Erase a tile into the selected position * @param {Number} x Horizontal position * @param {Number} y Vertical position */ function erase(x, y) { var exists = tileExists('tile_' + x + '_' + y); if (typeof exists === 'undefined') { return; } // clear area tiles[exists].dispose(); // delete tile tiles.splice(exists, 1); } // public methods and properties return { id: id, element: canvas, context: context, draw: draw, erase: erase, drawPath: drawPath, tiles: tiles }; }; }(window.db = window.db || {})); (function (db) { 'use strict'; /** * Represents a Tile * @constructor * @param {CanvasRenderingContext2D} Context - The tile context (canvas) * @param {Enum} options - Tile options * @return {Object} Exposed methods */ db.Tile = function(context, options) { /** * Tile Identifier * @type {String} */ var id = 'tile', /** * Tile Width * @type {Number} */ width = 10, /** * Tile height * @type {Number} */ height = 10, /** * Horizontal position * @type {Number} */ x = 0, /** * Vertical position * @type {Number} */ y = 0, /** * Tile padding * @type {Number} */ padding = 1, /** * Background color * @type {String} */ color = options.color || '200,200,200', /** * Background alpha * @type {Float} */ opacity = 1.0 ; /** * @construcs db.Tile */ (function () { id = options.id || 'tile_' + options.x + '_' + options.y; x = (options.x * width) + (padding * options.x); y = (options.y * height) + (padding * options.y); context.fillStyle = 'rgba(' + color + ',' + opacity + ')'; context.fillRect(x,y,width,height); }()); /** * Clear tile */ function dispose() { context.clearRect(x,y,width,height); } // public methods and properties return { id: id, color: color, context: context, width: width, height: height, x: x, y: y, dispose: dispose }; }; }(window.db = window.db || {})); (function (db) { 'use strict'; /** * Represents the Toolbar Persistence Layer * @constructor * @return {Object} Exposed methods */ db.Tools = (function() { /** * Background color * @type {String} */ var color = '200,200,200', /** * Background alpha * @type {Float} */ opacity = 1.0, /** * Eraser enabled? * @type {Boolean} */ erase = false, /** * Current layer * @type {String} */ layer = 'layer_0' ; /** * @construcs db.Tools */ (function () { }()); // public methods and properties return { color: color, erase: erase, layer: layer }; }()); }(window.db = window.db || {})); function round(num) { return (0.5 + num) << 0; } /** * Mouse events mapper * @enum {Object.<String>} */ var TouchEvent = ('ontouchstart' in document.documentElement) ? // touch events { START: 'touchstart', MOVE: 'touchmove', CLICK: 'touchend', END: 'touchend' } : // desktop events { START: 'mousedown', MOVE: 'mousemove', CLICK: 'click', END: 'mouseup' }; // handle events invoking directly a method inside the DOM Element if (!Element.prototype.addEventListener) { Element.prototype.addEventListener = function(type, handler, useCapture) { if (this.attachEvent) { this.attachEvent('on' + type, handler); } return this; }; } Object.extend = function(destination, source) { for (var property in source) { destination[property] = source[property]; } return destination; };
// The MIT License (MIT) // Copyright (c) 2016 – 2019 David Hofmann <the.urban.drone@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE 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. import { typeOf } from '../core/typeof'; import { Type } from '../adt'; import { Show } from '../generics/Show'; import { Eq } from '../generics/Eq'; /* * @module monoid */ /** * The Fn monoid. Fn can be used to combine multiple functions * @class module:monoid.Fn * @extends module:generics/Show * @extends module:generics/Eq * @static * @version 3.0.0 * * @example * const {Fn} = require('futils').monoid; * * Fn((a) => a); // -> Fn(a -> a) * * Fn((a) => a).value; // -> (a -> a) * Fn((a) => a).run(1); // -> 1 */ export const Fn = Type('Fn', ['value']).deriving(Show, Eq); /** * Lifts a value into a Fn. Returns the empty Fn for values which are no * functions * @method of * @static * @memberof module:monoid.Fn * @param {any} a The value to lift * @return {Fn} A new Fn * * @example * const {Fn} = require('futils').monoid; * * Fn.of((a) => a * 2); // -> Fn(a -> a * 2) * Fn.of(null); // -> Fn(a -> a) * Fn.of({}); // -> Fn(a -> a) */ Fn.of = a => (typeof a === 'function' ? Fn(a) : Fn(x => x)); /** * Monoid implementation for Fn. Returns a Fn of the id function (a -> a) * @method empty * @static * @memberof module:monoid.Fn * @return {Fn} The empty Fn * * @example * const {Fn} = require('futils').monoid; * * Fn.empty(); // -> Fn(a -> a) */ Fn.empty = () => Fn(a => a); /** * Concatenates a Fn with another using function composition * @method concat * @memberof module:monoid.Fn * @instance * @param {Fn} a The Fn instance to concatenate with * @return {Fn} A new Fn * * @example * const {Fn} = require('futils').monoid; * * const fn = Fn((a) => a * 2); * * fn.concat(Fn((a) => a * 3)); // -> Fn(a -> a * 2 * 3) */ Fn.fn.concat = function(a) { if (Fn.is(a)) { return Fn(x => a.value(this.value(x))); } throw `Fn::concat cannot append ${typeOf(a)} to ${typeOf(this)}`; }; // Polyfill `.run()`, too. This often makes for better readability Fn.fn.run = function(a) { return this.value(a); };
import outputFileSync from 'vendor/fs-extra/outputFileSync'; export default function(path){ outputFileSync(path, ''); };
var net = require('net'); var fs = require("fs"); var child_process = require("child_process"); var local_port = 8893; //在本地创建一个server监听本地local_port端口 net.createServer(function (client) { //首先监听浏览器的数据发送事件,直到收到的数据包含完整的http请求头 var buffer = new Buffer(0); client.on('data',function(data) { buffer = buffer_add(buffer,data); if (buffer_find_body(buffer) == -1) return; var req = parse_request(buffer); if (req === false) return; client.removeAllListeners('data'); relay_connection(req); }); //从http请求头部取得请求信息后,继续监听浏览器发送数据,同时连接目标服务器,并把目标服务器的数据传给浏览器 function relay_connection(req) { console.log(req.method+' '+req.host+':'+req.port); //如果请求不是CONNECT方法(GET, POST),那么替换掉头部的一些东西 if (req.method != 'CONNECT') { //先从buffer中取出头部 var _body_pos = buffer_find_body(buffer); if (_body_pos < 0) _body_pos = buffer.length; var header = buffer.slice(0,_body_pos).toString('utf8'); //替换connection头 header = header.replace(/(proxy-)?connection\:.+\r\n/ig,'') .replace(/Keep-Alive\:.+\r\n/i,'') .replace("\r\n",'\r\nConnection: close\r\n'); header += "test:test\r\n"; //替换网址格式(去掉域名部分) if (req.httpVersion == '1.1') { var url = req.path.replace(/http\:\/\/[^\/]+/,''); if (req.path != url) header = header.replace(req.path,url); } buffer = buffer_add(new Buffer(header,'utf8'),buffer.slice(_body_pos)); } //建立到目标服务器的连接 var server = net.createConnection(req.port, req.host); //交换服务器与浏览器的数据 client.on("data", function(data){ server.write(data); }); server.on("data", function(data){ client.write(data); }); if (req.method == 'CONNECT') { client.write(new Buffer("HTTP/1.1 200 Connection established\r\nConnection: close\r\n\r\n")); } else { server.write(buffer); } } }).listen(local_port); console.log('Proxy server running at localhost:'+local_port); //处理各种错误 process.on('uncaughtException', function(err) { console.log("\nError!!!!"); console.log(err); }); /* 从请求头部取得请求详细信息 如果是 CONNECT 方法,那么会返回 { method,host,port,httpVersion} 如果是 GET/POST 方法,那么返回 { metod,host,port,path,httpVersion} */ function parse_request(buffer) { var s = buffer.toString('utf8'); var method = s.split('\n')[0].match(/^([A-Z]+)\s/)[1]; if (method == 'CONNECT') { var arr = s.match(/^([A-Z]+)\s([^\:\s]+)\:(\d+)\sHTTP\/(\d.\d)/); if (arr && arr[1] && arr[2] && arr[3] && arr[4]) return { method: arr[1], host:arr[2], port:arr[3],httpVersion:arr[4] }; } else { var arr = s.match(/^([A-Z]+)\s([^\s]+)\sHTTP\/(\d.\d)/); if (arr && arr[1] && arr[2] && arr[3]) { var host = s.match(/Host\:\s+([^\n\s\r]+)/)[1]; if (host) { var _p = host.split(':',2); return { method: arr[1], host:_p[0], port:_p[1]?_p[1]:80, path: arr[2],httpVersion:arr[3] }; } } } return false; } /* 两个buffer对象加起来 */ function buffer_add(buf1,buf2) { //var re = new Buffer(buf1.length + buf2.length); //buf1.copy(re); //buf2.copy(re,buf1.length); //return re; var bufArr = Array.prototype.slice.call(arguments); return Buffer.concat(bufArr); } /* 从缓存中找到头部结束标记("\r\n\r\n")的位置 */ function buffer_find_body(b) { //for(var i=0,len=b.length-3;i < len;i++) //{ // if (b[i] == 0x0d && b[i+1] == 0x0a && b[i+2] == 0x0d && b[i+3] == 0x0a) // { // return i+4; // } //} var index = b.toString().indexOf("\r\n\r\n"); if(index !== -1) { return index+4; } return -1; }
/* * Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com) * * openAUSIAS: The stunning micro-library that helps you to develop easily * AJAX web applications by using Java and jQuery * openAUSIAS is distributed under the MIT License (MIT) * Sources at https://github.com/rafaelaznar/ * * 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'; /* Controllers */ moduloTipoempleado.controller('TipoempleadoPListController', ['$scope', '$routeParams', 'serverService', '$location', function ($scope, $routeParams, serverService, $location) { $scope.visibles = {}; $scope.visibles.id = true; $scope.visibles.cargo = true; $scope.ob = "tipoempleado"; $scope.op = "plist"; $scope.title = "Listado de tipos de empleados"; $scope.icon = "fa-user-secret"; $scope.neighbourhood = 2; if (!$routeParams.page) { $routeParams.page = 1; } if (!$routeParams.rpp) { $routeParams.rpp = 10; } $scope.numpage = $routeParams.page; $scope.rpp = $routeParams.rpp;; $scope.order = ""; $scope.ordervalue = ""; $scope.filter = "id"; $scope.filteroperator = "like"; $scope.filtervalue = ""; $scope.systemfilter = ""; $scope.systemfilteroperator = ""; $scope.systemfiltervalue = ""; $scope.params = ""; $scope.paramsWithoutOrder = ""; $scope.paramsWithoutFilter = ""; $scope.paramsWithoutSystemFilter = ""; if ($routeParams.order && $routeParams.ordervalue) { $scope.order = $routeParams.order; $scope.ordervalue = $routeParams.ordervalue; $scope.orderParams = "&order=" + $routeParams.order + "&ordervalue=" + $routeParams.ordervalue; $scope.paramsWithoutFilter += $scope.orderParams; $scope.paramsWithoutSystemFilter += $scope.orderParams; } else { $scope.orderParams = ""; } if ($routeParams.filter && $routeParams.filteroperator && $routeParams.filtervalue) { $scope.filter = $routeParams.filter; $scope.filteroperator = $routeParams.filteroperator; $scope.filtervalue = $routeParams.filtervalue; $scope.filterParams = "&filter=" + $routeParams.filter + "&filteroperator=" + $routeParams.filteroperator + "&filtervalue=" + $routeParams.filtervalue; $scope.paramsWithoutOrder += $scope.filterParams; $scope.paramsWithoutSystemFilter += $scope.filterParams; } else { $scope.filterParams = ""; } if ($routeParams.systemfilter && $routeParams.systemfilteroperator && $routeParams.systemfiltervalue) { $scope.systemFilterParams = "&systemfilter=" + $routeParams.systemfilter + "&systemfilteroperator=" + $routeParams.systemfilteroperator + "&systemfiltervalue=" + $routeParams.systemfiltervalue; $scope.paramsWithoutOrder += $scope.systemFilterParams; $scope.paramsWithoutFilter += $scope.systemFilterParams; } else { $scope.systemFilterParams = ""; } $scope.params = ($scope.orderParams + $scope.filterParams + $scope.systemFilterParams); $scope.params = $scope.params.replace('&', '?'); serverService.getDataFromPromise(serverService.promise_getSome($scope.ob, $scope.rpp, $scope.numpage, $scope.filterParams, $scope.orderParams, $scope.systemFilterParams)).then(function (data) { if (data.status != 200) { $scope.status = "Error en la recepción de datos del servidor"; } else { $scope.pages = data.message.pages.message; if (parseInt($scope.numpage) > parseInt($scope.pages)) $scope.numpage = $scope.pages; $scope.page = data.message.page.message; $scope.registers = data.message.registers.message; $scope.status = ""; } }); $scope.getRangeArray = function (lowEnd, highEnd) { var rangeArray = []; for (var i = lowEnd; i <= highEnd; i++) { rangeArray.push(i); } return rangeArray; }; $scope.evaluateMin = function (lowEnd, highEnd) { return Math.min(lowEnd, highEnd); }; $scope.evaluateMax = function (lowEnd, highEnd) { return Math.max(lowEnd, highEnd); }; $scope.dofilter = function () { if ($scope.filter != "" && $scope.filteroperator != "" && $scope.filtervalue != "") { if ($routeParams.order && $routeParams.ordervalue) { if ($routeParams.systemfilter && $routeParams.systemfilteroperator) { $location.path($scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp).search('filter', $scope.filter).search('filteroperator', $scope.filteroperator).search('filtervalue', $scope.filtervalue).search('order', $routeParams.order).search('ordervalue', $routeParams.ordervalue).search('systemfilter', $routeParams.systemfilter).search('systemfilteroperator', $routeParams.systemfilteroperator).search('systemfiltervalue', $routeParams.systemfiltervalue); } else { $location.path($scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp).search('filter', $scope.filter).search('filteroperator', $scope.filteroperator).search('filtervalue', $scope.filtervalue).search('order', $routeParams.order).search('ordervalue', $routeParams.ordervalue); } } else { $location.path($scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp).search('filter', $scope.filter).search('filteroperator', $scope.filteroperator).search('filtervalue', $scope.filtervalue); } } return false; }; }]);
import React from 'react'; import { TrackStore } from '../stores'; import { SearchActions } from '../actions'; import Q from 'q'; import { LinkContainer } from 'react-router-bootstrap'; import { Grid, Input, Row, Col, Table, ProgressBar, Button, Glyphicon, Dropdown, MenuItem } from 'react-bootstrap'; import _ from 'lodash'; class SearchComponent extends React.Component { constructor(props) { super(props); this.state = { trackList: TrackStore.getState().tracks, okMessage: '' }; this.handleTracklistChange = this.handleTracklistChange.bind(this); } componentDidMount() { TrackStore.listen(this.handleTracklistChange); } componentWillUnmount() { TrackStore.unlisten(this.handleTracklistChange); } handleTracklistChange(state) { console.log('Search Component: handleTracklistChange', state); this.setState({trackList: state.tracks}); } render() { let body = ( <Row> <Col xs={12}> <Table> <tbody> {_.map(this.state.trackList, track => ( <LinkContainer to={`/tracks/${track.id}`} key={track.id}> <tr> <td> {track.name} </td> <td> {track.artists[ 0 ].name} </td> </tr> </LinkContainer> ) )} </tbody> </Table> </Col> </Row> ); return ( <div className='search-component'> <Row> <Col xs={12}> {body} </Col> </Row> </div> ); } } SearchComponent.defaultProps = {}; export default SearchComponent;
var LintRoller = require('../src/LintRoller'); var config = { verbose : false, stopOnFirstError : false, logFile : { name : './error.log', type : 'text' }, //recursively include JS files in these folders filepaths : [ './' ], //but ignore anything in these folders exclusions : [ './node_modules/', './assets/', './docs/' ], linters : [ { type : 'bom' }, { type : 'jsLint' } ] }; LintRoller.init(config);
/*var bmd, map, layer, marker, currentTile; var score, scoreTextValue, nBlackTextValue, textStyle_Key, textStyle_Value; var cursors; var player; var jumpButton, jumpTimer; var background, colorBackground, backgroundDelay, changeBackground, screenDelay; var index; var floors; var timer; var A,S,D,F; var obstacles; var velocityUp;*/ var laserRojoHGroup; var laserRojoVGroup; var laserRojoH; var laserRojoV; var laserDelay; var nLaserH; var White_World = { preload : function() { game.load.spritesheet('camaleonWalk', 'assets/images/Camaleon.png', 31, 27); game.load.image('floor', 'assets/images/spikess.png'); game.load.image('backgroundWhite', 'assets/images/backgroundWhite.png'); game.load.spritesheet('laserRojoHorizontal', 'assets/images/laser_horizontal.png',800,32); }, create : function() { game.physics.startSystem(Phaser.Physics.ARCADE); game.physics.arcade.gravity.y = 450; // Create our Timer timer = game.time.create(false); music_mundo2 = game.add.audio('music_mundo2', 1, true); music_mundo2.play(); sfx_laser = game.add.audio('sfx_laser2'); sfx_laser.addMarker('laser', 2.5, 2); background = game.add.tileSprite(0, 0, 800, 600, "backgroundWhite"); background.fixedToCamera = true; jumpTimer = 0; currentTile = 0; score = 0; laserDelay = 4; nLaserH = 3; //Paleta de colores map = game.add.tilemap(); bmd = game.add.bitmapData(32 * 2, 32 * 1); var color = Phaser.Color.createColor(64,64,64);//Black bmd.rect(0*32, 0, 32, 32, color.rgba); color = Phaser.Color.createColor(255,255,255); //White bmd.rect(1*32, 0, 64, 32, color.rgba); // Add a Tileset image to the map map.addTilesetImage('tiles', bmd); // Creates a new blank layer and sets the map dimensions. // In this case the map is 40x30 tiles in size and the tiles are 32x32 pixels in size. layer = map.create('level1', 2000, 30, 32, 32); //Intentar Corregir el 2000 // Populate some tiles for our player to start on with color Blue for (var i = 0; i < 20; i++){ i < 10 ? map.putTile(0, i, 10, layer) : map.putTile(0, i, 10, layer); } //Se setea Blanco con collider debido al background inicial Azul, y color Negro siempre tiene Collider; map.setCollision([0], true); // Create our tile selector at the top of the screen this.createTileSelector(); // Add Text to top of game. textStyle_Key = { font: "bold 14px sans-serif", fill: "#46c0f9", align: "center" }; textStyle_Value = { font: "bold 18px sans-serif", fill: "#46c0f9", align: "center" }; // Score. game.add.text(30, 40, "Distance", textStyle_Key).fixedToCamera = true; scoreTextValue = game.add.text(100, 38, score.toString(), textStyle_Value); scoreTextValue.fixedToCamera = true; // Letras con que se activa cada Tile game.add.text(12, 10, "A", textStyle_Key).fixedToCamera = true; game.add.text(44, 10, "S", textStyle_Key).fixedToCamera = true; this.createFloor(); this.laserRojoCreate(); // Crea Player this.createPlayer(); cursors = game.input.keyboard.createCursorKeys(); jumpButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); A = game.input.keyboard.addKey(Phaser.Keyboard.A); S = game.input.keyboard.addKey(Phaser.Keyboard.S); game.input.addMoveCallback(this.updateMarker, this); timer.start(); }, update : function() { game.world.setBounds(player.xChange, 0, game.width + player.xChange, game.world.height); game.physics.arcade.collide(player, layer); this.addScore(); this.playerMove(); if(timer.seconds > laserDelay){ if(laserRojoHGroup.exists){ laserRojoHGroup.forEach(function(laserRojoH) { laserRojoH.kill(); }); } this.laserRojoHorizontal(); } laserRojoHGroup.forEach(function(laserRojo) { if(laserRojo.frame == 14){ laserRojo.kill(); } }); game.physics.arcade.overlap(laserRojoHGroup, player, this.playerLaserCollision, null, this); game.physics.arcade.overlap(obstacles, player, this.playerCollision, null, this); game.physics.arcade.overlap(player, floors, this.gameOver, null, this); }, playerCollision : function(){ this.gameOver(); }, playerLaserCollision : function(pj, laser){ if(laser.frame == 10){ this.gameOver(); } }, addScore : function(){ score = Math.floor(player.x / 50) + GlobalScore; scoreTextValue.text = score.toString(); }, laserRojoCreate : function() { laserRojoHGroup = game.add.group(); laserRojoHGroup.enableBody = true; laserRojoHGroup.createMultiple(10, 'laserRojoHorizontal', 0, false); }, laserRojoHorizontal: function() { var posX = 0; var posY = Math.floor(player.y / 32); for(var i = 0; i < nLaserH; i++){ var laserRojoH = laserRojoHGroup.getFirstDead(true, posX, posY*32 + i*64); laserRojoH.body.immovable = true; laserRojoH.body.allowGravity = false; laserRojoH.fixedToCamera = true; laserRojoH.body.setSize(800,20,0,6); laserRojoH.animations.add('laserRojo', [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14], 8, false); laserRojoH.play('laserRojo'); sfx_laser.play('laser'); } for(var i = 0; i < (nLaserH - 1); i++){ var laserRojoH = laserRojoHGroup.getFirstDead(true, posX, posY*32 - (i+1)*64); laserRojoH.body.immovable = true; laserRojoH.body.allowGravity = false; laserRojoH.fixedToCamera = true; laserRojoH.body.setSize(800,20,0,6); laserRojoH.animations.add('laserRojo', [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14], 8, false); laserRojoH.play('laserRojo'); } laserDelay = timer.seconds + 4; }, createFloor : function(){ floors = game.add.group(); floors.enableBody = true; var floor = floors.create(0, game.world.height - 32, 'floor'); //floor.scale.x = game.world.width; //floor.scale.setTo(0.25, 0.25); floor.fixedToCamera = true; floor.body.immovable = true; floor.body.allowGravity = false; }, createPlayer : function() { player = game.add.sprite(96, game.world.centerY - 30, 'camaleonWalk'); player.xOrig = player.x; player.xChange = 0; //Asegurarse de setear al jugador al inicio del mapa game.world.setBounds(player.xChange, 0, game.width, game.world.height); game.physics.arcade.enable(player); player.body.collideWorldBounds = true; player.body.setSize(32,16,0,11); player.animations.add('camaleonWalkBlack', [24,25,26,27], 20, true); player.animations.add('camaleonJumpBlack', [28,29,30,31,32,33,34,35], 12, true); player.animations.add('camaleonWalkBlue', [12,13,14,15], 20, true); player.animations.add('camaleonJumpBlue', [16,17,18,19,20,21,22,23], 12, true); }, playerMove : function(){ player.body.velocity.x = 150 + velocityUp; if(player.body.onFloor()){ player.play('camaleonWalkBlack'); } else{ player.play('camaleonJumpBlack'); } //Si player está en el suelo su caja de colision es player.body.setSize(32,16,0,11); if(player.body.onFloor()){ player.body.setSize(32,16,0,11); } //Si player está en el aire su colsion es player.body.setSize(32,32,0,0) else{ player.body.setSize(21,16,6,9); } player.xChange = Math.max(Math.abs(player.x - player.xOrig), player.xChange); if(A.isDown){ currentTileMarker.x = 0; currentTileMarker.y = 0; currentTile = 0; } else if(S.isDown){ currentTileMarker.x = 32; currentTileMarker.y = 0; currentTile = 1; } if (jumpButton.isDown && player.body.onFloor() && game.time.now > jumpTimer) { player.body.velocity.y = -220; jumpTimer = game.time.now + 750; } }, pickTile: function(sprite, pointer) { var x = game.math.snapToFloor(pointer.x, 32, 0); var y = game.math.snapToFloor(pointer.y, 32, 0); currentTileMarker.x = x; currentTileMarker.y = y; x /= 32; y /= 32; currentTile = x + (y * 25); }, updateMarker : function() { marker.x = layer.getTileX(game.input.activePointer.worldX) * 32; marker.y = layer.getTileY(game.input.activePointer.worldY) * 32; if (game.input.mousePointer.isDown && marker.y > 32 && marker.y < (game.world.height - 32)) { //Acá utilizar sprite en vez de currenTile map.putTile(currentTile, layer.getTileX(marker.x), layer.getTileY(marker.y), layer); } }, createTileSelector : function() { // Our tile selection window var tileSelector = game.add.group(); var tileSelectorBackground = game.make.graphics(); tileSelectorBackground.beginFill(0x000000, 0.8); tileSelectorBackground.drawRect(0, 0, 64, 33); tileSelectorBackground.endFill(); tileSelector.add(tileSelectorBackground); var tileStrip = tileSelector.create(1, 1, bmd); tileStrip.inputEnabled = true; //tileStrip.events.onInputDown.add(this.pickTile, this); //Permite cambiar color haciando click en la paleta de colores // Our painting marker (El marcador negro) marker = game.add.graphics(); marker.lineStyle(2, 0x000000, 1); marker.drawRect(0, 0, 32, 32); // Our current tile marker currentTileMarker = game.add.graphics(); currentTileMarker.lineStyle(1, 0xffffff, 1); currentTileMarker.drawRect(0, 0, 32, 32); tileSelector.add(currentTileMarker); tileSelector.fixedToCamera = true; }, gameOver : function(){ //TGS.Analytics.logGameEvent('end'); sfx_colision.play('colision'); music_mundo2.stop(); game.world.setBounds(0, 0, game.width, game.height); GlobalScore = score; game.state.start('Game_Over'); }, render : function(){ laserRojoHGroup.forEach(function(laserRojo) { //game.debug.body(laserRojo); }); } }
import React from 'react'; import Icon from '../Icon'; export default class CloudQueueIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M38.71 20.07C37.35 13.19 31.28 8 24 8c-5.78 0-10.79 3.28-13.3 8.07C4.69 16.72 0 21.81 0 28c0 6.63 5.37 12 12 12h26c5.52 0 10-4.48 10-10 0-5.28-4.11-9.56-9.29-9.93zM38 36H12c-4.42 0-8-3.58-8-8s3.58-8 8-8h1.42c1.31-4.61 5.54-8 10.58-8 6.08 0 11 4.92 11 11v1h3c3.31 0 6 2.69 6 6s-2.69 6-6 6z"/></svg>;} };
var path = require("path"); var utils = require("utils-pkg"); /** * Parse options of the package * * @param {Object} opts Options given from the server * @return {Object} Options object merged with default */ module.exports.parseOptions = function(opts){ if(typeof opts == "undefined"){ throw new Error("Options is undefined"); } else if(!utils.isObject(opts)){ throw new Error("Options parameter must be an object"); } else{ // Path is mandatory for this package, throw error if undefined if(!opts.path){ throw new Error("Path for static files is undefined"); } // Set the errors for resolve option else if(typeof opts.hook != "undefined"){ var hook = opts.hook, events = ["request", "success", "fail", "cached"]; if(!utils.isObject(hook)){ throw new Error("Hook must be a map object"); } // Throw an error if any of the listed events is // not a valid passed value events.forEach(function(e){ if(utils.inKeyObject(hook, e) && !utils.isFunction(hook[e])){ throw new Error(`Hook ${e} must be a function`); } }); } // Throw error if cache is defined with invalid values // Valid values are string or function else if(typeof opts.cache != "undefined"){ if(!utils.isFunction(opts.cache) && !utils.isString(opts.cache)){ throw new Error("Cache value must be a string or function"); } } return { path: path.resolve(opts.path), index: opts.index !== undefined ? this.resolveIndex(opts.index) : "index", defaultExtension: opts.defaultExtension || "html", cache: opts.cache || "max-age=3600", scriptName: opts.scriptName !== undefined ? opts.scriptName : false, hook: opts.hook || null }; } } /** * Give or replace extension file with a directory * * @param {String} dir The normal directory * @param {String} ext The new directory with the given extension */ module.exports.setExtension = function(dir, ext){ if(ext){ if(path.extname(dir)){ return dir.replace(path.extname(dir), "." + ext); } return dir + "." + ext; } return dir; } /** * Resolve the index value defined in options * Either boolean or string value * * @param {String|Boolean} val The provided value for the index * @return {String|Null} Return the correct value for file handler */ module.exports.resolveIndex = function(val){ if(utils.isBoolean(val)){ if(val == true){ return "index" } else{ return null; } } else if(utils.isString(val)){ return val; } else{ throw new Error("Index value not valid"); } } /** * Compares 2 date times regardless of which format they are, * ignoring milliseconds * * @param {Date} time1 The date string/object to compare * @param {Date} time2 The date string/object to compare * @return {Boolean} Whether they have the same time */ module.exports.isEqualTime = function(time1, time2){ var time1 = new Date(time1) .getTime() .toString() .slice(0, -3); var time2 = new Date(time2) .getTime() .toString() .slice(0, -3); return time1 == time2; }
(function () { 'use strict'; angular.module('OpenSlidesApp.users', []) .factory('operator', [ 'User', 'Group', 'loadGlobalData', 'autoupdate', 'DS', function (User, Group, loadGlobalData, autoupdate, DS) { var operatorChangeCallbacks = [autoupdate.reconnect]; var operator = { user: null, perms: [], isAuthenticated: function () { return !!this.user; }, onOperatorChange: function (func) { operatorChangeCallbacks.push(func); }, setUser: function(user_id) { if (user_id) { User.find(user_id).then(function(user) { operator.user = user; // TODO: load only the needed groups Group.findAll().then(function() { operator.perms = user.getPerms(); _.forEach(operatorChangeCallbacks, function (callback) { callback(); }); }); }); } else { operator.user = null; operator.perms = []; DS.clear(); _.forEach(operatorChangeCallbacks, function (callback) { callback(); }); Group.find(1).then(function(group) { operator.perms = group.permissions; _.forEach(operatorChangeCallbacks, function (callback) { callback(); }); }); } }, // Returns true if the operator has at least one perm of the perms-list. hasPerms: function(perms) { if (typeof perms == 'string') { perms = perms.split(' '); } return _.intersection(perms, operator.perms).length > 0; }, }; return operator; } ]) .factory('User', [ 'DS', 'Group', 'jsDataModel', function(DS, Group, jsDataModel) { var name = 'users/user'; return DS.defineResource({ name: name, useClass: jsDataModel, computed: { full_name: function () { return this.get_full_name(); }, short_name: function () { return this.get_short_name(); }, }, methods: { getResourceName: function () { return name; }, get_short_name: function() { // should be the same as in the python user model. var title = _.trim(this.title), firstName = _.trim(this.first_name), lastName = _.trim(this.last_name), name = ''; if (title) { name = title + ' '; } if (firstName && lastName) { name += [firstName, lastName].join(' '); } else { name += firstName || lastName || this.username; } return name; }, get_full_name: function() { // should be the same as in the python user model. var title = _.trim(this.title), firstName = _.trim(this.first_name), lastName = _.trim(this.last_name), structure_level = _.trim(this.structure_level), name = ''; if (title) { name = title + ' '; } if (firstName && lastName) { name += [firstName, lastName].join(' '); } else { name += firstName || lastName || this.username; } if (structure_level) { name += " (" + structure_level + ")"; } return name; }, getPerms: function() { var allPerms = []; var allGroups = []; if (this.groups_id) { allGroups = this.groups_id.slice(0); } // Add registered group allGroups.push(2); _.forEach(allGroups, function(groupId) { var group = Group.get(groupId); if (group) { _.forEach(group.permissions, function(perm) { allPerms.push(perm); }); } }); return _.uniq(allPerms); }, // link name which is shown in search result getSearchResultName: function () { return this.get_full_name(); }, // subtitle of search result getSearchResultSubtitle: function () { return "Participant"; }, }, relations: { hasMany: { 'users/group': { localField: 'groups', localKey: 'groups_id', } } } }); } ]) .factory('Group', [ '$http', 'DS', function($http, DS) { var permissions; return DS.defineResource({ name: 'users/group', permissions: permissions, getPermissions: function() { if (!this.permissions) { this.permissions = $http({ 'method': 'OPTIONS', 'url': '/rest/users/group/' }) .then(function(result) { return result.data.actions.POST.permissions.choices; }); } return this.permissions; } }); } ]) .run([ 'User', 'Group', function(User, Group) {} ]) // Mark strings for translation in JavaScript. .config([ 'gettext', function (gettext) { // default group names (from users/signals.py) gettext('Guests'); gettext('Registered users'); gettext('Delegates'); gettext('Staff'); } ]); }());
import React from 'react'; import { shallow, mount } from 'enzyme'; import Search from '../lib/Components/Search'; describe('Search', () => { let wrapper; let mockFn; beforeEach(() => { mockFn = jest.fn(); wrapper = shallow(<Search getApi={mockFn} />); }); it('should exist', () => { expect(wrapper).toBeDefined(); }); it('should render an input field with className city-search', () => { expect(wrapper.find('.city-search')).toBeDefined(); expect(wrapper.find('.city-search').text('')); }); it('should render a submit button with className sub-btn', () => { expect(wrapper.find('.sub-btn')).toBeDefined(); }); it('should call getVal when button is clicked', () => { mockFn = jest.fn(); const submitButton = wrapper.find('.sub-btn'); wrapper.instance().getVal = mockFn; submitButton.simulate('click'); expect(mockFn).toHaveBeenCalled; }); it.skip('should change set location in state on button click', () => { const inputBox = wrapper.find('.city-search'); const submitButton = wrapper.find('.sub-btn'); inputBox.simulate('keydown', { which: 'a' }); submitButton.simulate('click'); expect(wrapper.find('.city-search')).toBeDefined(); expect(wrapper.instance().state.location).toEqual('a'); }); it('should create a new instance of Trie on mount', () => { wrapper.instance().componentDidMount(); expect(wrapper.instance().trie).toEqual(expect.objectContaining({ root: expect.objectContaining({ letter: null, isWord: false, children: expect.objectContaining({}), }), })); }); });
var io = require('socket.io'); var client = require('webrtc.io-client'); var rtc = {}; rtc._events = {}; var rooms = {}; module.exports.listen = function() { // delegate all arguments to socket.io.listen var manager = io.listen.apply(io, arguments); attachRoutes(manager); attachEvents(manager); return manager; }; rtc.on = function(eventName, callback) { rtc._events[eventName] = rtc._events[eventName] || []; rtc._events[eventName].push(callback); }; rtc.fire = function(eventName, _) { var events = rtc._events[eventName]; var args = Array.prototype.slice.call(arguments, 1); if (!events) { return; } for (var i = 0, len = events.length; i < len; i++) { events[i].apply(null, args); } }; function attachRoutes(manager) { var server = manager.server; var oldHandlers = server.listeners('request').splice(0); server.on('request', function(req, res) { if (req.url !== '/webrtc.io/webrtc.io.js') { // re-run old handlers for (var i = 0, len = oldHandlers.length; i < len; i++) { var handler = oldHandlers[i]; handler.call(server, req, res); console.log(server); } return; } client.builder(function(err, content) { if (err) { console.error(err); return; } res.writeHead(200, { 'Content-Type': 'text/javascript' }); res.end(req.method !== 'HEAD' && content ? content : ''); }); }); } function attachEvents(manager) { manager.sockets.on('connection', function(socket) { // TODO: let you join multiple rooms socket.on('join room', function(room) { // initialize room as an empty array var connections = rooms[room] = rooms[room] || []; socket.join(room); // tell everyone else in the room about the new peer socket.broadcast.to(room) .emit('new peer connected', { socketId: socket.id }); connections.push(socket); // pass array of connection ids except for peer's to peer var connectionsId = []; for (var i = 0, len = connections.length; i < len; i++) { var id = connections[i].id; if (id !== socket.id) { connectionsId.push(id); } } socket.emit('get peers', { connections: connectionsId }); // remove connection from array and tell everyone else about the // disconnect socket.on('disconnect', function() { var connections = rooms[room]; for (var i = 0; i < connections.length; i++) { var id = connections[i].id; if (id == socket.id) { connections.splice(i, 1); i--; socket.leave(room); socket.broadcast.to(room).emit('remove peer connected', { socketId: socket.id }); } } rtc.fire('disconnect'); }); socket.on('receive ice candidate', function(data) { var soc = getSocket(room, data.socketId); if (soc) { soc.emit('receive ice candidate', { label: data.label, candidate: data.candidate, socketId: socket.id }); } }); socket.on('send offer', function(data) { var soc = getSocket(room, data.socketId); if (soc) { soc.emit('receive offer', { sdp: data.sdp, socketId: socket.id }); } }); socket.on('send offer', function(data) { var soc = getSocket(room, data.socketId); if (soc) { soc.emit('receive offer', { sdp: data.sdp, socketId: socket.id }); } }); socket.on('send answer', function(data) { var soc = getSocket(room, data.socketId); if (soc) { soc.emit('receive answer', { sdp: data.sdp, socketId: socket.id }); } rtc.fire('send_answer'); }); }); rtc.fire('connection', rtc); }); manager.rtc = rtc; return manager; } function getSocket(room, id) { var connections = rooms[room]; if (!connections) { // TODO: Or error, or customize return; } for (var i = 0; i < connections.length; i++) { var socket = connections[i]; if (id === socket.id) { return socket; } } }
'use strict' var BaseModel = require('capital-models').BaseModel; module.exports = class Buyer extends BaseModel { constructor(source) { super('buyer', '1.0.0'); // Define properties. this.code = ''; this.name = ''; this.address = ''; this.country = ''; this.contact = ''; this.tempo = ''; this.copy(source); } }
function initMap() { var latLng = new google.maps.LatLng(40.791885, -73.952581); var styles = [ { stylers: [ { hue: "#541388" }, { saturation: 0 } ] },{ featureType: "road", elementType: "geometry", stylers: [ { lightness: 100 }, { visibility: "simplified" } ] },{ featureType: "road.local", elementType: "labels", stylers: [ { visibility: "off" } ] } ]; // Create a new StyledMapType object, passing it the array of styles, // as well as the name to be displayed on the map type control. var styledMap = new google.maps.StyledMapType(styles, {name: "Styled Map"}); var mapOptions = { zoom: 15, center: latLng, mapTypeId: google.maps.MapTypeId.ROADMAP, panControl: true, zoomControl: true, mapTypeControl: true, scaleControl: true, streetViewControl: false, overviewMapControl: false, disableDoubleClickZoom: false, scrollwheel: false, draggable: false, mapTypeControlOptions: { mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style'] } }; var map = new google.maps.Map(document.getElementById('map'), mapOptions); map.mapTypes.set('map_style', styledMap); map.setMapTypeId('map_style'); function addHotelMarker(title, latLng, url, map) { var marker = new google.maps.Marker({ position: latLng, map: map, title: title, icon: '/img/map/hotel.png', animation: google.maps.Animation.DROP }); // Add Click Event google.maps.event.addListener(marker, 'click', function() { window.location = url; }); } var eventMarker = new google.maps.Marker({ position: latLng, map: map, title: "The New York Academy of Medicine", icon: '/img/map/star.png', animation: google.maps.Animation.DROP }); // Add Click Event for location google.maps.event.addListener(eventMarker, 'click', function() { window.location = 'https://nyam.org/'; }); // // Add Hotels // addHotelMarker( // "Hyatt House", // new google.maps.LatLng(32.956958, -96.828211), // "http://addison.house.hyatt.com/en/hotel/home.html", // map // ); // addHotelMarker( // "Radisson Hotel Dallas North", // new google.maps.LatLng(32.958204, -96.826842), // "http://hotels.radisson.com/tx/addison/hotels_addison_tx_usadntx.html", // map // ); // addHotelMarker( // "Spring Hill Suites", // new google.maps.LatLng(32.956949, -96.827179), // "http://www.marriott.com/hotels/travel/dalsh-springhill-suites-dallas-addison-quorum-drive/", // map // ); }
'use strict'; angular.module('myApp.view1', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/view1', { templateUrl: 'view1/view1.html', controller: 'View1Ctrl' }); }]) .controller('View1Ctrl', [function() { $("#add-story-cta").click(function () { var $storyName = $('#story-name').val(); var $storyUrl = $('#story-url').val(); var $storyDescription = $(' #story-description').val(); $("#story-table").append( "<tr>"+ "<td>" + $storyName + "</td>"+ "<td>" + $storyUrl + "</td>"+ "<td>" + $storyDescription + "</td>"+ "<td>" + '<button class="btn btn-edit fa fa-edit edit-row"></button>' + '<button class="btn btn-red fa fa-trash delete-row"></button>' + "</td>" + "</tr>" ); }); $("#add-podcast-cta").click(function () { var $podcastName = $('#podcast-name').val(); var $podcastUrl = $('#podcast-url').val(); var $podcastDescription = $('#podcast-description').val(); $("#podcast-table").append( "<tr>"+ "<td>" + $podcastName + "</td>"+ "<td>" + $podcastUrl + "</td>"+ "<td>" + $podcastDescription + "</td>"+ "<td>" + '<button class="btn btn-edit fa fa-edit edit-row"></button>' + '<button class="btn btn-red fa fa-trash delete-row"></button>' + "</td>" + "</tr>" ); }); $("#add-website-cta").click(function () { var $websiteName = $('#website-name').val(); var $websiteUrl = $('#website-url').val(); var $websiteDescription = $('#website-description').val(); $("#website-table").append( "<tr>"+ "<td>" + $websiteName + "</td>"+ "<td>" + $websiteUrl + "</td>"+ "<td>" + $websiteDescription + "</td>"+ "<td>" + '<button class="btn btn-edit fa fa-edit edit-row"></button>' + '<button class="btn btn-red fa fa-trash delete-row"></button>' + "</td>" + "</tr>" ); }); //delete row $(document).on('click', '.delete-row', function () { $(this).closest('tr').remove(); return false; }); //edit row $(document).on('click', '.edit-row', function () { //on edit click grab values //paste them into input fields //show save button //on save click rewrite the table cells $(this).closest('tr').addClass('edit-row'); $('.edit-row td').each(function(i){ $(this).html(); console.log($(this).html()); $(this).append( "<input type='text' class='edit-val'>" ); }); }); $('body').scrollspy({ target: '#gloo-nav' }); }]);
"use strict"; var IP = 'helios.rest.api'; describe("ProviderService of profileApp.services module", function() { var mockProviderService, httpBackend; beforeEach(module("profileApp.services")); beforeEach(inject(function(_ProviderService_, $httpBackend) { mockProviderService = _ProviderService_; httpBackend = $httpBackend; })); it("should get all providers mathcing the search crieteria", function() { httpBackend.whenGET("http://" + IP + ":3000/api/providersearch/11") .respond({ name : 'starsports', provider_id : '111', email : 'info@star.in', profile_count : '2' }, { name : 'MTV', provider_id : '1111', email : 'support@mtv.com', profile_count : '1' }); mockProviderService.getProviders("11").then(function(providers) { expect(providers).toEqual({ name : 'starsports', provider_id : '111', email : 'info@star.in', profile_count : '2' }, { name : 'MTV', provider_id : '1111', email : 'support@mtv.com', profile_count : '1' }); }); httpBackend.flush(); }); it("should get specific provider when Provider id used for search", function() { httpBackend.whenGET("http://" + IP + ":3000/api/providers/333") .respond({ name : 'starsports1', provider_id : '333', email : 'info@star.in', profile_count : '2' }); mockProviderService.getProvider("333").then(function(provider) { expect(provider).toEqual({ name : 'starsports1', provider_id : '333', email : 'info@star.in', profile_count : '2' }); }); httpBackend.flush(); }); }); describe( "ProfileService of profileApp.services module", function() { var mockProviderService, httpBackend; beforeEach(module("profileApp.services")); beforeEach(inject(function(_ProfileService_, $httpBackend) { mockProviderService = _ProfileService_; httpBackend = $httpBackend; })); it( "should get all profiles for specific provider id", function() { httpBackend .whenGET( "http://" + IP + ":3000/api/providers/111/profiles") .respond( [ { "profile_id" : "77472075-2d06-11e4-a599-1078d24a5935", "name" : "4-Stream", "type" : "video", "private" : 0, "deinterlace_input" : 1, "frame_rate" : 30, "mezzanine_multipass_encoding" : 1, "streams" : [] }, { "profile_id" : "774724fb-2d06-11e4-a599-1078d24a5935", "name" : "generic", "type" : "video", "private" : 1, "deinterlace_input" : 1, "frame_rate" : 25, "mezzanine_multipass_encoding" : 1, "streams" : [ { "id" : 2, "stream_id" : "ad7bff02-2e79-11e4-9c3a-1078d24a5935", "name" : "HTTP Live Streaming audio + video", "muxing_format" : "ts", "profile" : "baseline", "audio_sample_rate" : 44100, "audio_bitrate" : 64, "video_bitrate" : 300, "video_width" : 640, "keyframe_interval_sec" : 5, "watermark" : null, "multipass_encoding" : 1, "segment_length_sec" : 5, "encrypt" : 1, "key_rotation_period" : 6, "video_encryption_level" : null, "stream_type" : "single", "encode_width" : 576, "h266_profile" : "iphone" } ] } ]); mockProviderService .getProfiles("111") .then( function(providers) { expect(providers) .toEqual( [ { "profile_id" : "77472075-2d06-11e4-a599-1078d24a5935", "name" : "4-Stream", "type" : "video", "private" : 0, "deinterlace_input" : 1, "frame_rate" : 30, "mezzanine_multipass_encoding" : 1, "streams" : [] }, { "profile_id" : "774724fb-2d06-11e4-a599-1078d24a5935", "name" : "generic", "type" : "video", "private" : 1, "deinterlace_input" : 1, "frame_rate" : 25, "mezzanine_multipass_encoding" : 1, "streams" : [ { "id" : 2, "stream_id" : "ad7bff02-2e79-11e4-9c3a-1078d24a5935", "name" : "HTTP Live Streaming audio + video", "muxing_format" : "ts", "profile" : "baseline", "audio_sample_rate" : 44100, "audio_bitrate" : 64, "video_bitrate" : 300, "video_width" : 640, "keyframe_interval_sec" : 5, "watermark" : null, "multipass_encoding" : 1, "segment_length_sec" : 5, "encrypt" : 1, "key_rotation_period" : 6, "video_encryption_level" : null, "stream_type" : "single", "encode_width" : 576, "h266_profile" : "iphone" } ] } ]); }); httpBackend.flush(); }); it( "should get the details for a specific Profile id", function() { httpBackend .whenGET( "http://" + IP + ":3000/api/profile/77472075-2d06-11e4-a599-1078d24a5935") .respond( { "profile_id" : "77472075-2d06-11e4-a599-1078d24a5935", "name" : "4-Stream", "type" : "video", "private" : 0, "deinterlace_input" : 1, "frame_rate" : 30, "mezzanine_multipass_encoding" : 1, "streams" : [] }); mockProviderService .getProfile( "77472075-2d06-11e4-a599-1078d24a5935") .then( function(providers) { expect(providers) .toEqual( { "profile_id" : "77472075-2d06-11e4-a599-1078d24a5935", "name" : "4-Stream", "type" : "video", "private" : 0, "deinterlace_input" : 1, "frame_rate" : 30, "mezzanine_multipass_encoding" : 1, "streams" : [] }); }); httpBackend.flush(); }); });
'use strict'; const assert = require('assert'); const Bluebird = require('bluebird'); const Crypto = require('crypto'); const getAWSConfig = require('../aws_config'); const Ironium = require('../..'); const ms = require('ms'); const setup = require('../helpers'); (getAWSConfig.isAvailable ? describe : describe.skip)('Publish - AWS', function() { // We test that publish works by consuming from this queue // (which must be subscribed to the topic). let snsSubscribedQueue; const processedJobs = []; const randomValue = Crypto.randomBytes(32).toString('hex'); function processJob(notification) { const job = JSON.parse(notification.Message); processedJobs.push(job); return Promise.resolve(); } before(setup); before(function() { snsSubscribedQueue = Ironium.queue('sns-foo-notification'); }); before(function() { Ironium.configure(getAWSConfig()); process.env.NODE_ENV = 'production'; }); before(function() { snsSubscribedQueue.eachJob(processJob); }); before(function() { return Ironium.publish('foo-notification', { value: randomValue }); }); before(function() { Ironium.start(); }); before(function() { return Bluebird.delay(ms('3s')); }); it('should have published to SNS and processed the job in SQS', function() { const processedJob = processedJobs.find(job => job.value === randomValue); assert(processedJob); }); after(function() { process.env.NODE_ENV = 'test'; Ironium.stop(); Ironium.configure({}); }); });
!function(p,A){function r(b){return A.isComplexArray(b)&&b||new t(b)}function y(b,z){var f=b.length;if(f&f-1){var f=b.length,a,c,k,e,d,h,u,n,g,m,l,q,v;if(1!==f){k=new t(f,b.ArrayType);b:{a=3;for(c=B(f);a<=c;){if(0===f%a){n=a;break b}a+=2}n=f}g=f/n;m=1/B(n);l=new t(g,b.ArrayType);for(c=0;c<n;c++){for(a=0;a<g;a++)l.real[a]=b.real[a*n+c],l.imag[a]=b.imag[a*n+c];1<g&&(l=y(l,z));h=C(2*w*c/f);u=(z?-1:1)*D(2*w*c/f);e=1;for(a=d=0;a<f;a++)q=l.real[a%g],v=l.imag[a%g],k.real[a]+=e*q-d*v,k.imag[a]+=e*v+d*q,q= e*h-d*u,d=e*u+d*h,e=q}for(a=0;a<f;a++)b.real[a]=m*k.real[a],b.imag[a]=m*k.imag[a]}return b}var f=b.length,p,r;k=b.length;a={};for(c=0;c<k;c++){e=c;d=k;for(h=0;1<d;)h<<=1,h+=e&1,e>>=1,d>>=1;d=h;a.hasOwnProperty(c)||a.hasOwnProperty(d)||(e=b.real[d],b.real[d]=b.real[c],b.real[c]=e,e=b.imag[d],b.imag[d]=b.imag[c],b.imag[c]=e,a[c]=a[d]=!0)}c=b.real;e=b.imag;for(g=1;g<f;){u=C(w/g);n=(z?-1:1)*D(w/g);for(k=0;k<f/(2*g);k++)for(d=1,a=h=0;a<g;a++)m=2*k*g+a,l=m+g,q=c[m],v=e[m],p=d*c[l]-h*e[l],r=h*c[l]+d*e[l], c[m]=x*(q+p),e[m]=x*(v+r),c[l]=x*(q-p),e[l]=x*(v-r),m=d*u-h*n,h=d*n+h*u,d=m;g<<=1}return b}var t=A.ComplexArray,w=Math.PI,x=Math.SQRT1_2,B=Math.sqrt,C=Math.cos,D=Math.sin;t.prototype.FFT=function(){return y(this,!1)};p.FFT=function(b){return r(b).FFT()};t.prototype.InvFFT=function(){return y(this,!0)};p.InvFFT=function(b){return r(b).InvFFT()};t.prototype.frequencyMap=function(b){return this.FFT().map(b).InvFFT()};p.frequencyMap=function(b,p){return r(b).frequencyMap(p)}}("undefined"===typeof exports&& (this.fft={})||exports,"undefined"===typeof require&&this.complex_array||require("./complex_array"));
/** * autonumeric_ujs.js * @author: randoum * @version: 2.0 - 2017-01-07 * * Created by Randoum on 2013-08-15. Please report any bugs to https://github.com/randoum/autonumeric-rails * * Wrap-up autoNumeric.js library to be used with Rails in a UJS flavor * All credits for autoNumeric library goes to its original creators * Whom can be reached at https://github.com/BobKnothe/autoNumeric * * The MIT License (http://www.opensource.org/licenses/mit-license.php) * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ var AutonumericRails; window.AutonumericRails = AutonumericRails = (function() { AutonumericRails.create_autonumeric_object = function(obj) { if (!obj.data('autonumeric-initialized')) { return new this(obj); } }; AutonumericRails.delete_autonumeric_object = function(obj) { if (obj.data('autonumeric-initialized')) { obj.removeData('autonumeric-initialized').removeData('autonumeric').removeAttr('data-autonumeric').off('keyup blur').autoNumeric('destroy'); $('input#' + obj.attr('id') + '_val[type="hidden"][name="' + obj.attr('name') + '"]').remove(); } }; function AutonumericRails(field) { this.field = field; this.field.data('autonumeric-initialized', true); this.create_hidden_field(); this.init_autonumeric(); this.sanitize_value(); this.field.on('keyup blur', $.proxy(function() { this.sanitize_value(); }, this)); } AutonumericRails.prototype.create_hidden_field = function() { this.hidden = $('<input>').attr('type', 'hidden').attr('id', this.field.attr('id') + '_val').attr('name', this.field.attr('name')); this.hidden.insertAfter(this.field); }; AutonumericRails.prototype.init_autonumeric = function() { this.field.autoNumeric('init', $.parseJSON(this.field.attr('data-autonumeric'))); }; AutonumericRails.prototype.sanitize_value = function() { this.hidden.val(this.field.autoNumeric('getSettings').rawValue); }; return AutonumericRails; })(); window.refresh_autonumeric = function() { $('input[data-autonumeric]').each(function() { AutonumericRails.create_autonumeric_object($(this)); }); }; jQuery(function() { window.refresh_autonumeric(); $(document).on('refresh_autonumeric', function() { window.refresh_autonumeric(); }); $(document).on('ajaxComplete', function() { window.refresh_autonumeric(); }); });
//>>excludeStart("exclude", pragmas.exclude); define(['validatrix', 'validators/regex'], function(){ //>>excludeEnd("exclude"); validatrix.validators.email = function(element, options) { var errorMessage = element.getAttribute('data-val-email'); return validatrix.validators.regex(element, options, '\\w+([-+.\']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*', errorMessage); }; //>>excludeStart("exclude", pragmas.exclude); }); //>>excludeEnd("exclude");
"use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var requireIndex = require("requireindex"); //------------------------------------------------------------------------------ // Plugin Definition //------------------------------------------------------------------------------ // import all rules in lib/rules module.exports.rules = requireIndex(__dirname + "/rules");
import app from '~/app'; import _ from 'lodash'; var _exports = { escape : solrEscape, andOr : andOr, lstring : lstring }; app.factory('solr', [function() { return _exports; }]) export default _exports; function solrEscape(value) { if(value===undefined) throw "Value is undefined"; if(value===null) throw "Value is null"; if(value==="") throw "Value is null"; if(_.isNumber(value)) value = value.toString(); if(_.isDate (value)) value = value.toISOString(); //TODO add more types value = value.toString(); value = value.replace(/\\/g, '\\\\'); value = value.replace(/\+/g, '\\+'); value = value.replace(/\-/g, '\\-'); value = value.replace(/\&\&/g, '\\&&'); value = value.replace(/\|\|/g, '\\||'); value = value.replace(/\!/g, '\\!'); value = value.replace(/\(/g, '\\('); value = value.replace(/\)/g, '\\)'); value = value.replace(/\{/g, '\\{'); value = value.replace(/\}/g, '\\}'); value = value.replace(/\[/g, '\\['); value = value.replace(/\]/g, '\\]'); value = value.replace(/\^/g, '\\^'); value = value.replace(/\"/g, '\\"'); value = value.replace(/\~/g, '\\~'); value = value.replace(/\*/g, '\\*'); value = value.replace(/\?/g, '\\?'); value = value.replace(/\:/g, '\\:'); return value; } function andOr(query, sep) { sep = sep || 'AND'; if(_.isArray(query)) { query = _.map(query, function(criteria){ if(_.isArray(criteria)) { return andOr(criteria, sep=="AND" ? "OR" : "AND"); } return criteria; }); query = '(' + query.join(' ' + sep + ' ') + ')'; } return query; } function lstring(value) { var fields = _.drop(arguments, 1); return _.reduce(['en', 'es', 'fr', 'ru', 'zh', 'ar'], function(text, locale){ text[locale] = _.reduce(fields, function(v, f) { return v || value[f.replace('*', locale.toUpperCase())] || ""; }, ""); if(!text[locale]) delete text[locale]; return text; }, {}); }
import React from 'react'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './WhiteButton.css'; class WhiteButton extends React.Component { render() { const { children } = this.props; return <button className={s.btnWhite}>{children}</button>; } } export default withStyles(s)(WhiteButton);
/* eslint-disable ember/require-computed-property-dependencies */ /* globals FastBoot */ import Service from '@ember/service'; import { computed } from '@ember/object'; let isString = function(value) { return typeof value === 'string'; }; let lowercase = function(string) { return isString(string) ? string.toLowerCase() : string; }; let toInt = function(str) { return parseInt(str, 10); }; export default Service.extend({ vendorPrefix: '', transitions: false, animations: false, _document: null, _window: null, android: computed('', function() { return toInt((/android (\d+)/.exec(lowercase((this._window.navigator || {}).userAgent)) || [])[1]); }), init() { this._super(...arguments); if (typeof FastBoot !== 'undefined') { return; } let _document = document; let _window = window; this.setProperties({ _document, _window }); let bodyStyle = _document.body && _document.body.style; let vendorPrefix, match; let vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/; let transitions = false; let animations = false; if (bodyStyle) { for (let prop in bodyStyle) { match = vendorRegex.exec(prop); if (match) { vendorPrefix = match[0]; vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1); break; } } if (!vendorPrefix) { vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit'; } transitions = !!(('transition' in bodyStyle) || (`${vendorPrefix}Transition` in bodyStyle)); animations = !!(('animation' in bodyStyle) || (`${vendorPrefix}Animation` in bodyStyle)); if (this.android && (!transitions || !animations)) { transitions = isString(bodyStyle.webkitTransition); animations = isString(bodyStyle.webkitAnimation); } } this.set('transitions', transitions); this.set('animations', animations); this.set('vendorPrefix', vendorPrefix); } });
import React, { Component } from 'react'; import PropTypes from 'prop-types'; class SummaryList extends Component { static propTypes = { items: PropTypes.arrayOf(PropTypes.shape({ })), } static defaultProps = { items: [ { text: 'ราคาสินค้า', color: 'blue', amount: '40', }, { text: 'ส่วนลด', color: 'purple', amount: '10', }, ], } render() { const { items } = this.props; return ( <div className="summary-list"> { items.map((item, index) => { return ( <div className="item" key={`summary-list-item-${index}`}> <p>{item.text}</p> <div className={`circle ${item.color}`}> <span className="pt">{item.amount}</span> <span className="currency"> ฿</span> </div> </div> ); }) } </div> ); } } export default SummaryList;
'use strict'; var React = require('react'); var ReactDOM = require('react-dom'); var commons = require('./commons'); module.exports = function() { ReactDOM.render( <commons.PageHeader>Science <small>Visualization</small></commons.PageHeader>, document.getElementById('heading') ); ReactDOM.render( <div> </div>, document.getElementById('container') ); };
function GetShaderCode(id) { var shaderScript = document.getElementById(id); if(!shaderScript) return null; var str = ""; var k = shaderScript.firstChild; while(k) { if(k.nodeType==3) str += k.textContent; k = k.nextSibling; } return str; } Demo = { minSizeOrderLoc : -1, maxSizeOrderLoc : -1, timeLoc : -1, rateLoc : -1, lifeTimeLoc : -1, viewportLoc : -1, startIndexLoc: -1, canvas : null, progId : 0, bufId : 0, paused : false, speed : 0.5, time : 0, absTime : 0, lifeTime : 5, rate : 10000, gl : null, projMatrix : Matrix.I(4), worldViewMatrix : Matrix.I(4), upPressed : false, downPressed : false, OnWindowResize : function() { Demo.canvas.width = window.innerWidth - 20; Demo.canvas.height = window.innerHeight - 20; this.gl.viewport(0, 0, this.canvas.width, this.canvas.height); this.gl.clearColor(0.0, 0.0, 0.0, 1.0); SetMatrixUniform(this.gl, this.progId, "ProjMatrix", this.projMatrix); this.gl.uniform2f(this.viewportLoc, this.canvas.width, this.canvas.height); }, Init : function() { this.canvas = canvas; if(!this.canvas) alert("Could not initialize canvas."); try { this.gl = this.canvas.getContext("webgl", {premultipliedAlpha: false, alpha: false, antialias: false}); if(!this.gl) this.gl = this.canvas.getContext("experimental-webgl", {premultipliedAlpha: false, alpha: false, antialias: false}); } catch(e) {} if(!this.gl) alert("Could not initialize WebGL."); this.gl.clearColor(0.0, 0.0, 0.0, 1.0); this.gl.clear(this.gl.COLOR_BUFFER_BIT); this.gl.colorMask(true, true, true, false); this.effect = { VertexTemplateCode : GetShaderCode("VertexTemplateCode"), FragmentShaderCode : GetShaderCode("FragmentShaderCode"), ColorFunction : "vec3 mainColor = mix( f3rand(vec2(floor(birthTime), 42.1)), f3rand(vec2(floor(birthTime)+1.0, 42.1)), fract(birthTime) )*4.0;\ vec3 startColor = f3rand(vec2(birthTime, 342.1))*0.1;\ vec3 finalColor = f3rand(vec2(birthTime, 39.6));\ return vec4( mix(startColor, finalColor, factor)*mainColor, (1.0-factor)*(1.0-factor) );", EmitterPositionFunction : SomeEmitterTrajectoryFunction, EmitterRotationFunction : "return vec3(5.2, -5., -3.)*t;", PositionFunction : SomeParticleTrajectoryFunction, SizeFunction : SomeSizeFunction, StartParametersFunction : SomeEmitterFunction }; this.progId = ParticleEffectDescToShader(this.gl, this.effect); this.timeLoc = this.gl.getUniformLocation(this.progId, "Time"); this.rateLoc = this.gl.getUniformLocation(this.progId, "Rate"); this.lifeTimeLoc = this.gl.getUniformLocation(this.progId, "LifeTime"); this.viewportLoc = this.gl.getUniformLocation(this.progId, "ViewportSize"); this.minSizeOrderLoc = this.gl.getUniformLocation(this.progId, "MinSizeOrder"); this.maxSizeOrderLoc = this.gl.getUniformLocation(this.progId, "MaxSizeOrder"); this.startIndexLoc = this.gl.getUniformLocation(this.progId, "StartIndex"); var buffer = new ArrayBuffer(65536); var array = new Float32Array(buffer); for(var i=0; i<16384; i++) array[i] = i; this.bufId = this.gl.createBuffer(); this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.bufId); this.gl.bufferData(this.gl.ARRAY_BUFFER, buffer, this.gl.STATIC_DRAW); array = null; buffer = null; this.gl.vertexAttribPointer(0, 1, this.gl.FLOAT, false, 4, 0); this.gl.enable(this.gl.BLEND); this.gl.blendFunc(this.gl.SRC_ALPHA, this.gl.ONE); this.projMatrix = makePerspective(60, this.canvas.width/this.canvas.height, 0.1, 100); this.rate = 10000; this.lifeTime = 5; this.gl.uniform1f(this.rateLoc, this.rate); this.gl.uniform1f(this.lifeTimeLoc, this.lifeTime); this.gl.uniform1f(this.minSizeOrderLoc, 0.0); this.gl.uniform1f(this.maxSizeOrderLoc, 2.5); this.time = 0; this.speed = 0.5; this.paused = false; window.onkeydown = function(e) { if(e.keyCode==73) Demo.time = 0.0; if(e.keyCode>=49 && e.keyCode<=57) { var rates = [2000, 2000, 10000, 10000, 100000, 100000, 200000, 500000, 1000000]; var lifeTimes = [2, 4, 2, 4, 2, 4, 5, 5, 10]; var minSizeOrders = [1.0, 1.0, 0.0, 0.0, -1.0, -1.0, -1.5, -2.0, -2.0]; var i = parseInt(e.keyCode)-49; Demo.rate = rates[i]; Demo.lifeTime = lifeTimes[i]; var minSizeOrder = minSizeOrders[i]; var maxSizeOrder = minSizeOrder+2.0; Demo.gl.uniform1f(Demo.rateLoc, Demo.rate); Demo.gl.uniform1f(Demo.lifeTimeLoc, Demo.lifeTime); Demo.gl.uniform1f(Demo.minSizeOrderLoc, minSizeOrder); Demo.gl.uniform1f(Demo.maxSizeOrderLoc, maxSizeOrder); } if(e.keyCode==16) Demo.speed *= 1.1; //shift if(e.keyCode==17) Demo.speed /= 1.1; //control if(Demo.speed>0 && e.keyCode==37 || Demo.speed<0 && e.keyCode==39) Demo.speed = -Demo.speed; //left or right if(e.keyCode==38) Demo.upPressed = true; if(e.keyCode==40) Demo.downPressed = true; if(e.keyCode==80) Demo.paused = !Demo.paused; if(e.keyCode==115) { if(Demo.canvas.requestFullScreen) Demo.canvas.requestFullScreen(); else if(Demo.canvas.webkitRequestFullScreen) Demo.canvas.webkitRequestFullScreen(); else Demo.canvas.mozRequestFullScreen(); } }; window.onkeyup = function(e) { if(e.keyCode==38) Demo.upPressed = false; if(e.keyCode==40) Demo.downPressed = false; }; this.OnWindowResize(); }, Step : function(dt) { var delta = dt; this.absTime += dt; if(this.upPressed) delta *= 5; else if(this.downPressed) delta *= -5; else if(this.paused) delta = 0; var s = Math.cos(this.absTime*0.23+0.9)*1.5-0.5; this.time += delta*this.speed*(1.0 + s + s*s*0.5 + s*s*s*0.167 + s*s*s*s*0.04); if(this.time<0) this.time = 0; }, } var RenderFrame = function() { Demo.gl.clear(Demo.gl.COLOR_BUFFER_BIT); Demo.worldViewMatrix = TranslationMatrix([0, 0, -7]).x(RotationMatrixDeg(Demo.time*20, [0.1, 0.9, 0])); SetMatrixUniform(Demo.gl, Demo.progId, "WorldViewMatrix", Demo.worldViewMatrix); Demo.gl.uniform1f(Demo.timeLoc, Demo.time); Demo.gl.enableVertexAttribArray(0); var particleCount = Math.floor(Math.min(Demo.time, Demo.lifeTime)*Demo.rate); var batchSize = 16384; var numBatches = Math.ceil(particleCount/batchSize); document.getElementById("particles.div").innerHTML = "Particles: " + particleCount; for(var i=0; i<numBatches; i++) { Demo.gl.uniform1f(Demo.startIndexLoc, i*batchSize); Demo.gl.drawArrays(Demo.gl.POINTS, 0, Math.min(particleCount, batchSize)); particleCount -= batchSize; } Demo.gl.disableVertexAttribArray(0); }; var gPrevTime; var frames = 0 var fpstime = new Date().getTime() function DemoMainLoop() { var now = new Date().getTime(); var dt = now - (gPrevTime || now); gPrevTime = now; Demo.Step(dt/1000); RenderFrame(); window.requestAnimFrame(DemoMainLoop); time = now; frames++; // update FPS two times per second if (now - fpstime > 500) { document.getElementById("fps.div").innerHTML = "FPS: " + (frames / (now - fpstime) * 1000).toFixed(2); fpstime = now frames = 0 } }
/** Custom trie implementation - Supports multiple entries and anything as leaves -- add -- (key{text}, item{anything}[optional]) //If item not present, key itself will be leaf --lookup -- (partial{text}) -- dumpJsonStr -- () -- wipe -- () Author : Aniket Lawande **/ define(function (require, exports, module) { "use strict"; /** Custom trie implementation - Supports multiple entries and anything as leaves -- add -- (key{text}, item{anything}[optional]) //If item not present, key itself will be leaf --lookup -- (partial{text}) -- dumpJsonStr -- () -- wipe -- () Author : Aniket Lawande **/ var LEAFIND = "$"; function Trie() { this.trie = {}; this.count = 0; } Trie.prototype.add = function(word, item) { if (word === undefined || word === null || word === "") return; var lword = word.toLowerCase(); var current = this.trie; for(var a = 0; a < lword.length ; a++) { if(current[lword[a]] === undefined) current[lword[a]] = {}; current = current[lword[a]]; } current[LEAFIND] = current[LEAFIND] || []; var toPush = item || word; current[LEAFIND].push(toPush); this.count++; return this; } Trie.prototype.lookup = function(word) { var results = []; if(word === undefined || word === null || word === "") return results; var lword = word.toLowerCase(); var current = this.trie; for(var a = 0; a < lword.length; a++) { if(current[lword[a]] === undefined) return results; current = current[lword[a]]; } getAllLeaves(current, results); return results; } Trie.prototype.top = function(max) { var results = []; max = max || 10; getAllLeaves(this.trie, results, max); return results; } function getAllLeaves(node, results, max) { if(max !== undefined && results.length >= max) return; for(var a in node) { if(node.hasOwnProperty(a)) { if(a === LEAFIND) flattenAndPush(node[a], results, max); else getAllLeaves(node[a], results, max); } } } function flattenAndPush(arr, results, max) { var arrlength = arr.length; for(var i = 0; i < arrlength; i++) { if(max !== undefined && results.length >= max) return; results.push(arr[i]); } } Trie.prototype.wipe = function() { delete this.trie; this.trie = {}; this.count = 0; return this; } Trie.prototype.dumpJsonStr = function() { return JSON.stringify(this.trie); } exports.Trie = Trie; });
version https://git-lfs.github.com/spec/v1 oid sha256:020caf1d4e1a321944ed6c57d2ddb4452fdca24efe694ef9e20b599e49846508 size 356
var PHASE_CODE = { BASIC: 0, DAY: 1, NIGHTCOMING: 2, WEREWOLF: 3, SEER: 4, WITCH: 5, HUNTER: 6, IDIOT: 7, VILLAGER: 8, ELDER: 9, SAVIOR: 10, KNIGHT: 11, HUNZI: 12, SUNRAISE: 13, END: 14 }; module.exports = PHASE_CODE;
/** * NotFoundPage * * This is the page we show when the user visits a url that doesn't have a route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react' import { FormattedMessage } from 'react-intl' import { PICTOGRAMS_URL } from 'services/config' import View from 'components/View' import Logo from 'components/Logo' import messages from './messages' export default class NotFound extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <View left={true} right={true} top={0}> <h1 style={{ textAlign: 'center' }}> <FormattedMessage {...messages.header} /> </h1> <div style={{ textAlign: 'center' }}><img src={`${PICTOGRAMS_URL}/21466/21466_300.png`} /></div> </View> ) } }
import React from 'react' import { Provider } from 'react-redux' import { Route, Switch } from 'react-router-dom'; import RegisterComponent from '../../RegisterComponent' import createStore from './redux/create' import AppList from './components/AppList' import AppUsers from './components/AppUsers' import AppEdit from './components/AppEdit' import AppDiff from './components/AppDiff' const ApplicationsAdminWidget = (props) => { const store = createStore(props) return ( <Provider store={store} > <Switch> <Route exact path="/admin/applications/:id/users" component={AppUsers} /> <Route path="/admin/applications/:id/edit" component={AppEdit} /> <Route path="/admin/applications/:id/diff" component={AppDiff} /> <Route path="/admin/applications" component={AppList} /> </Switch> </Provider> ) } export default new RegisterComponent({ 'applications-admin': ApplicationsAdminWidget })
// ------------------------------------ // Constants // ------------------------------------ export const GET_MESSAGE = 'GET_MESSAGE' export const ADD_MESSAGE = 'ADD_MESSAGE' // ------------------------------------ // Actions // ------------------------------------ export const addMessage = (value) => { return { type : ADD_MESSAGE, payload : value } } export const getMessage = () => { return (dispatch, getState) => { return new Promise((resolve) => { setTimeout(() => { dispatch({ type: GET_MESSAGE, payload: [{name: 'dyj', photo: '//i2.hdslb.com/bfs/face/c863184762be88ea07e388e2b1fa27fa192e47a5.jpg@52w_52h.webp', value: '第一个评论',level: 1, startTime: 1492737920404, children:[]}, {name: 'DDYYJJ', photo: '//i2.hdslb.com/bfs/face/c863184762be88ea07e388e2b1fa27fa192e47a5.jpg@52w_52h.webp', value: '第2个评论',level: 2, startTime: 1492737920404, children:[]}, {name: 'DDYYJJ', photo: '//i2.hdslb.com/bfs/face/c863184762be88ea07e388e2b1fa27fa192e47a5.jpg@52w_52h.webp', value: '第3个评论',level: 3, startTime: 1492737920404, children:[]}, {name: 'DDYYJJ', photo: '//i2.hdslb.com/bfs/face/c863184762be88ea07e388e2b1fa27fa192e47a5.jpg@52w_52h.webp', value: '第4个评论',level: 4, startTime: 1492737920404, children:[]}, {name: 'DDYYJJ', photo: '//i2.hdslb.com/bfs/face/c863184762be88ea07e388e2b1fa27fa192e47a5.jpg@52w_52h.webp', value: '第5个评论',level: 5, startTime: 1492737920404, children:[]}, {name: 'DDYYJJ', photo: '//i2.hdslb.com/bfs/face/c863184762be88ea07e388e2b1fa27fa192e47a5.jpg@52w_52h.webp', value: '第6个评论',level: 6, startTime: 1492737920404, children:[]}, {name: 'DDYYJJ', photo: '//i2.hdslb.com/bfs/face/c863184762be88ea07e388e2b1fa27fa192e47a5.jpg@52w_52h.webp', value: '第7个评论',level: 7, startTime: 1492737920404, children:[]}] }) resolve() }, 200) }) } } export const actions = { getMessage, addMessage } // ------------------------------------ // Action Handlers // ------------------------------------ const ACTION_HANDLERS = { [GET_MESSAGE] : (state, action) => ( Object.assign({}, state, {messages: action.payload}) ), [ADD_MESSAGE] : (state, action) => { debugger; } // [GET_MESSAGE] : function(state, action) {debugger; // var a = Object.assign({}, state, {messages: action.payload}) // debugger; // return a; // // return Object.assign({}, state, {nodes: action.payload}) // } } // ------------------------------------ // Reducer // ------------------------------------ const initialState = {messages: []} export default function messageboardReducer (state = initialState, action) { const handler = ACTION_HANDLERS[action.type] return handler ? handler(state, action) : state }
import ToggleElement from './element' customElements.define('shaf-toggle', ToggleElement)
var expect = require('expect'); var helpers = require('./helpers.js'); var validEmojiFormat = helpers.validEmojiFormat; var getRandomBanter = helpers.getRandomBanter; validEmojiFormatTest(); getRandomBanterTest(); function validEmojiFormatTest() { console.log('validEmojiFormat() test'); console.log('=> should return a valid emoji format'); expect(validEmojiFormat('heart')).toEqual(':heart:'); expect(validEmojiFormat(':heart:')).toEqual(':heart:'); expect(validEmojiFormat(':heart')).toEqual(':heart:'); expect(validEmojiFormat('heart:')).toEqual(':heart:'); console.log('✓ Passed test cases. \n'); } function getRandomBanterTest() { console.log('getRandomBanter() test'); console.log('=> should return a string'); expect(getRandomBanter()).toBeA('string'); expect(getRandomBanter()).toBeA('string'); expect(getRandomBanter()).toBeA('string'); expect(getRandomBanter()).toBeA('string'); console.log('✓ Passed test cases. \n'); }
import async from 'async' export default ({nspApiClient, db}) => { let syncAdvisoriesIntervalId = null const Nsp = { // Given a list of dependency names, retrieve an object that lists advisories // by dependency name getAdvisories (depNames, cb) { const tasks = depNames.reduce((tasks, depName) => { tasks[depName] = (cb) => { db.get(`nsp/advisories/${depName}`, (err, advisories) => { if (err) { if (err.notFound) return cb(null, []) return cb(err) } cb(null, advisories) }) } return tasks }, {}) async.parallel(tasks, cb) }, syncAdvisories (cb) { cb = cb || ((err) => { if (err) console.error('Failed to sync advisories', err) }) // Get the first page const limit = 100 let done = false nspApiClient.advisories({limit: 1, offset: 0}, (err, response) => { if (err) return cb(err) const pages = Math.ceil(response.total / limit) const offsets = [] for (let i = 0; i < pages; i++) { offsets.push(i * limit) } async.eachSeries(offsets, (offset, cb) => { if (done) return cb() nspApiClient.advisories({limit: limit - 1, offset}, (err, response) => { if (err) { console.error('Failed to get advisories page', offset) return cb(err) } async.eachSeries(response.results, (advisory, cb) => { if (done) return cb() const key = `nsp/advisories/${advisory.module_name}` db.get(key, (err, advisories) => { if (err) { if (err.notFound) { console.log('Adding first advisory', advisory.id, 'for module', advisory.module_name) return db.put(key, [advisory], cb) } return cb(err) } const advisoryIds = advisories.map((a) => a.id) if (advisoryIds.indexOf(advisory.id) > -1) { // Already found - we're all synced done = true cb() } else { console.log(`Adding another advisory ${advisory.id} for module ${advisory.module_name}`) db.put(key, advisories.concat(advisory), cb) } }) }, cb) }) }, cb) }) }, syncAdvisoriesPeriodically (interval) { clearInterval(syncAdvisoriesIntervalId) interval = interval || 3600000 syncAdvisoriesIntervalId = setInterval(Nsp.syncAdvisories, interval) } } return Nsp }
const validateString = (value) => { return (value != null && typeof value === 'string') ? value.trim() : null; } const validate = (value) => { return (value != null) ? value : null; } const validateUrl = (url) => { // check if url seems like a yelp url if (url.includes('yelp.com')) { // returns full url if no '?' return url.split('?')[0]; } else { return null; } } export { validateString, validate, validateUrl, };
! function(e, t) { "object" == typeof module && "object" == typeof module.exports ? module.exports = e.document ? t(e, !0) : function(e) { if (!e.document) throw new Error("jQuery requires a window with a document"); return t(e) } : t(e) }("undefined" != typeof window ? window : this, function(e, t) { function n(e) { var t = "length" in e && e.length, n = Z.type(e); return "function" !== n && !Z.isWindow(e) && (!(1 !== e.nodeType || !t) || ("array" === n || 0 === t || "number" == typeof t && t > 0 && t - 1 in e)) } function r(e, t, n) { if (Z.isFunction(t)) return Z.grep(e, function(e, r) { return !!t.call(e, r, e) !== n }); if (t.nodeType) return Z.grep(e, function(e) { return e === t !== n }); if ("string" == typeof t) { if (ae.test(t)) return Z.filter(t, e, n); t = Z.filter(t, e) } return Z.grep(e, function(e) { return V.call(t, e) >= 0 !== n }) } function i(e, t) { for (; (e = e[t]) && 1 !== e.nodeType;); return e } function o(e) { var t = he[e] = {}; return Z.each(e.match(pe) || [], function(e, n) { t[n] = !0 }), t } function s() { J.removeEventListener("DOMContentLoaded", s, !1), e.removeEventListener("load", s, !1), Z.ready() } function a() { Object.defineProperty(this.cache = {}, 0, { get: function() { return {} } }), this.expando = Z.expando + a.uid++ } function u(e, t, n) { var r; if (void 0 === n && 1 === e.nodeType) if (r = "data-" + t.replace(be, "-$1").toLowerCase(), n = e.getAttribute(r), "string" == typeof n) { try { n = "true" === n || "false" !== n && ("null" === n ? null : +n + "" === n ? +n : xe.test(n) ? Z.parseJSON(n) : n) } catch (i) {} ye.set(e, t, n) } else n = void 0; return n } function l() { return !0 } function c() { return !1 } function f() { try { return J.activeElement } catch (e) {} } function d(e, t) { return Z.nodeName(e, "table") && Z.nodeName(11 !== t.nodeType ? t : t.firstChild, "tr") ? e.getElementsByTagName("tbody")[0] || e.appendChild(e.ownerDocument.createElement("tbody")) : e } function p(e) { return e.type = (null !== e.getAttribute("type")) + "/" + e.type, e } function h(e) { var t = Pe.exec(e.type); return t ? e.type = t[1] : e.removeAttribute("type"), e } function g(e, t) { for (var n = 0, r = e.length; r > n; n++) ve.set(e[n], "globalEval", !t || ve.get(t[n], "globalEval")) } function m(e, t) { var n, r, i, o, s, a, u, l; if (1 === t.nodeType) { if (ve.hasData(e) && (o = ve.access(e), s = ve.set(t, o), l = o.events)) { delete s.handle, s.events = {}; for (i in l) for (n = 0, r = l[i].length; r > n; n++) Z.event.add(t, i, l[i][n]) } ye.hasData(e) && (a = ye.access(e), u = Z.extend({}, a), ye.set(t, u)) } } function v(e, t) { var n = e.getElementsByTagName ? e.getElementsByTagName(t || "*") : e.querySelectorAll ? e.querySelectorAll(t || "*") : []; return void 0 === t || t && Z.nodeName(e, t) ? Z.merge([e], n) : n } function y(e, t) { var n = t.nodeName.toLowerCase(); "input" === n && ke.test(e.type) ? t.checked = e.checked : ("input" === n || "textarea" === n) && (t.defaultValue = e.defaultValue) } function x(t, n) { var r, i = Z(n.createElement(t)).appendTo(n.body), o = e.getDefaultComputedStyle && (r = e.getDefaultComputedStyle(i[0])) ? r.display : Z.css(i[0], "display"); return i.detach(), o } function b(e) { var t = J, n = Ie[e]; return n || (n = x(e, t), "none" !== n && n || (We = (We || Z("<iframe frameborder='0' width='0' height='0'/>")).appendTo(t.documentElement), t = We[0].contentDocument, t.write(), t.close(), n = x(e, t), We.detach()), Ie[e] = n), n } function w(e, t, n) { var r, i, o, s, a = e.style; return n = n || _e(e), n && (s = n.getPropertyValue(t) || n[t]), n && ("" !== s || Z.contains(e.ownerDocument, e) || (s = Z.style(e, t)), Be.test(s) && $e.test(t) && (r = a.width, i = a.minWidth, o = a.maxWidth, a.minWidth = a.maxWidth = a.width = s, s = n.width, a.width = r, a.minWidth = i, a.maxWidth = o)), void 0 !== s ? s + "" : s } function T(e, t) { return { get: function() { return e() ? void delete this.get : (this.get = t).apply(this, arguments) } } } function C(e, t) { if (t in e) return t; for (var n = t[0].toUpperCase() + t.slice(1), r = t, i = Ge.length; i--;) if (t = Ge[i] + n, t in e) return t; return r } function k(e, t, n) { var r = Xe.exec(t); return r ? Math.max(0, r[1] - (n || 0)) + (r[2] || "px") : t } function N(e, t, n, r, i) { for (var o = n === (r ? "border" : "content") ? 4 : "width" === t ? 1 : 0, s = 0; 4 > o; o += 2) "margin" === n && (s += Z.css(e, n + Te[o], !0, i)), r ? ("content" === n && (s -= Z.css(e, "padding" + Te[o], !0, i)), "margin" !== n && (s -= Z.css(e, "border" + Te[o] + "Width", !0, i))) : (s += Z.css(e, "padding" + Te[o], !0, i), "padding" !== n && (s += Z.css(e, "border" + Te[o] + "Width", !0, i))); return s } function E(e, t, n) { var r = !0, i = "width" === t ? e.offsetWidth : e.offsetHeight, o = _e(e), s = "border-box" === Z.css(e, "boxSizing", !1, o); if (0 >= i || null == i) { if (i = w(e, t, o), (0 > i || null == i) && (i = e.style[t]), Be.test(i)) return i; r = s && (Q.boxSizingReliable() || i === e.style[t]), i = parseFloat(i) || 0 } return i + N(e, t, n || (s ? "border" : "content"), r, o) + "px" } function j(e, t) { for (var n, r, i, o = [], s = 0, a = e.length; a > s; s++) r = e[s], r.style && (o[s] = ve.get(r, "olddisplay"), n = r.style.display, t ? (o[s] || "none" !== n || (r.style.display = ""), "" === r.style.display && Ce(r) && (o[s] = ve.access(r, "olddisplay", b(r.nodeName)))) : (i = Ce(r), "none" === n && i || ve.set(r, "olddisplay", i ? n : Z.css(r, "display")))); for (s = 0; a > s; s++) r = e[s], r.style && (t && "none" !== r.style.display && "" !== r.style.display || (r.style.display = t ? o[s] || "" : "none")); return e } function S(e, t, n, r, i) { return new S.prototype.init(e, t, n, r, i) } function D() { return setTimeout(function() { Qe = void 0 }), Qe = Z.now() } function A(e, t) { var n, r = 0, i = { height: e }; for (t = t ? 1 : 0; 4 > r; r += 2 - t) n = Te[r], i["margin" + n] = i["padding" + n] = e; return t && (i.opacity = i.width = e), i } function L(e, t, n) { for (var r, i = (nt[t] || []).concat(nt["*"]), o = 0, s = i.length; s > o; o++) if (r = i[o].call(n, t, e)) return r } function q(e, t, n) { var r, i, o, s, a, u, l, c, f = this, d = {}, p = e.style, h = e.nodeType && Ce(e), g = ve.get(e, "fxshow"); n.queue || (a = Z._queueHooks(e, "fx"), null == a.unqueued && (a.unqueued = 0, u = a.empty.fire, a.empty.fire = function() { a.unqueued || u() }), a.unqueued++, f.always(function() { f.always(function() { a.unqueued--, Z.queue(e, "fx").length || a.empty.fire() }) })), 1 === e.nodeType && ("height" in t || "width" in t) && (n.overflow = [p.overflow, p.overflowX, p.overflowY], l = Z.css(e, "display"), c = "none" === l ? ve.get(e, "olddisplay") || b(e.nodeName) : l, "inline" === c && "none" === Z.css(e, "float") && (p.display = "inline-block")), n.overflow && (p.overflow = "hidden", f.always(function() { p.overflow = n.overflow[0], p.overflowX = n.overflow[1], p.overflowY = n.overflow[2] })); for (r in t) if (i = t[r], Ke.exec(i)) { if (delete t[r], o = o || "toggle" === i, i === (h ? "hide" : "show")) { if ("show" !== i || !g || void 0 === g[r]) continue; h = !0 } d[r] = g && g[r] || Z.style(e, r) } else l = void 0; if (Z.isEmptyObject(d)) "inline" === ("none" === l ? b(e.nodeName) : l) && (p.display = l); else { g ? "hidden" in g && (h = g.hidden) : g = ve.access(e, "fxshow", {}), o && (g.hidden = !h), h ? Z(e).show() : f.done(function() { Z(e).hide() }), f.done(function() { var t; ve.remove(e, "fxshow"); for (t in d) Z.style(e, t, d[t]) }); for (r in d) s = L(h ? g[r] : 0, r, f), r in g || (g[r] = s.start, h && (s.end = s.start, s.start = "width" === r || "height" === r ? 1 : 0)) } } function H(e, t) { var n, r, i, o, s; for (n in e) if (r = Z.camelCase(n), i = t[r], o = e[n], Z.isArray(o) && (i = o[1], o = e[n] = o[0]), n !== r && (e[r] = o, delete e[n]), s = Z.cssHooks[r], s && "expand" in s) { o = s.expand(o), delete e[r]; for (n in o) n in e || (e[n] = o[n], t[n] = i) } else t[r] = i } function O(e, t, n) { var r, i, o = 0, s = tt.length, a = Z.Deferred().always(function() { delete u.elem }), u = function() { if (i) return !1; for (var t = Qe || D(), n = Math.max(0, l.startTime + l.duration - t), r = n / l.duration || 0, o = 1 - r, s = 0, u = l.tweens.length; u > s; s++) l.tweens[s].run(o); return a.notifyWith(e, [l, o, n]), 1 > o && u ? n : (a.resolveWith(e, [l]), !1) }, l = a.promise({ elem: e, props: Z.extend({}, t), opts: Z.extend(!0, { specialEasing: {} }, n), originalProperties: t, originalOptions: n, startTime: Qe || D(), duration: n.duration, tweens: [], createTween: function(t, n) { var r = Z.Tween(e, l.opts, t, n, l.opts.specialEasing[t] || l.opts.easing); return l.tweens.push(r), r }, stop: function(t) { var n = 0, r = t ? l.tweens.length : 0; if (i) return this; for (i = !0; r > n; n++) l.tweens[n].run(1); return t ? a.resolveWith(e, [l, t]) : a.rejectWith(e, [l, t]), this } }), c = l.props; for (H(c, l.opts.specialEasing); s > o; o++) if (r = tt[o].call(l, e, c, l.opts)) return r; return Z.map(c, L, l), Z.isFunction(l.opts.start) && l.opts.start.call(e, l), Z.fx.timer(Z.extend(u, { elem: e, anim: l, queue: l.opts.queue })), l.progress(l.opts.progress).done(l.opts.done, l.opts.complete).fail(l.opts.fail).always(l.opts.always) } function F(e) { return function(t, n) { "string" != typeof t && (n = t, t = "*"); var r, i = 0, o = t.toLowerCase().match(pe) || []; if (Z.isFunction(n)) for (; r = o[i++];) "+" === r[0] ? (r = r.slice(1) || "*", (e[r] = e[r] || []).unshift(n)) : (e[r] = e[r] || []).push(n) } } function P(e, t, n, r) { function i(a) { var u; return o[a] = !0, Z.each(e[a] || [], function(e, a) { var l = a(t, n, r); return "string" != typeof l || s || o[l] ? s ? !(u = l) : void 0 : (t.dataTypes.unshift(l), i(l), !1) }), u } var o = {}, s = e === xt; return i(t.dataTypes[0]) || !o["*"] && i("*") } function M(e, t) { var n, r, i = Z.ajaxSettings.flatOptions || {}; for (n in t) void 0 !== t[n] && ((i[n] ? e : r || (r = {}))[n] = t[n]); return r && Z.extend(!0, e, r), e } function R(e, t, n) { for (var r, i, o, s, a = e.contents, u = e.dataTypes; "*" === u[0];) u.shift(), void 0 === r && (r = e.mimeType || t.getResponseHeader("Content-Type")); if (r) for (i in a) if (a[i] && a[i].test(r)) { u.unshift(i); break } if (u[0] in n) o = u[0]; else { for (i in n) { if (!u[0] || e.converters[i + " " + u[0]]) { o = i; break } s || (s = i) } o = o || s } return o ? (o !== u[0] && u.unshift(o), n[o]) : void 0 } function W(e, t, n, r) { var i, o, s, a, u, l = {}, c = e.dataTypes.slice(); if (c[1]) for (s in e.converters) l[s.toLowerCase()] = e.converters[s]; for (o = c.shift(); o;) if (e.responseFields[o] && (n[e.responseFields[o]] = t), !u && r && e.dataFilter && (t = e.dataFilter(t, e.dataType)), u = o, o = c.shift()) if ("*" === o) o = u; else if ("*" !== u && u !== o) { if (s = l[u + " " + o] || l["* " + o], !s) for (i in l) if (a = i.split(" "), a[1] === o && (s = l[u + " " + a[0]] || l["* " + a[0]])) { s === !0 ? s = l[i] : l[i] !== !0 && (o = a[0], c.unshift(a[1])); break } if (s !== !0) if (s && e["throws"]) t = s(t); else try { t = s(t) } catch (f) { return { state: "parsererror", error: s ? f : "No conversion from " + u + " to " + o } } } return { state: "success", data: t } } function I(e, t, n, r) { var i; if (Z.isArray(t)) Z.each(t, function(t, i) { n || kt.test(e) ? r(e, i) : I(e + "[" + ("object" == typeof i ? t : "") + "]", i, n, r) }); else if (n || "object" !== Z.type(t)) r(e, t); else for (i in t) I(e + "[" + i + "]", t[i], n, r) } function $(e) { return Z.isWindow(e) ? e : 9 === e.nodeType && e.defaultView } var B = [], _ = B.slice, z = B.concat, X = B.push, V = B.indexOf, U = {}, Y = U.toString, G = U.hasOwnProperty, Q = {}, J = e.document, K = "2.1.4", Z = function(e, t) { return new Z.fn.init(e, t) }, ee = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, te = /^-ms-/, ne = /-([\da-z])/gi, re = function(e, t) { return t.toUpperCase() }; Z.fn = Z.prototype = { jquery: K, constructor: Z, selector: "", length: 0, toArray: function() { return _.call(this) }, get: function(e) { return null != e ? 0 > e ? this[e + this.length] : this[e] : _.call(this) }, pushStack: function(e) { var t = Z.merge(this.constructor(), e); return t.prevObject = this, t.context = this.context, t }, each: function(e, t) { return Z.each(this, e, t) }, map: function(e) { return this.pushStack(Z.map(this, function(t, n) { return e.call(t, n, t) })) }, slice: function() { return this.pushStack(_.apply(this, arguments)) }, first: function() { return this.eq(0) }, last: function() { return this.eq(-1) }, eq: function(e) { var t = this.length, n = +e + (0 > e ? t : 0); return this.pushStack(n >= 0 && t > n ? [this[n]] : []) }, end: function() { return this.prevObject || this.constructor(null) }, push: X, sort: B.sort, splice: B.splice }, Z.extend = Z.fn.extend = function() { var e, t, n, r, i, o, s = arguments[0] || {}, a = 1, u = arguments.length, l = !1; for ("boolean" == typeof s && (l = s, s = arguments[a] || {}, a++), "object" == typeof s || Z.isFunction(s) || (s = {}), a === u && (s = this, a--); u > a; a++) if (null != (e = arguments[a])) for (t in e) n = s[t], r = e[t], s !== r && (l && r && (Z.isPlainObject(r) || (i = Z.isArray(r))) ? (i ? (i = !1, o = n && Z.isArray(n) ? n : []) : o = n && Z.isPlainObject(n) ? n : {}, s[t] = Z.extend(l, o, r)) : void 0 !== r && (s[t] = r)); return s }, Z.extend({ expando: "jQuery" + (K + Math.random()).replace(/\D/g, ""), isReady: !0, error: function(e) { throw new Error(e) }, noop: function() {}, isFunction: function(e) { return "function" === Z.type(e) }, isArray: Array.isArray, isWindow: function(e) { return null != e && e === e.window }, isNumeric: function(e) { return !Z.isArray(e) && e - parseFloat(e) + 1 >= 0 }, isPlainObject: function(e) { return "object" === Z.type(e) && !e.nodeType && !Z.isWindow(e) && !(e.constructor && !G.call(e.constructor.prototype, "isPrototypeOf")) }, isEmptyObject: function(e) { var t; for (t in e) return !1; return !0 }, type: function(e) { return null == e ? e + "" : "object" == typeof e || "function" == typeof e ? U[Y.call(e)] || "object" : typeof e }, globalEval: function(e) { var t, n = eval; e = Z.trim(e), e && (1 === e.indexOf("use strict") ? (t = J.createElement("script"), t.text = e, J.head.appendChild(t).parentNode.removeChild(t)) : n(e)) }, camelCase: function(e) { return e.replace(te, "ms-").replace(ne, re) }, nodeName: function(e, t) { return e.nodeName && e.nodeName.toLowerCase() === t.toLowerCase() }, each: function(e, t, r) { var i, o = 0, s = e.length, a = n(e); if (r) { if (a) for (; s > o && (i = t.apply(e[o], r), i !== !1); o++); else for (o in e) if (i = t.apply(e[o], r), i === !1) break } else if (a) for (; s > o && (i = t.call(e[o], o, e[o]), i !== !1); o++); else for (o in e) if (i = t.call(e[o], o, e[o]), i === !1) break; return e }, trim: function(e) { return null == e ? "" : (e + "").replace(ee, "") }, makeArray: function(e, t) { var r = t || []; return null != e && (n(Object(e)) ? Z.merge(r, "string" == typeof e ? [e] : e) : X.call(r, e)), r }, inArray: function(e, t, n) { return null == t ? -1 : V.call(t, e, n) }, merge: function(e, t) { for (var n = +t.length, r = 0, i = e.length; n > r; r++) e[i++] = t[r]; return e.length = i, e }, grep: function(e, t, n) { for (var r, i = [], o = 0, s = e.length, a = !n; s > o; o++) r = !t(e[o], o), r !== a && i.push(e[o]); return i }, map: function(e, t, r) { var i, o = 0, s = e.length, a = n(e), u = []; if (a) for (; s > o; o++) i = t(e[o], o, r), null != i && u.push(i); else for (o in e) i = t(e[o], o, r), null != i && u.push(i); return z.apply([], u) }, guid: 1, proxy: function(e, t) { var n, r, i; return "string" == typeof t && (n = e[t], t = e, e = n), Z.isFunction(e) ? (r = _.call(arguments, 2), i = function() { return e.apply(t || this, r.concat(_.call(arguments))) }, i.guid = e.guid = e.guid || Z.guid++, i) : void 0 }, now: Date.now, support: Q }), Z.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(e, t) { U["[object " + t + "]"] = t.toLowerCase() }); var ie = function(e) { function t(e, t, n, r) { var i, o, s, a, u, l, f, p, h, g; if ((t ? t.ownerDocument || t : I) !== q && L(t), t = t || q, n = n || [], a = t.nodeType, "string" != typeof e || !e || 1 !== a && 9 !== a && 11 !== a) return n; if (!r && O) { if (11 !== a && (i = ye.exec(e))) if (s = i[1]) { if (9 === a) { if (o = t.getElementById(s), !o || !o.parentNode) return n; if (o.id === s) return n.push(o), n } else if (t.ownerDocument && (o = t.ownerDocument.getElementById(s)) && R(t, o) && o.id === s) return n.push(o), n } else { if (i[2]) return K.apply(n, t.getElementsByTagName(e)), n; if ((s = i[3]) && w.getElementsByClassName) return K.apply(n, t.getElementsByClassName(s)), n } if (w.qsa && (!F || !F.test(e))) { if (p = f = W, h = t, g = 1 !== a && e, 1 === a && "object" !== t.nodeName.toLowerCase()) { for (l = N(e), (f = t.getAttribute("id")) ? p = f.replace(be, "\\$&") : t.setAttribute("id", p), p = "[id='" + p + "'] ", u = l.length; u--;) l[u] = p + d(l[u]); h = xe.test(e) && c(t.parentNode) || t, g = l.join(",") } if (g) try { return K.apply(n, h.querySelectorAll(g)), n } catch (m) {} finally { f || t.removeAttribute("id") } } } return j(e.replace(ue, "$1"), t, n, r) } function n() { function e(n, r) { return t.push(n + " ") > T.cacheLength && delete e[t.shift()], e[n + " "] = r } var t = []; return e } function r(e) { return e[W] = !0, e } function i(e) { var t = q.createElement("div"); try { return !!e(t) } catch (n) { return !1 } finally { t.parentNode && t.parentNode.removeChild(t), t = null } } function o(e, t) { for (var n = e.split("|"), r = e.length; r--;) T.attrHandle[n[r]] = t } function s(e, t) { var n = t && e, r = n && 1 === e.nodeType && 1 === t.nodeType && (~t.sourceIndex || U) - (~e.sourceIndex || U); if (r) return r; if (n) for (; n = n.nextSibling;) if (n === t) return -1; return e ? 1 : -1 } function a(e) { return function(t) { var n = t.nodeName.toLowerCase(); return "input" === n && t.type === e } } function u(e) { return function(t) { var n = t.nodeName.toLowerCase(); return ("input" === n || "button" === n) && t.type === e } } function l(e) { return r(function(t) { return t = +t, r(function(n, r) { for (var i, o = e([], n.length, t), s = o.length; s--;) n[i = o[s]] && (n[i] = !(r[i] = n[i])) }) }) } function c(e) { return e && "undefined" != typeof e.getElementsByTagName && e } function f() {} function d(e) { for (var t = 0, n = e.length, r = ""; n > t; t++) r += e[t].value; return r } function p(e, t, n) { var r = t.dir, i = n && "parentNode" === r, o = B++; return t.first ? function(t, n, o) { for (; t = t[r];) if (1 === t.nodeType || i) return e(t, n, o) } : function(t, n, s) { var a, u, l = [$, o]; if (s) { for (; t = t[r];) if ((1 === t.nodeType || i) && e(t, n, s)) return !0 } else for (; t = t[r];) if (1 === t.nodeType || i) { if (u = t[W] || (t[W] = {}), (a = u[r]) && a[0] === $ && a[1] === o) return l[2] = a[2]; if (u[r] = l, l[2] = e(t, n, s)) return !0 } } } function h(e) { return e.length > 1 ? function(t, n, r) { for (var i = e.length; i--;) if (!e[i](t, n, r)) return !1; return !0 } : e[0] } function g(e, n, r) { for (var i = 0, o = n.length; o > i; i++) t(e, n[i], r); return r } function m(e, t, n, r, i) { for (var o, s = [], a = 0, u = e.length, l = null != t; u > a; a++)(o = e[a]) && (!n || n(o, r, i)) && (s.push(o), l && t.push(a)); return s } function v(e, t, n, i, o, s) { return i && !i[W] && (i = v(i)), o && !o[W] && (o = v(o, s)), r(function(r, s, a, u) { var l, c, f, d = [], p = [], h = s.length, v = r || g(t || "*", a.nodeType ? [a] : a, []), y = !e || !r && t ? v : m(v, d, e, a, u), x = n ? o || (r ? e : h || i) ? [] : s : y; if (n && n(y, x, a, u), i) for (l = m(x, p), i(l, [], a, u), c = l.length; c--;)(f = l[c]) && (x[p[c]] = !(y[p[c]] = f)); if (r) { if (o || e) { if (o) { for (l = [], c = x.length; c--;)(f = x[c]) && l.push(y[c] = f); o(null, x = [], l, u) } for (c = x.length; c--;)(f = x[c]) && (l = o ? ee(r, f) : d[c]) > -1 && (r[l] = !(s[l] = f)) } } else x = m(x === s ? x.splice(h, x.length) : x), o ? o(null, s, x, u) : K.apply(s, x) }) } function y(e) { for (var t, n, r, i = e.length, o = T.relative[e[0].type], s = o || T.relative[" "], a = o ? 1 : 0, u = p(function(e) { return e === t }, s, !0), l = p(function(e) { return ee(t, e) > -1 }, s, !0), c = [function(e, n, r) { var i = !o && (r || n !== S) || ((t = n).nodeType ? u(e, n, r) : l(e, n, r)); return t = null, i }]; i > a; a++) if (n = T.relative[e[a].type]) c = [p(h(c), n)]; else { if (n = T.filter[e[a].type].apply(null, e[a].matches), n[W]) { for (r = ++a; i > r && !T.relative[e[r].type]; r++); return v(a > 1 && h(c), a > 1 && d(e.slice(0, a - 1).concat({ value: " " === e[a - 2].type ? "*" : "" })).replace(ue, "$1"), n, r > a && y(e.slice(a, r)), i > r && y(e = e.slice(r)), i > r && d(e)) } c.push(n) } return h(c) } function x(e, n) { var i = n.length > 0, o = e.length > 0, s = function(r, s, a, u, l) { var c, f, d, p = 0, h = "0", g = r && [], v = [], y = S, x = r || o && T.find.TAG("*", l), b = $ += null == y ? 1 : Math.random() || .1, w = x.length; for (l && (S = s !== q && s); h !== w && null != (c = x[h]); h++) { if (o && c) { for (f = 0; d = e[f++];) if (d(c, s, a)) { u.push(c); break } l && ($ = b) } i && ((c = !d && c) && p--, r && g.push(c)) } if (p += h, i && h !== p) { for (f = 0; d = n[f++];) d(g, v, s, a); if (r) { if (p > 0) for (; h--;) g[h] || v[h] || (v[h] = Q.call(u)); v = m(v) } K.apply(u, v), l && !r && v.length > 0 && p + n.length > 1 && t.uniqueSort(u) } return l && ($ = b, S = y), g }; return i ? r(s) : s } var b, w, T, C, k, N, E, j, S, D, A, L, q, H, O, F, P, M, R, W = "sizzle" + 1 * new Date, I = e.document, $ = 0, B = 0, _ = n(), z = n(), X = n(), V = function(e, t) { return e === t && (A = !0), 0 }, U = 1 << 31, Y = {}.hasOwnProperty, G = [], Q = G.pop, J = G.push, K = G.push, Z = G.slice, ee = function(e, t) { for (var n = 0, r = e.length; r > n; n++) if (e[n] === t) return n; return -1 }, te = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", ne = "[\\x20\\t\\r\\n\\f]", re = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", ie = re.replace("w", "w#"), oe = "\\[" + ne + "*(" + re + ")(?:" + ne + "*([*^$|!~]?=)" + ne + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + ie + "))|)" + ne + "*\\]", se = ":(" + re + ")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|" + oe + ")*)|.*)\\)|)", ae = new RegExp(ne + "+", "g"), ue = new RegExp("^" + ne + "+|((?:^|[^\\\\])(?:\\\\.)*)" + ne + "+$", "g"), le = new RegExp("^" + ne + "*," + ne + "*"), ce = new RegExp("^" + ne + "*([>+~]|" + ne + ")" + ne + "*"), fe = new RegExp("=" + ne + "*([^\\]'\"]*?)" + ne + "*\\]", "g"), de = new RegExp(se), pe = new RegExp("^" + ie + "$"), he = { ID: new RegExp("^#(" + re + ")"), CLASS: new RegExp("^\\.(" + re + ")"), TAG: new RegExp("^(" + re.replace("w", "w*") + ")"), ATTR: new RegExp("^" + oe), PSEUDO: new RegExp("^" + se), CHILD: new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + ne + "*(even|odd|(([+-]|)(\\d*)n|)" + ne + "*(?:([+-]|)" + ne + "*(\\d+)|))" + ne + "*\\)|)", "i"), bool: new RegExp("^(?:" + te + ")$", "i"), needsContext: new RegExp("^" + ne + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + ne + "*((?:-\\d)?\\d*)" + ne + "*\\)|)(?=[^-]|$)", "i") }, ge = /^(?:input|select|textarea|button)$/i, me = /^h\d$/i, ve = /^[^{]+\{\s*\[native \w/, ye = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, xe = /[+~]/, be = /'|\\/g, we = new RegExp("\\\\([\\da-f]{1,6}" + ne + "?|(" + ne + ")|.)", "ig"), Te = function(e, t, n) { var r = "0x" + t - 65536; return r !== r || n ? t : 0 > r ? String.fromCharCode(r + 65536) : String.fromCharCode(r >> 10 | 55296, 1023 & r | 56320) }, Ce = function() { L() }; try { K.apply(G = Z.call(I.childNodes), I.childNodes), G[I.childNodes.length].nodeType } catch (ke) { K = { apply: G.length ? function(e, t) { J.apply(e, Z.call(t)) } : function(e, t) { for (var n = e.length, r = 0; e[n++] = t[r++];); e.length = n - 1 } } } w = t.support = {}, k = t.isXML = function(e) { var t = e && (e.ownerDocument || e).documentElement; return !!t && "HTML" !== t.nodeName }, L = t.setDocument = function(e) { var t, n, r = e ? e.ownerDocument || e : I; return r !== q && 9 === r.nodeType && r.documentElement ? (q = r, H = r.documentElement, n = r.defaultView, n && n !== n.top && (n.addEventListener ? n.addEventListener("unload", Ce, !1) : n.attachEvent && n.attachEvent("onunload", Ce)), O = !k(r), w.attributes = i(function(e) { return e.className = "i", !e.getAttribute("className") }), w.getElementsByTagName = i(function(e) { return e.appendChild(r.createComment("")), !e.getElementsByTagName("*").length }), w.getElementsByClassName = ve.test(r.getElementsByClassName), w.getById = i(function(e) { return H.appendChild(e).id = W, !r.getElementsByName || !r.getElementsByName(W).length }), w.getById ? (T.find.ID = function(e, t) { if ("undefined" != typeof t.getElementById && O) { var n = t.getElementById(e); return n && n.parentNode ? [n] : [] } }, T.filter.ID = function(e) { var t = e.replace(we, Te); return function(e) { return e.getAttribute("id") === t } }) : (delete T.find.ID, T.filter.ID = function(e) { var t = e.replace(we, Te); return function(e) { var n = "undefined" != typeof e.getAttributeNode && e.getAttributeNode("id"); return n && n.value === t } }), T.find.TAG = w.getElementsByTagName ? function(e, t) { return "undefined" != typeof t.getElementsByTagName ? t.getElementsByTagName(e) : w.qsa ? t.querySelectorAll(e) : void 0 } : function(e, t) { var n, r = [], i = 0, o = t.getElementsByTagName(e); if ("*" === e) { for (; n = o[i++];) 1 === n.nodeType && r.push(n); return r } return o }, T.find.CLASS = w.getElementsByClassName && function(e, t) { return O ? t.getElementsByClassName(e) : void 0 }, P = [], F = [], (w.qsa = ve.test(r.querySelectorAll)) && (i(function(e) { H.appendChild(e).innerHTML = "<a id='" + W + "'></a><select id='" + W + "-\f]' msallowcapture=''><option selected=''></option></select>", e.querySelectorAll("[msallowcapture^='']").length && F.push("[*^$]=" + ne + "*(?:''|\"\")"), e.querySelectorAll("[selected]").length || F.push("\\[" + ne + "*(?:value|" + te + ")"), e.querySelectorAll("[id~=" + W + "-]").length || F.push("~="), e.querySelectorAll(":checked").length || F.push(":checked"), e.querySelectorAll("a#" + W + "+*").length || F.push(".#.+[+~]") }), i(function(e) { var t = r.createElement("input"); t.setAttribute("type", "hidden"), e.appendChild(t).setAttribute("name", "D"), e.querySelectorAll("[name=d]").length && F.push("name" + ne + "*[*^$|!~]?="), e.querySelectorAll(":enabled").length || F.push(":enabled", ":disabled"), e.querySelectorAll("*,:x"), F.push(",.*:") })), (w.matchesSelector = ve.test(M = H.matches || H.webkitMatchesSelector || H.mozMatchesSelector || H.oMatchesSelector || H.msMatchesSelector)) && i(function(e) { w.disconnectedMatch = M.call(e, "div"), M.call(e, "[s!='']:x"), P.push("!=", se) }), F = F.length && new RegExp(F.join("|")), P = P.length && new RegExp(P.join("|")), t = ve.test(H.compareDocumentPosition), R = t || ve.test(H.contains) ? function(e, t) { var n = 9 === e.nodeType ? e.documentElement : e, r = t && t.parentNode; return e === r || !(!r || 1 !== r.nodeType || !(n.contains ? n.contains(r) : e.compareDocumentPosition && 16 & e.compareDocumentPosition(r))) } : function(e, t) { if (t) for (; t = t.parentNode;) if (t === e) return !0; return !1 }, V = t ? function(e, t) { if (e === t) return A = !0, 0; var n = !e.compareDocumentPosition - !t.compareDocumentPosition; return n ? n : (n = (e.ownerDocument || e) === (t.ownerDocument || t) ? e.compareDocumentPosition(t) : 1, 1 & n || !w.sortDetached && t.compareDocumentPosition(e) === n ? e === r || e.ownerDocument === I && R(I, e) ? -1 : t === r || t.ownerDocument === I && R(I, t) ? 1 : D ? ee(D, e) - ee(D, t) : 0 : 4 & n ? -1 : 1) } : function(e, t) { if (e === t) return A = !0, 0; var n, i = 0, o = e.parentNode, a = t.parentNode, u = [e], l = [t]; if (!o || !a) return e === r ? -1 : t === r ? 1 : o ? -1 : a ? 1 : D ? ee(D, e) - ee(D, t) : 0; if (o === a) return s(e, t); for (n = e; n = n.parentNode;) u.unshift(n); for (n = t; n = n.parentNode;) l.unshift(n); for (; u[i] === l[i];) i++; return i ? s(u[i], l[i]) : u[i] === I ? -1 : l[i] === I ? 1 : 0 }, r) : q }, t.matches = function(e, n) { return t(e, null, null, n) }, t.matchesSelector = function(e, n) { if ((e.ownerDocument || e) !== q && L(e), n = n.replace(fe, "='$1']"), !(!w.matchesSelector || !O || P && P.test(n) || F && F.test(n))) try { var r = M.call(e, n); if (r || w.disconnectedMatch || e.document && 11 !== e.document.nodeType) return r } catch (i) {} return t(n, q, null, [e]).length > 0 }, t.contains = function(e, t) { return (e.ownerDocument || e) !== q && L(e), R(e, t) }, t.attr = function(e, t) { (e.ownerDocument || e) !== q && L(e); var n = T.attrHandle[t.toLowerCase()], r = n && Y.call(T.attrHandle, t.toLowerCase()) ? n(e, t, !O) : void 0; return void 0 !== r ? r : w.attributes || !O ? e.getAttribute(t) : (r = e.getAttributeNode(t)) && r.specified ? r.value : null }, t.error = function(e) { throw new Error("Syntax error, unrecognized expression: " + e) }, t.uniqueSort = function(e) { var t, n = [], r = 0, i = 0; if (A = !w.detectDuplicates, D = !w.sortStable && e.slice(0), e.sort(V), A) { for (; t = e[i++];) t === e[i] && (r = n.push(i)); for (; r--;) e.splice(n[r], 1) } return D = null, e }, C = t.getText = function(e) { var t, n = "", r = 0, i = e.nodeType; if (i) { if (1 === i || 9 === i || 11 === i) { if ("string" == typeof e.textContent) return e.textContent; for (e = e.firstChild; e; e = e.nextSibling) n += C(e) } else if (3 === i || 4 === i) return e.nodeValue } else for (; t = e[r++];) n += C(t); return n }, T = t.selectors = { cacheLength: 50, createPseudo: r, match: he, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: !0 }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: !0 }, "~": { dir: "previousSibling" } }, preFilter: { ATTR: function(e) { return e[1] = e[1].replace(we, Te), e[3] = (e[3] || e[4] || e[5] || "").replace(we, Te), "~=" === e[2] && (e[3] = " " + e[3] + " "), e.slice(0, 4) }, CHILD: function(e) { return e[1] = e[1].toLowerCase(), "nth" === e[1].slice(0, 3) ? (e[3] || t.error(e[0]), e[4] = +(e[4] ? e[5] + (e[6] || 1) : 2 * ("even" === e[3] || "odd" === e[3])), e[5] = +(e[7] + e[8] || "odd" === e[3])) : e[3] && t.error(e[0]), e }, PSEUDO: function(e) { var t, n = !e[6] && e[2]; return he.CHILD.test(e[0]) ? null : (e[3] ? e[2] = e[4] || e[5] || "" : n && de.test(n) && (t = N(n, !0)) && (t = n.indexOf(")", n.length - t) - n.length) && (e[0] = e[0].slice(0, t), e[2] = n.slice(0, t)), e.slice(0, 3)) } }, filter: { TAG: function(e) { var t = e.replace(we, Te).toLowerCase(); return "*" === e ? function() { return !0 } : function(e) { return e.nodeName && e.nodeName.toLowerCase() === t } }, CLASS: function(e) { var t = _[e + " "]; return t || (t = new RegExp("(^|" + ne + ")" + e + "(" + ne + "|$)")) && _(e, function(e) { return t.test("string" == typeof e.className && e.className || "undefined" != typeof e.getAttribute && e.getAttribute("class") || "") }) }, ATTR: function(e, n, r) { return function(i) { var o = t.attr(i, e); return null == o ? "!=" === n : !n || (o += "", "=" === n ? o === r : "!=" === n ? o !== r : "^=" === n ? r && 0 === o.indexOf(r) : "*=" === n ? r && o.indexOf(r) > -1 : "$=" === n ? r && o.slice(-r.length) === r : "~=" === n ? (" " + o.replace(ae, " ") + " ").indexOf(r) > -1 : "|=" === n && (o === r || o.slice(0, r.length + 1) === r + "-")) } }, CHILD: function(e, t, n, r, i) { var o = "nth" !== e.slice(0, 3), s = "last" !== e.slice(-4), a = "of-type" === t; return 1 === r && 0 === i ? function(e) { return !!e.parentNode } : function(t, n, u) { var l, c, f, d, p, h, g = o !== s ? "nextSibling" : "previousSibling", m = t.parentNode, v = a && t.nodeName.toLowerCase(), y = !u && !a; if (m) { if (o) { for (; g;) { for (f = t; f = f[g];) if (a ? f.nodeName.toLowerCase() === v : 1 === f.nodeType) return !1; h = g = "only" === e && !h && "nextSibling" } return !0 } if (h = [s ? m.firstChild : m.lastChild], s && y) { for (c = m[W] || (m[W] = {}), l = c[e] || [], p = l[0] === $ && l[1], d = l[0] === $ && l[2], f = p && m.childNodes[p]; f = ++p && f && f[g] || (d = p = 0) || h.pop();) if (1 === f.nodeType && ++d && f === t) { c[e] = [$, p, d]; break } } else if (y && (l = (t[W] || (t[W] = {}))[e]) && l[0] === $) d = l[1]; else for (; (f = ++p && f && f[g] || (d = p = 0) || h.pop()) && ((a ? f.nodeName.toLowerCase() !== v : 1 !== f.nodeType) || !++d || (y && ((f[W] || (f[W] = {}))[e] = [$, d]), f !== t));); return d -= i, d === r || d % r === 0 && d / r >= 0 } } }, PSEUDO: function(e, n) { var i, o = T.pseudos[e] || T.setFilters[e.toLowerCase()] || t.error("unsupported pseudo: " + e); return o[W] ? o(n) : o.length > 1 ? (i = [e, e, "", n], T.setFilters.hasOwnProperty(e.toLowerCase()) ? r(function(e, t) { for (var r, i = o(e, n), s = i.length; s--;) r = ee(e, i[s]), e[r] = !(t[r] = i[s]) }) : function(e) { return o(e, 0, i) }) : o } }, pseudos: { not: r(function(e) { var t = [], n = [], i = E(e.replace(ue, "$1")); return i[W] ? r(function(e, t, n, r) { for (var o, s = i(e, null, r, []), a = e.length; a--;)(o = s[a]) && (e[a] = !(t[a] = o)) }) : function(e, r, o) { return t[0] = e, i(t, null, o, n), t[0] = null, !n.pop() } }), has: r(function(e) { return function(n) { return t(e, n).length > 0 } }), contains: r(function(e) { return e = e.replace(we, Te), function(t) { return (t.textContent || t.innerText || C(t)).indexOf(e) > -1 } }), lang: r(function(e) { return pe.test(e || "") || t.error("unsupported lang: " + e), e = e.replace(we, Te).toLowerCase(), function(t) { var n; do if (n = O ? t.lang : t.getAttribute("xml:lang") || t.getAttribute("lang")) return n = n.toLowerCase(), n === e || 0 === n.indexOf(e + "-"); while ((t = t.parentNode) && 1 === t.nodeType); return !1 } }), target: function(t) { var n = e.location && e.location.hash; return n && n.slice(1) === t.id }, root: function(e) { return e === H }, focus: function(e) { return e === q.activeElement && (!q.hasFocus || q.hasFocus()) && !!(e.type || e.href || ~e.tabIndex) }, enabled: function(e) { return e.disabled === !1 }, disabled: function(e) { return e.disabled === !0 }, checked: function(e) { var t = e.nodeName.toLowerCase(); return "input" === t && !!e.checked || "option" === t && !!e.selected }, selected: function(e) { return e.parentNode && e.parentNode.selectedIndex, e.selected === !0 }, empty: function(e) { for (e = e.firstChild; e; e = e.nextSibling) if (e.nodeType < 6) return !1; return !0 }, parent: function(e) { return !T.pseudos.empty(e) }, header: function(e) { return me.test(e.nodeName) }, input: function(e) { return ge.test(e.nodeName) }, button: function(e) { var t = e.nodeName.toLowerCase(); return "input" === t && "button" === e.type || "button" === t }, text: function(e) { var t; return "input" === e.nodeName.toLowerCase() && "text" === e.type && (null == (t = e.getAttribute("type")) || "text" === t.toLowerCase()) }, first: l(function() { return [0] }), last: l(function(e, t) { return [t - 1] }), eq: l(function(e, t, n) { return [0 > n ? n + t : n] }), even: l(function(e, t) { for (var n = 0; t > n; n += 2) e.push(n); return e }), odd: l(function(e, t) { for (var n = 1; t > n; n += 2) e.push(n); return e }), lt: l(function(e, t, n) { for (var r = 0 > n ? n + t : n; --r >= 0;) e.push(r); return e }), gt: l(function(e, t, n) { for (var r = 0 > n ? n + t : n; ++r < t;) e.push(r); return e }) } }, T.pseudos.nth = T.pseudos.eq; for (b in { radio: !0, checkbox: !0, file: !0, password: !0, image: !0 }) T.pseudos[b] = a(b); for (b in { submit: !0, reset: !0 }) T.pseudos[b] = u(b); return f.prototype = T.filters = T.pseudos, T.setFilters = new f, N = t.tokenize = function(e, n) { var r, i, o, s, a, u, l, c = z[e + " "]; if (c) return n ? 0 : c.slice(0); for (a = e, u = [], l = T.preFilter; a;) { (!r || (i = le.exec(a))) && (i && (a = a.slice(i[0].length) || a), u.push(o = [])), r = !1, (i = ce.exec(a)) && (r = i.shift(), o.push({ value: r, type: i[0].replace(ue, " ") }), a = a.slice(r.length)); for (s in T.filter) !(i = he[s].exec(a)) || l[s] && !(i = l[s](i)) || (r = i.shift(), o.push({ value: r, type: s, matches: i }), a = a.slice(r.length)); if (!r) break } return n ? a.length : a ? t.error(e) : z(e, u).slice(0) }, E = t.compile = function(e, t) { var n, r = [], i = [], o = X[e + " "]; if (!o) { for (t || (t = N(e)), n = t.length; n--;) o = y(t[n]), o[W] ? r.push(o) : i.push(o); o = X(e, x(i, r)), o.selector = e } return o }, j = t.select = function(e, t, n, r) { var i, o, s, a, u, l = "function" == typeof e && e, f = !r && N(e = l.selector || e); if (n = n || [], 1 === f.length) { if (o = f[0] = f[0].slice(0), o.length > 2 && "ID" === (s = o[0]).type && w.getById && 9 === t.nodeType && O && T.relative[o[1].type]) { if (t = (T.find.ID(s.matches[0].replace(we, Te), t) || [])[0], !t) return n; l && (t = t.parentNode), e = e.slice(o.shift().value.length) } for (i = he.needsContext.test(e) ? 0 : o.length; i-- && (s = o[i], !T.relative[a = s.type]);) if ((u = T.find[a]) && (r = u(s.matches[0].replace(we, Te), xe.test(o[0].type) && c(t.parentNode) || t))) { if (o.splice(i, 1), e = r.length && d(o), !e) return K.apply(n, r), n; break } } return (l || E(e, f))(r, t, !O, n, xe.test(e) && c(t.parentNode) || t), n }, w.sortStable = W.split("").sort(V).join("") === W, w.detectDuplicates = !!A, L(), w.sortDetached = i(function(e) { return 1 & e.compareDocumentPosition(q.createElement("div")) }), i(function(e) { return e.innerHTML = "<a href='#'></a>", "#" === e.firstChild.getAttribute("href") }) || o("type|href|height|width", function(e, t, n) { return n ? void 0 : e.getAttribute(t, "type" === t.toLowerCase() ? 1 : 2) }), w.attributes && i(function(e) { return e.innerHTML = "<input/>", e.firstChild.setAttribute("value", ""), "" === e.firstChild.getAttribute("value") }) || o("value", function(e, t, n) { return n || "input" !== e.nodeName.toLowerCase() ? void 0 : e.defaultValue }), i(function(e) { return null == e.getAttribute("disabled") }) || o(te, function(e, t, n) { var r; return n ? void 0 : e[t] === !0 ? t.toLowerCase() : (r = e.getAttributeNode(t)) && r.specified ? r.value : null }), t }(e); Z.find = ie, Z.expr = ie.selectors, Z.expr[":"] = Z.expr.pseudos, Z.unique = ie.uniqueSort, Z.text = ie.getText, Z.isXMLDoc = ie.isXML, Z.contains = ie.contains; var oe = Z.expr.match.needsContext, se = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, ae = /^.[^:#\[\.,]*$/; Z.filter = function(e, t, n) { var r = t[0]; return n && (e = ":not(" + e + ")"), 1 === t.length && 1 === r.nodeType ? Z.find.matchesSelector(r, e) ? [r] : [] : Z.find.matches(e, Z.grep(t, function(e) { return 1 === e.nodeType })) }, Z.fn.extend({ find: function(e) { var t, n = this.length, r = [], i = this; if ("string" != typeof e) return this.pushStack(Z(e).filter(function() { for (t = 0; n > t; t++) if (Z.contains(i[t], this)) return !0 })); for (t = 0; n > t; t++) Z.find(e, i[t], r); return r = this.pushStack(n > 1 ? Z.unique(r) : r), r.selector = this.selector ? this.selector + " " + e : e, r }, filter: function(e) { return this.pushStack(r(this, e || [], !1)) }, not: function(e) { return this.pushStack(r(this, e || [], !0)) }, is: function(e) { return !!r(this, "string" == typeof e && oe.test(e) ? Z(e) : e || [], !1).length } }); var ue, le = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, ce = Z.fn.init = function(e, t) { var n, r; if (!e) return this; if ("string" == typeof e) { if (n = "<" === e[0] && ">" === e[e.length - 1] && e.length >= 3 ? [null, e, null] : le.exec(e), !n || !n[1] && t) return !t || t.jquery ? (t || ue).find(e) : this.constructor(t).find(e); if (n[1]) { if (t = t instanceof Z ? t[0] : t, Z.merge(this, Z.parseHTML(n[1], t && t.nodeType ? t.ownerDocument || t : J, !0)), se.test(n[1]) && Z.isPlainObject(t)) for (n in t) Z.isFunction(this[n]) ? this[n](t[n]) : this.attr(n, t[n]); return this } return r = J.getElementById(n[2]), r && r.parentNode && (this.length = 1, this[0] = r), this.context = J, this.selector = e, this } return e.nodeType ? (this.context = this[0] = e, this.length = 1, this) : Z.isFunction(e) ? "undefined" != typeof ue.ready ? ue.ready(e) : e(Z) : (void 0 !== e.selector && (this.selector = e.selector, this.context = e.context), Z.makeArray(e, this)) }; ce.prototype = Z.fn, ue = Z(J); var fe = /^(?:parents|prev(?:Until|All))/, de = { children: !0, contents: !0, next: !0, prev: !0 }; Z.extend({ dir: function(e, t, n) { for (var r = [], i = void 0 !== n; (e = e[t]) && 9 !== e.nodeType;) if (1 === e.nodeType) { if (i && Z(e).is(n)) break; r.push(e) } return r }, sibling: function(e, t) { for (var n = []; e; e = e.nextSibling) 1 === e.nodeType && e !== t && n.push(e); return n } }), Z.fn.extend({ has: function(e) { var t = Z(e, this), n = t.length; return this.filter(function() { for (var e = 0; n > e; e++) if (Z.contains(this, t[e])) return !0 }) }, closest: function(e, t) { for (var n, r = 0, i = this.length, o = [], s = oe.test(e) || "string" != typeof e ? Z(e, t || this.context) : 0; i > r; r++) for (n = this[r]; n && n !== t; n = n.parentNode) if (n.nodeType < 11 && (s ? s.index(n) > -1 : 1 === n.nodeType && Z.find.matchesSelector(n, e))) { o.push(n); break } return this.pushStack(o.length > 1 ? Z.unique(o) : o) }, index: function(e) { return e ? "string" == typeof e ? V.call(Z(e), this[0]) : V.call(this, e.jquery ? e[0] : e) : this[0] && this[0].parentNode ? this.first().prevAll().length : -1 }, add: function(e, t) { return this.pushStack(Z.unique(Z.merge(this.get(), Z(e, t)))) }, addBack: function(e) { return this.add(null == e ? this.prevObject : this.prevObject.filter(e)) } }), Z.each({ parent: function(e) { var t = e.parentNode; return t && 11 !== t.nodeType ? t : null }, parents: function(e) { return Z.dir(e, "parentNode") }, parentsUntil: function(e, t, n) { return Z.dir(e, "parentNode", n) }, next: function(e) { return i(e, "nextSibling") }, prev: function(e) { return i(e, "previousSibling") }, nextAll: function(e) { return Z.dir(e, "nextSibling") }, prevAll: function(e) { return Z.dir(e, "previousSibling") }, nextUntil: function(e, t, n) { return Z.dir(e, "nextSibling", n) }, prevUntil: function(e, t, n) { return Z.dir(e, "previousSibling", n) }, siblings: function(e) { return Z.sibling((e.parentNode || {}).firstChild, e) }, children: function(e) { return Z.sibling(e.firstChild) }, contents: function(e) { return e.contentDocument || Z.merge([], e.childNodes) } }, function(e, t) { Z.fn[e] = function(n, r) { var i = Z.map(this, t, n); return "Until" !== e.slice(-5) && (r = n), r && "string" == typeof r && (i = Z.filter(r, i)), this.length > 1 && (de[e] || Z.unique(i), fe.test(e) && i.reverse()), this.pushStack(i) } }); var pe = /\S+/g, he = {}; Z.Callbacks = function(e) { e = "string" == typeof e ? he[e] || o(e) : Z.extend({}, e); var t, n, r, i, s, a, u = [], l = !e.once && [], c = function(o) { for (t = e.memory && o, n = !0, a = i || 0, i = 0, s = u.length, r = !0; u && s > a; a++) if (u[a].apply(o[0], o[1]) === !1 && e.stopOnFalse) { t = !1; break } r = !1, u && (l ? l.length && c(l.shift()) : t ? u = [] : f.disable()) }, f = { add: function() { if (u) { var n = u.length; ! function o(t) { Z.each(t, function(t, n) { var r = Z.type(n); "function" === r ? e.unique && f.has(n) || u.push(n) : n && n.length && "string" !== r && o(n) }) }(arguments), r ? s = u.length : t && (i = n, c(t)) } return this }, remove: function() { return u && Z.each(arguments, function(e, t) { for (var n; (n = Z.inArray(t, u, n)) > -1;) u.splice(n, 1), r && (s >= n && s--, a >= n && a--) }), this }, has: function(e) { return e ? Z.inArray(e, u) > -1 : !(!u || !u.length) }, empty: function() { return u = [], s = 0, this }, disable: function() { return u = l = t = void 0, this }, disabled: function() { return !u }, lock: function() { return l = void 0, t || f.disable(), this }, locked: function() { return !l }, fireWith: function(e, t) { return !u || n && !l || (t = t || [], t = [e, t.slice ? t.slice() : t], r ? l.push(t) : c(t)), this }, fire: function() { return f.fireWith(this, arguments), this }, fired: function() { return !!n } }; return f }, Z.extend({ Deferred: function(e) { var t = [ ["resolve", "done", Z.Callbacks("once memory"), "resolved"], ["reject", "fail", Z.Callbacks("once memory"), "rejected"], ["notify", "progress", Z.Callbacks("memory")] ], n = "pending", r = { state: function() { return n }, always: function() { return i.done(arguments).fail(arguments), this }, then: function() { var e = arguments; return Z.Deferred(function(n) { Z.each(t, function(t, o) { var s = Z.isFunction(e[t]) && e[t]; i[o[1]](function() { var e = s && s.apply(this, arguments); e && Z.isFunction(e.promise) ? e.promise().done(n.resolve).fail(n.reject).progress(n.notify) : n[o[0] + "With"](this === r ? n.promise() : this, s ? [e] : arguments) }) }), e = null }).promise() }, promise: function(e) { return null != e ? Z.extend(e, r) : r } }, i = {}; return r.pipe = r.then, Z.each(t, function(e, o) { var s = o[2], a = o[3]; r[o[1]] = s.add, a && s.add(function() { n = a }, t[1 ^ e][2].disable, t[2][2].lock), i[o[0]] = function() { return i[o[0] + "With"](this === i ? r : this, arguments), this }, i[o[0] + "With"] = s.fireWith }), r.promise(i), e && e.call(i, i), i }, when: function(e) { var t, n, r, i = 0, o = _.call(arguments), s = o.length, a = 1 !== s || e && Z.isFunction(e.promise) ? s : 0, u = 1 === a ? e : Z.Deferred(), l = function(e, n, r) { return function(i) { n[e] = this, r[e] = arguments.length > 1 ? _.call(arguments) : i, r === t ? u.notifyWith(n, r) : --a || u.resolveWith(n, r) } }; if (s > 1) for (t = new Array(s), n = new Array(s), r = new Array(s); s > i; i++) o[i] && Z.isFunction(o[i].promise) ? o[i].promise().done(l(i, r, o)).fail(u.reject).progress(l(i, n, t)) : --a; return a || u.resolveWith(r, o), u.promise() } }); var ge; Z.fn.ready = function(e) { return Z.ready.promise().done(e), this }, Z.extend({ isReady: !1, readyWait: 1, holdReady: function(e) { e ? Z.readyWait++ : Z.ready(!0) }, ready: function(e) { (e === !0 ? --Z.readyWait : Z.isReady) || (Z.isReady = !0, e !== !0 && --Z.readyWait > 0 || (ge.resolveWith(J, [Z]), Z.fn.triggerHandler && (Z(J).triggerHandler("ready"), Z(J).off("ready")))) } }), Z.ready.promise = function(t) { return ge || (ge = Z.Deferred(), "complete" === J.readyState ? setTimeout(Z.ready) : (J.addEventListener("DOMContentLoaded", s, !1), e.addEventListener("load", s, !1))), ge.promise(t) }, Z.ready.promise(); var me = Z.access = function(e, t, n, r, i, o, s) { var a = 0, u = e.length, l = null == n; if ("object" === Z.type(n)) { i = !0; for (a in n) Z.access(e, t, a, n[a], !0, o, s) } else if (void 0 !== r && (i = !0, Z.isFunction(r) || (s = !0), l && (s ? (t.call(e, r), t = null) : (l = t, t = function(e, t, n) { return l.call(Z(e), n) })), t)) for (; u > a; a++) t(e[a], n, s ? r : r.call(e[a], a, t(e[a], n))); return i ? e : l ? t.call(e) : u ? t(e[0], n) : o }; Z.acceptData = function(e) { return 1 === e.nodeType || 9 === e.nodeType || !+e.nodeType }, a.uid = 1, a.accepts = Z.acceptData, a.prototype = { key: function(e) { if (!a.accepts(e)) return 0; var t = {}, n = e[this.expando]; if (!n) { n = a.uid++; try { t[this.expando] = { value: n }, Object.defineProperties(e, t) } catch (r) { t[this.expando] = n, Z.extend(e, t) } } return this.cache[n] || (this.cache[n] = {}), n }, set: function(e, t, n) { var r, i = this.key(e), o = this.cache[i]; if ("string" == typeof t) o[t] = n; else if (Z.isEmptyObject(o)) Z.extend(this.cache[i], t); else for (r in t) o[r] = t[r]; return o }, get: function(e, t) { var n = this.cache[this.key(e)]; return void 0 === t ? n : n[t] }, access: function(e, t, n) { var r; return void 0 === t || t && "string" == typeof t && void 0 === n ? (r = this.get(e, t), void 0 !== r ? r : this.get(e, Z.camelCase(t))) : (this.set(e, t, n), void 0 !== n ? n : t) }, remove: function(e, t) { var n, r, i, o = this.key(e), s = this.cache[o]; if (void 0 === t) this.cache[o] = {}; else { Z.isArray(t) ? r = t.concat(t.map(Z.camelCase)) : (i = Z.camelCase(t), t in s ? r = [t, i] : (r = i, r = r in s ? [r] : r.match(pe) || [])), n = r.length; for (; n--;) delete s[r[n]] } }, hasData: function(e) { return !Z.isEmptyObject(this.cache[e[this.expando]] || {}) }, discard: function(e) { e[this.expando] && delete this.cache[e[this.expando]] } }; var ve = new a, ye = new a, xe = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, be = /([A-Z])/g; Z.extend({ hasData: function(e) { return ye.hasData(e) || ve.hasData(e) }, data: function(e, t, n) { return ye.access(e, t, n) }, removeData: function(e, t) { ye.remove(e, t) }, _data: function(e, t, n) { return ve.access(e, t, n) }, _removeData: function(e, t) { ve.remove(e, t) } }), Z.fn.extend({ data: function(e, t) { var n, r, i, o = this[0], s = o && o.attributes; if (void 0 === e) { if (this.length && (i = ye.get(o), 1 === o.nodeType && !ve.get(o, "hasDataAttrs"))) { for (n = s.length; n--;) s[n] && (r = s[n].name, 0 === r.indexOf("data-") && (r = Z.camelCase(r.slice(5)), u(o, r, i[r]))); ve.set(o, "hasDataAttrs", !0) } return i } return "object" == typeof e ? this.each(function() { ye.set(this, e) }) : me(this, function(t) { var n, r = Z.camelCase(e); if (o && void 0 === t) { if (n = ye.get(o, e), void 0 !== n) return n; if (n = ye.get(o, r), void 0 !== n) return n; if (n = u(o, r, void 0), void 0 !== n) return n } else this.each(function() { var n = ye.get(this, r); ye.set(this, r, t), -1 !== e.indexOf("-") && void 0 !== n && ye.set(this, e, t) }) }, null, t, arguments.length > 1, null, !0) }, removeData: function(e) { return this.each(function() { ye.remove(this, e) }) } }), Z.extend({ queue: function(e, t, n) { var r; return e ? (t = (t || "fx") + "queue", r = ve.get(e, t), n && (!r || Z.isArray(n) ? r = ve.access(e, t, Z.makeArray(n)) : r.push(n)), r || []) : void 0 }, dequeue: function(e, t) { t = t || "fx"; var n = Z.queue(e, t), r = n.length, i = n.shift(), o = Z._queueHooks(e, t), s = function() { Z.dequeue(e, t) }; "inprogress" === i && (i = n.shift(), r--), i && ("fx" === t && n.unshift("inprogress"), delete o.stop, i.call(e, s, o)), !r && o && o.empty.fire() }, _queueHooks: function(e, t) { var n = t + "queueHooks"; return ve.get(e, n) || ve.access(e, n, { empty: Z.Callbacks("once memory").add(function() { ve.remove(e, [t + "queue", n]) }) }) } }), Z.fn.extend({ queue: function(e, t) { var n = 2; return "string" != typeof e && (t = e, e = "fx", n--), arguments.length < n ? Z.queue(this[0], e) : void 0 === t ? this : this.each(function() { var n = Z.queue(this, e, t); Z._queueHooks(this, e), "fx" === e && "inprogress" !== n[0] && Z.dequeue(this, e) }) }, dequeue: function(e) { return this.each(function() { Z.dequeue(this, e) }) }, clearQueue: function(e) { return this.queue(e || "fx", []) }, promise: function(e, t) { var n, r = 1, i = Z.Deferred(), o = this, s = this.length, a = function() { --r || i.resolveWith(o, [o]) }; for ("string" != typeof e && (t = e, e = void 0), e = e || "fx"; s--;) n = ve.get(o[s], e + "queueHooks"), n && n.empty && (r++, n.empty.add(a)); return a(), i.promise(t) } }); var we = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, Te = ["Top", "Right", "Bottom", "Left"], Ce = function(e, t) { return e = t || e, "none" === Z.css(e, "display") || !Z.contains(e.ownerDocument, e) }, ke = /^(?:checkbox|radio)$/i; ! function() { var e = J.createDocumentFragment(), t = e.appendChild(J.createElement("div")), n = J.createElement("input"); n.setAttribute("type", "radio"), n.setAttribute("checked", "checked"), n.setAttribute("name", "t"), t.appendChild(n), Q.checkClone = t.cloneNode(!0).cloneNode(!0).lastChild.checked, t.innerHTML = "<textarea>x</textarea>", Q.noCloneChecked = !!t.cloneNode(!0).lastChild.defaultValue }(); var Ne = "undefined"; Q.focusinBubbles = "onfocusin" in e; var Ee = /^key/, je = /^(?:mouse|pointer|contextmenu)|click/, Se = /^(?:focusinfocus|focusoutblur)$/, De = /^([^.]*)(?:\.(.+)|)$/; Z.event = { global: {}, add: function(e, t, n, r, i) { var o, s, a, u, l, c, f, d, p, h, g, m = ve.get(e); if (m) for (n.handler && (o = n, n = o.handler, i = o.selector), n.guid || (n.guid = Z.guid++), (u = m.events) || (u = m.events = {}), (s = m.handle) || (s = m.handle = function(t) { return typeof Z !== Ne && Z.event.triggered !== t.type ? Z.event.dispatch.apply(e, arguments) : void 0 }), t = (t || "").match(pe) || [""], l = t.length; l--;) a = De.exec(t[l]) || [], p = g = a[1], h = (a[2] || "").split(".").sort(), p && (f = Z.event.special[p] || {}, p = (i ? f.delegateType : f.bindType) || p, f = Z.event.special[p] || {}, c = Z.extend({ type: p, origType: g, data: r, handler: n, guid: n.guid, selector: i, needsContext: i && Z.expr.match.needsContext.test(i), namespace: h.join(".") }, o), (d = u[p]) || (d = u[p] = [], d.delegateCount = 0, f.setup && f.setup.call(e, r, h, s) !== !1 || e.addEventListener && e.addEventListener(p, s, !1)), f.add && (f.add.call(e, c), c.handler.guid || (c.handler.guid = n.guid)), i ? d.splice(d.delegateCount++, 0, c) : d.push(c), Z.event.global[p] = !0) }, remove: function(e, t, n, r, i) { var o, s, a, u, l, c, f, d, p, h, g, m = ve.hasData(e) && ve.get(e); if (m && (u = m.events)) { for (t = (t || "").match(pe) || [""], l = t.length; l--;) if (a = De.exec(t[l]) || [], p = g = a[1], h = (a[2] || "").split(".").sort(), p) { for (f = Z.event.special[p] || {}, p = (r ? f.delegateType : f.bindType) || p, d = u[p] || [], a = a[2] && new RegExp("(^|\\.)" + h.join("\\.(?:.*\\.|)") + "(\\.|$)"), s = o = d.length; o--;) c = d[o], !i && g !== c.origType || n && n.guid !== c.guid || a && !a.test(c.namespace) || r && r !== c.selector && ("**" !== r || !c.selector) || (d.splice(o, 1), c.selector && d.delegateCount--, f.remove && f.remove.call(e, c)); s && !d.length && (f.teardown && f.teardown.call(e, h, m.handle) !== !1 || Z.removeEvent(e, p, m.handle), delete u[p]) } else for (p in u) Z.event.remove(e, p + t[l], n, r, !0); Z.isEmptyObject(u) && (delete m.handle, ve.remove(e, "events")) } }, trigger: function(t, n, r, i) { var o, s, a, u, l, c, f, d = [r || J], p = G.call(t, "type") ? t.type : t, h = G.call(t, "namespace") ? t.namespace.split(".") : []; if (s = a = r = r || J, 3 !== r.nodeType && 8 !== r.nodeType && !Se.test(p + Z.event.triggered) && (p.indexOf(".") >= 0 && (h = p.split("."), p = h.shift(), h.sort()), l = p.indexOf(":") < 0 && "on" + p, t = t[Z.expando] ? t : new Z.Event(p, "object" == typeof t && t), t.isTrigger = i ? 2 : 3, t.namespace = h.join("."), t.namespace_re = t.namespace ? new RegExp("(^|\\.)" + h.join("\\.(?:.*\\.|)") + "(\\.|$)") : null, t.result = void 0, t.target || (t.target = r), n = null == n ? [t] : Z.makeArray(n, [t]), f = Z.event.special[p] || {}, i || !f.trigger || f.trigger.apply(r, n) !== !1)) { if (!i && !f.noBubble && !Z.isWindow(r)) { for (u = f.delegateType || p, Se.test(u + p) || (s = s.parentNode); s; s = s.parentNode) d.push(s), a = s; a === (r.ownerDocument || J) && d.push(a.defaultView || a.parentWindow || e) } for (o = 0; (s = d[o++]) && !t.isPropagationStopped();) t.type = o > 1 ? u : f.bindType || p, c = (ve.get(s, "events") || {})[t.type] && ve.get(s, "handle"), c && c.apply(s, n), c = l && s[l], c && c.apply && Z.acceptData(s) && (t.result = c.apply(s, n), t.result === !1 && t.preventDefault()); return t.type = p, i || t.isDefaultPrevented() || f._default && f._default.apply(d.pop(), n) !== !1 || !Z.acceptData(r) || l && Z.isFunction(r[p]) && !Z.isWindow(r) && (a = r[l], a && (r[l] = null), Z.event.triggered = p, r[p](), Z.event.triggered = void 0, a && (r[l] = a)), t.result } }, dispatch: function(e) { e = Z.event.fix(e); var t, n, r, i, o, s = [], a = _.call(arguments), u = (ve.get(this, "events") || {})[e.type] || [], l = Z.event.special[e.type] || {}; if (a[0] = e, e.delegateTarget = this, !l.preDispatch || l.preDispatch.call(this, e) !== !1) { for (s = Z.event.handlers.call(this, e, u), t = 0; (i = s[t++]) && !e.isPropagationStopped();) for (e.currentTarget = i.elem, n = 0; (o = i.handlers[n++]) && !e.isImmediatePropagationStopped();)(!e.namespace_re || e.namespace_re.test(o.namespace)) && (e.handleObj = o, e.data = o.data, r = ((Z.event.special[o.origType] || {}).handle || o.handler).apply(i.elem, a), void 0 !== r && (e.result = r) === !1 && (e.preventDefault(), e.stopPropagation())); return l.postDispatch && l.postDispatch.call(this, e), e.result } }, handlers: function(e, t) { var n, r, i, o, s = [], a = t.delegateCount, u = e.target; if (a && u.nodeType && (!e.button || "click" !== e.type)) for (; u !== this; u = u.parentNode || this) if (u.disabled !== !0 || "click" !== e.type) { for (r = [], n = 0; a > n; n++) o = t[n], i = o.selector + " ", void 0 === r[i] && (r[i] = o.needsContext ? Z(i, this).index(u) >= 0 : Z.find(i, this, null, [u]).length), r[i] && r.push(o); r.length && s.push({ elem: u, handlers: r }) } return a < t.length && s.push({ elem: this, handlers: t.slice(a) }), s }, props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function(e, t) { return null == e.which && (e.which = null != t.charCode ? t.charCode : t.keyCode), e } }, mouseHooks: { props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function(e, t) { var n, r, i, o = t.button; return null == e.pageX && null != t.clientX && (n = e.target.ownerDocument || J, r = n.documentElement, i = n.body, e.pageX = t.clientX + (r && r.scrollLeft || i && i.scrollLeft || 0) - (r && r.clientLeft || i && i.clientLeft || 0), e.pageY = t.clientY + (r && r.scrollTop || i && i.scrollTop || 0) - (r && r.clientTop || i && i.clientTop || 0)), e.which || void 0 === o || (e.which = 1 & o ? 1 : 2 & o ? 3 : 4 & o ? 2 : 0), e } }, fix: function(e) { if (e[Z.expando]) return e; var t, n, r, i = e.type, o = e, s = this.fixHooks[i]; for (s || (this.fixHooks[i] = s = je.test(i) ? this.mouseHooks : Ee.test(i) ? this.keyHooks : {}), r = s.props ? this.props.concat(s.props) : this.props, e = new Z.Event(o), t = r.length; t--;) n = r[t], e[n] = o[n]; return e.target || (e.target = J), 3 === e.target.nodeType && (e.target = e.target.parentNode), s.filter ? s.filter(e, o) : e }, special: { load: { noBubble: !0 }, focus: { trigger: function() { return this !== f() && this.focus ? (this.focus(), !1) : void 0 }, delegateType: "focusin" }, blur: { trigger: function() { return this === f() && this.blur ? (this.blur(), !1) : void 0 }, delegateType: "focusout" }, click: { trigger: function() { return "checkbox" === this.type && this.click && Z.nodeName(this, "input") ? (this.click(), !1) : void 0 }, _default: function(e) { return Z.nodeName(e.target, "a") } }, beforeunload: { postDispatch: function(e) { void 0 !== e.result && e.originalEvent && (e.originalEvent.returnValue = e.result) } } }, simulate: function(e, t, n, r) { var i = Z.extend(new Z.Event, n, { type: e, isSimulated: !0, originalEvent: {} }); r ? Z.event.trigger(i, null, t) : Z.event.dispatch.call(t, i), i.isDefaultPrevented() && n.preventDefault() } }, Z.removeEvent = function(e, t, n) { e.removeEventListener && e.removeEventListener(t, n, !1) }, Z.Event = function(e, t) { return this instanceof Z.Event ? (e && e.type ? (this.originalEvent = e, this.type = e.type, this.isDefaultPrevented = e.defaultPrevented || void 0 === e.defaultPrevented && e.returnValue === !1 ? l : c) : this.type = e, t && Z.extend(this, t), this.timeStamp = e && e.timeStamp || Z.now(), void(this[Z.expando] = !0)) : new Z.Event(e, t) }, Z.Event.prototype = { isDefaultPrevented: c, isPropagationStopped: c, isImmediatePropagationStopped: c, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = l, e && e.preventDefault && e.preventDefault() }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = l, e && e.stopPropagation && e.stopPropagation() }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = l, e && e.stopImmediatePropagation && e.stopImmediatePropagation(), this.stopPropagation() } }, Z.each({ mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function(e, t) { Z.event.special[e] = { delegateType: t, bindType: t, handle: function(e) { var n, r = this, i = e.relatedTarget, o = e.handleObj; return (!i || i !== r && !Z.contains(r, i)) && (e.type = o.origType, n = o.handler.apply(this, arguments), e.type = t), n } } }), Q.focusinBubbles || Z.each({ focus: "focusin", blur: "focusout" }, function(e, t) { var n = function(e) { Z.event.simulate(t, e.target, Z.event.fix(e), !0) }; Z.event.special[t] = { setup: function() { var r = this.ownerDocument || this, i = ve.access(r, t); i || r.addEventListener(e, n, !0), ve.access(r, t, (i || 0) + 1) }, teardown: function() { var r = this.ownerDocument || this, i = ve.access(r, t) - 1; i ? ve.access(r, t, i) : (r.removeEventListener(e, n, !0), ve.remove(r, t)) } } }), Z.fn.extend({ on: function(e, t, n, r, i) { var o, s; if ("object" == typeof e) { "string" != typeof t && (n = n || t, t = void 0); for (s in e) this.on(s, t, n, e[s], i); return this } if (null == n && null == r ? (r = t, n = t = void 0) : null == r && ("string" == typeof t ? (r = n, n = void 0) : (r = n, n = t, t = void 0)), r === !1) r = c; else if (!r) return this; return 1 === i && (o = r, r = function(e) { return Z().off(e), o.apply(this, arguments) }, r.guid = o.guid || (o.guid = Z.guid++)), this.each(function() { Z.event.add(this, e, r, n, t) }) }, one: function(e, t, n, r) { return this.on(e, t, n, r, 1) }, off: function(e, t, n) { var r, i; if (e && e.preventDefault && e.handleObj) return r = e.handleObj, Z(e.delegateTarget).off(r.namespace ? r.origType + "." + r.namespace : r.origType, r.selector, r.handler), this; if ("object" == typeof e) { for (i in e) this.off(i, t, e[i]); return this } return (t === !1 || "function" == typeof t) && (n = t, t = void 0), n === !1 && (n = c), this.each(function() { Z.event.remove(this, e, n, t) }) }, trigger: function(e, t) { return this.each(function() { Z.event.trigger(e, t, this) }) }, triggerHandler: function(e, t) { var n = this[0]; return n ? Z.event.trigger(e, t, n, !0) : void 0 } }); var Ae = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, Le = /<([\w:]+)/, qe = /<|&#?\w+;/, He = /<(?:script|style|link)/i, Oe = /checked\s*(?:[^=]|=\s*.checked.)/i, Fe = /^$|\/(?:java|ecma)script/i, Pe = /^true\/(.*)/, Me = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, Re = { option: [1, "<select multiple='multiple'>", "</select>"], thead: [1, "<table>", "</table>"], col: [2, "<table><colgroup>", "</colgroup></table>"], tr: [2, "<table><tbody>", "</tbody></table>"], td: [3, "<table><tbody><tr>", "</tr></tbody></table>"], _default: [0, "", ""] }; Re.optgroup = Re.option, Re.tbody = Re.tfoot = Re.colgroup = Re.caption = Re.thead, Re.th = Re.td, Z.extend({ clone: function(e, t, n) { var r, i, o, s, a = e.cloneNode(!0), u = Z.contains(e.ownerDocument, e); if (!(Q.noCloneChecked || 1 !== e.nodeType && 11 !== e.nodeType || Z.isXMLDoc(e))) for (s = v(a), o = v(e), r = 0, i = o.length; i > r; r++) y(o[r], s[r]); if (t) if (n) for (o = o || v(e), s = s || v(a), r = 0, i = o.length; i > r; r++) m(o[r], s[r]); else m(e, a); return s = v(a, "script"), s.length > 0 && g(s, !u && v(e, "script")), a }, buildFragment: function(e, t, n, r) { for (var i, o, s, a, u, l, c = t.createDocumentFragment(), f = [], d = 0, p = e.length; p > d; d++) if (i = e[d], i || 0 === i) if ("object" === Z.type(i)) Z.merge(f, i.nodeType ? [i] : i); else if (qe.test(i)) { for (o = o || c.appendChild(t.createElement("div")), s = (Le.exec(i) || ["", ""])[1].toLowerCase(), a = Re[s] || Re._default, o.innerHTML = a[1] + i.replace(Ae, "<$1></$2>") + a[2], l = a[0]; l--;) o = o.lastChild; Z.merge(f, o.childNodes), o = c.firstChild, o.textContent = "" } else f.push(t.createTextNode(i)); for (c.textContent = "", d = 0; i = f[d++];) if ((!r || -1 === Z.inArray(i, r)) && (u = Z.contains(i.ownerDocument, i), o = v(c.appendChild(i), "script"), u && g(o), n)) for (l = 0; i = o[l++];) Fe.test(i.type || "") && n.push(i); return c }, cleanData: function(e) { for (var t, n, r, i, o = Z.event.special, s = 0; void 0 !== (n = e[s]); s++) { if (Z.acceptData(n) && (i = n[ve.expando], i && (t = ve.cache[i]))) { if (t.events) for (r in t.events) o[r] ? Z.event.remove(n, r) : Z.removeEvent(n, r, t.handle); ve.cache[i] && delete ve.cache[i] } delete ye.cache[n[ye.expando]] } } }), Z.fn.extend({ text: function(e) { return me(this, function(e) { return void 0 === e ? Z.text(this) : this.empty().each(function() { (1 === this.nodeType || 11 === this.nodeType || 9 === this.nodeType) && (this.textContent = e) }) }, null, e, arguments.length) }, append: function() { return this.domManip(arguments, function(e) { if (1 === this.nodeType || 11 === this.nodeType || 9 === this.nodeType) { var t = d(this, e); t.appendChild(e) } }) }, prepend: function() { return this.domManip(arguments, function(e) { if (1 === this.nodeType || 11 === this.nodeType || 9 === this.nodeType) { var t = d(this, e); t.insertBefore(e, t.firstChild) } }) }, before: function() { return this.domManip(arguments, function(e) { this.parentNode && this.parentNode.insertBefore(e, this) }) }, after: function() { return this.domManip(arguments, function(e) { this.parentNode && this.parentNode.insertBefore(e, this.nextSibling) }) }, remove: function(e, t) { for (var n, r = e ? Z.filter(e, this) : this, i = 0; null != (n = r[i]); i++) t || 1 !== n.nodeType || Z.cleanData(v(n)), n.parentNode && (t && Z.contains(n.ownerDocument, n) && g(v(n, "script")), n.parentNode.removeChild(n)); return this }, empty: function() { for (var e, t = 0; null != (e = this[t]); t++) 1 === e.nodeType && (Z.cleanData(v(e, !1)), e.textContent = ""); return this }, clone: function(e, t) { return e = null != e && e, t = null == t ? e : t, this.map(function() { return Z.clone(this, e, t) }) }, html: function(e) { return me(this, function(e) { var t = this[0] || {}, n = 0, r = this.length; if (void 0 === e && 1 === t.nodeType) return t.innerHTML; if ("string" == typeof e && !He.test(e) && !Re[(Le.exec(e) || ["", ""])[1].toLowerCase()]) { e = e.replace(Ae, "<$1></$2>"); try { for (; r > n; n++) t = this[n] || {}, 1 === t.nodeType && (Z.cleanData(v(t, !1)), t.innerHTML = e); t = 0 } catch (i) {} } t && this.empty().append(e) }, null, e, arguments.length) }, replaceWith: function() { var e = arguments[0]; return this.domManip(arguments, function(t) { e = this.parentNode, Z.cleanData(v(this)), e && e.replaceChild(t, this) }), e && (e.length || e.nodeType) ? this : this.remove() }, detach: function(e) { return this.remove(e, !0) }, domManip: function(e, t) { e = z.apply([], e); var n, r, i, o, s, a, u = 0, l = this.length, c = this, f = l - 1, d = e[0], g = Z.isFunction(d); if (g || l > 1 && "string" == typeof d && !Q.checkClone && Oe.test(d)) return this.each(function(n) { var r = c.eq(n); g && (e[0] = d.call(this, n, r.html())), r.domManip(e, t) }); if (l && (n = Z.buildFragment(e, this[0].ownerDocument, !1, this), r = n.firstChild, 1 === n.childNodes.length && (n = r), r)) { for (i = Z.map(v(n, "script"), p), o = i.length; l > u; u++) s = n, u !== f && (s = Z.clone(s, !0, !0), o && Z.merge(i, v(s, "script"))), t.call(this[u], s, u); if (o) for (a = i[i.length - 1].ownerDocument, Z.map(i, h), u = 0; o > u; u++) s = i[u], Fe.test(s.type || "") && !ve.access(s, "globalEval") && Z.contains(a, s) && (s.src ? Z._evalUrl && Z._evalUrl(s.src) : Z.globalEval(s.textContent.replace(Me, ""))) } return this } }), Z.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function(e, t) { Z.fn[e] = function(e) { for (var n, r = [], i = Z(e), o = i.length - 1, s = 0; o >= s; s++) n = s === o ? this : this.clone(!0), Z(i[s])[t](n), X.apply(r, n.get()); return this.pushStack(r) } }); var We, Ie = {}, $e = /^margin/, Be = new RegExp("^(" + we + ")(?!px)[a-z%]+$", "i"), _e = function(t) { return t.ownerDocument.defaultView.opener ? t.ownerDocument.defaultView.getComputedStyle(t, null) : e.getComputedStyle(t, null) }; ! function() { function t() { s.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute", s.innerHTML = "", i.appendChild(o); var t = e.getComputedStyle(s, null); n = "1%" !== t.top, r = "4px" === t.width, i.removeChild(o) } var n, r, i = J.documentElement, o = J.createElement("div"), s = J.createElement("div"); s.style && (s.style.backgroundClip = "content-box", s.cloneNode(!0).style.backgroundClip = "", Q.clearCloneStyle = "content-box" === s.style.backgroundClip, o.style.cssText = "border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;position:absolute", o.appendChild(s), e.getComputedStyle && Z.extend(Q, { pixelPosition: function() { return t(), n }, boxSizingReliable: function() { return null == r && t(), r }, reliableMarginRight: function() { var t, n = s.appendChild(J.createElement("div")); return n.style.cssText = s.style.cssText = "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0", n.style.marginRight = n.style.width = "0", s.style.width = "1px", i.appendChild(o), t = !parseFloat(e.getComputedStyle(n, null).marginRight), i.removeChild(o), s.removeChild(n), t } })) }(), Z.swap = function(e, t, n, r) { var i, o, s = {}; for (o in t) s[o] = e.style[o], e.style[o] = t[o]; i = n.apply(e, r || []); for (o in t) e.style[o] = s[o]; return i }; var ze = /^(none|table(?!-c[ea]).+)/, Xe = new RegExp("^(" + we + ")(.*)$", "i"), Ve = new RegExp("^([+-])=(" + we + ")", "i"), Ue = { position: "absolute", visibility: "hidden", display: "block" }, Ye = { letterSpacing: "0", fontWeight: "400" }, Ge = ["Webkit", "O", "Moz", "ms"]; Z.extend({ cssHooks: { opacity: { get: function(e, t) { if (t) { var n = w(e, "opacity"); return "" === n ? "1" : n } } } }, cssNumber: { columnCount: !0, fillOpacity: !0, flexGrow: !0, flexShrink: !0, fontWeight: !0, lineHeight: !0, opacity: !0, order: !0, orphans: !0, widows: !0, zIndex: !0, zoom: !0 }, cssProps: { "float": "cssFloat" }, style: function(e, t, n, r) { if (e && 3 !== e.nodeType && 8 !== e.nodeType && e.style) { var i, o, s, a = Z.camelCase(t), u = e.style; return t = Z.cssProps[a] || (Z.cssProps[a] = C(u, a)), s = Z.cssHooks[t] || Z.cssHooks[a], void 0 === n ? s && "get" in s && void 0 !== (i = s.get(e, !1, r)) ? i : u[t] : (o = typeof n, "string" === o && (i = Ve.exec(n)) && (n = (i[1] + 1) * i[2] + parseFloat(Z.css(e, t)), o = "number"), void(null != n && n === n && ("number" !== o || Z.cssNumber[a] || (n += "px"), Q.clearCloneStyle || "" !== n || 0 !== t.indexOf("background") || (u[t] = "inherit"), s && "set" in s && void 0 === (n = s.set(e, n, r)) || (u[t] = n)))) } }, css: function(e, t, n, r) { var i, o, s, a = Z.camelCase(t); return t = Z.cssProps[a] || (Z.cssProps[a] = C(e.style, a)), s = Z.cssHooks[t] || Z.cssHooks[a], s && "get" in s && (i = s.get(e, !0, n)), void 0 === i && (i = w(e, t, r)), "normal" === i && t in Ye && (i = Ye[t]), "" === n || n ? (o = parseFloat(i), n === !0 || Z.isNumeric(o) ? o || 0 : i) : i } }), Z.each(["height", "width"], function(e, t) { Z.cssHooks[t] = { get: function(e, n, r) { return n ? ze.test(Z.css(e, "display")) && 0 === e.offsetWidth ? Z.swap(e, Ue, function() { return E(e, t, r) }) : E(e, t, r) : void 0 }, set: function(e, n, r) { var i = r && _e(e); return k(e, n, r ? N(e, t, r, "border-box" === Z.css(e, "boxSizing", !1, i), i) : 0) } } }), Z.cssHooks.marginRight = T(Q.reliableMarginRight, function(e, t) { return t ? Z.swap(e, { display: "inline-block" }, w, [e, "marginRight"]) : void 0 }), Z.each({ margin: "", padding: "", border: "Width" }, function(e, t) { Z.cssHooks[e + t] = { expand: function(n) { for (var r = 0, i = {}, o = "string" == typeof n ? n.split(" ") : [n]; 4 > r; r++) i[e + Te[r] + t] = o[r] || o[r - 2] || o[0]; return i } }, $e.test(e) || (Z.cssHooks[e + t].set = k) }), Z.fn.extend({ css: function(e, t) { return me(this, function(e, t, n) { var r, i, o = {}, s = 0; if (Z.isArray(t)) { for (r = _e(e), i = t.length; i > s; s++) o[t[s]] = Z.css(e, t[s], !1, r); return o } return void 0 !== n ? Z.style(e, t, n) : Z.css(e, t) }, e, t, arguments.length > 1) }, show: function() { return j(this, !0) }, hide: function() { return j(this) }, toggle: function(e) { return "boolean" == typeof e ? e ? this.show() : this.hide() : this.each(function() { Ce(this) ? Z(this).show() : Z(this).hide() }) } }), Z.Tween = S, S.prototype = { constructor: S, init: function(e, t, n, r, i, o) { this.elem = e, this.prop = n, this.easing = i || "swing", this.options = t, this.start = this.now = this.cur(), this.end = r, this.unit = o || (Z.cssNumber[n] ? "" : "px") }, cur: function() { var e = S.propHooks[this.prop]; return e && e.get ? e.get(this) : S.propHooks._default.get(this) }, run: function(e) { var t, n = S.propHooks[this.prop]; return this.options.duration ? this.pos = t = Z.easing[this.easing](e, this.options.duration * e, 0, 1, this.options.duration) : this.pos = t = e, this.now = (this.end - this.start) * t + this.start, this.options.step && this.options.step.call(this.elem, this.now, this), n && n.set ? n.set(this) : S.propHooks._default.set(this), this } }, S.prototype.init.prototype = S.prototype, S.propHooks = { _default: { get: function(e) { var t; return null == e.elem[e.prop] || e.elem.style && null != e.elem.style[e.prop] ? (t = Z.css(e.elem, e.prop, ""), t && "auto" !== t ? t : 0) : e.elem[e.prop] }, set: function(e) { Z.fx.step[e.prop] ? Z.fx.step[e.prop](e) : e.elem.style && (null != e.elem.style[Z.cssProps[e.prop]] || Z.cssHooks[e.prop]) ? Z.style(e.elem, e.prop, e.now + e.unit) : e.elem[e.prop] = e.now } } }, S.propHooks.scrollTop = S.propHooks.scrollLeft = { set: function(e) { e.elem.nodeType && e.elem.parentNode && (e.elem[e.prop] = e.now) } }, Z.easing = { linear: function(e) { return e }, swing: function(e) { return .5 - Math.cos(e * Math.PI) / 2 } }, Z.fx = S.prototype.init, Z.fx.step = {}; var Qe, Je, Ke = /^(?:toggle|show|hide)$/, Ze = new RegExp("^(?:([+-])=|)(" + we + ")([a-z%]*)$", "i"), et = /queueHooks$/, tt = [q], nt = { "*": [function(e, t) { var n = this.createTween(e, t), r = n.cur(), i = Ze.exec(t), o = i && i[3] || (Z.cssNumber[e] ? "" : "px"), s = (Z.cssNumber[e] || "px" !== o && +r) && Ze.exec(Z.css(n.elem, e)), a = 1, u = 20; if (s && s[3] !== o) { o = o || s[3], i = i || [], s = +r || 1; do a = a || ".5", s /= a, Z.style(n.elem, e, s + o); while (a !== (a = n.cur() / r) && 1 !== a && --u) } return i && (s = n.start = +s || +r || 0, n.unit = o, n.end = i[1] ? s + (i[1] + 1) * i[2] : +i[2]), n }] }; Z.Animation = Z.extend(O, { tweener: function(e, t) { Z.isFunction(e) ? (t = e, e = ["*"]) : e = e.split(" "); for (var n, r = 0, i = e.length; i > r; r++) n = e[r], nt[n] = nt[n] || [], nt[n].unshift(t) }, prefilter: function(e, t) { t ? tt.unshift(e) : tt.push(e) } }), Z.speed = function(e, t, n) { var r = e && "object" == typeof e ? Z.extend({}, e) : { complete: n || !n && t || Z.isFunction(e) && e, duration: e, easing: n && t || t && !Z.isFunction(t) && t }; return r.duration = Z.fx.off ? 0 : "number" == typeof r.duration ? r.duration : r.duration in Z.fx.speeds ? Z.fx.speeds[r.duration] : Z.fx.speeds._default, (null == r.queue || r.queue === !0) && (r.queue = "fx"), r.old = r.complete, r.complete = function() { Z.isFunction(r.old) && r.old.call(this), r.queue && Z.dequeue(this, r.queue) }, r }, Z.fn.extend({ fadeTo: function(e, t, n, r) { return this.filter(Ce).css("opacity", 0).show().end().animate({ opacity: t }, e, n, r) }, animate: function(e, t, n, r) { var i = Z.isEmptyObject(e), o = Z.speed(t, n, r), s = function() { var t = O(this, Z.extend({}, e), o); (i || ve.get(this, "finish")) && t.stop(!0) }; return s.finish = s, i || o.queue === !1 ? this.each(s) : this.queue(o.queue, s) }, stop: function(e, t, n) { var r = function(e) { var t = e.stop; delete e.stop, t(n) }; return "string" != typeof e && (n = t, t = e, e = void 0), t && e !== !1 && this.queue(e || "fx", []), this.each(function() { var t = !0, i = null != e && e + "queueHooks", o = Z.timers, s = ve.get(this); if (i) s[i] && s[i].stop && r(s[i]); else for (i in s) s[i] && s[i].stop && et.test(i) && r(s[i]); for (i = o.length; i--;) o[i].elem !== this || null != e && o[i].queue !== e || (o[i].anim.stop(n), t = !1, o.splice(i, 1)); (t || !n) && Z.dequeue(this, e) }) }, finish: function(e) { return e !== !1 && (e = e || "fx"), this.each(function() { var t, n = ve.get(this), r = n[e + "queue"], i = n[e + "queueHooks"], o = Z.timers, s = r ? r.length : 0; for (n.finish = !0, Z.queue(this, e, []), i && i.stop && i.stop.call(this, !0), t = o.length; t--;) o[t].elem === this && o[t].queue === e && (o[t].anim.stop(!0), o.splice(t, 1)); for (t = 0; s > t; t++) r[t] && r[t].finish && r[t].finish.call(this); delete n.finish }) } }), Z.each(["toggle", "show", "hide"], function(e, t) { var n = Z.fn[t]; Z.fn[t] = function(e, r, i) { return null == e || "boolean" == typeof e ? n.apply(this, arguments) : this.animate(A(t, !0), e, r, i) } }), Z.each({ slideDown: A("show"), slideUp: A("hide"), slideToggle: A("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function(e, t) { Z.fn[e] = function(e, n, r) { return this.animate(t, e, n, r) } }), Z.timers = [], Z.fx.tick = function() { var e, t = 0, n = Z.timers; for (Qe = Z.now(); t < n.length; t++) e = n[t], e() || n[t] !== e || n.splice(t--, 1); n.length || Z.fx.stop(), Qe = void 0 }, Z.fx.timer = function(e) { Z.timers.push(e), e() ? Z.fx.start() : Z.timers.pop() }, Z.fx.interval = 13, Z.fx.start = function() { Je || (Je = setInterval(Z.fx.tick, Z.fx.interval)) }, Z.fx.stop = function() { clearInterval(Je), Je = null }, Z.fx.speeds = { slow: 600, fast: 200, _default: 400 }, Z.fn.delay = function(e, t) { return e = Z.fx ? Z.fx.speeds[e] || e : e, t = t || "fx", this.queue(t, function(t, n) { var r = setTimeout(t, e); n.stop = function() { clearTimeout(r) } }) }, function() { var e = J.createElement("input"), t = J.createElement("select"), n = t.appendChild(J.createElement("option")); e.type = "checkbox", Q.checkOn = "" !== e.value, Q.optSelected = n.selected, t.disabled = !0, Q.optDisabled = !n.disabled, e = J.createElement("input"), e.value = "t", e.type = "radio", Q.radioValue = "t" === e.value }(); var rt, it, ot = Z.expr.attrHandle; Z.fn.extend({ attr: function(e, t) { return me(this, Z.attr, e, t, arguments.length > 1) }, removeAttr: function(e) { return this.each(function() { Z.removeAttr(this, e) }) } }), Z.extend({ attr: function(e, t, n) { var r, i, o = e.nodeType; if (e && 3 !== o && 8 !== o && 2 !== o) return typeof e.getAttribute === Ne ? Z.prop(e, t, n) : (1 === o && Z.isXMLDoc(e) || (t = t.toLowerCase(), r = Z.attrHooks[t] || (Z.expr.match.bool.test(t) ? it : rt)), void 0 === n ? r && "get" in r && null !== (i = r.get(e, t)) ? i : (i = Z.find.attr(e, t), null == i ? void 0 : i) : null !== n ? r && "set" in r && void 0 !== (i = r.set(e, n, t)) ? i : (e.setAttribute(t, n + ""), n) : void Z.removeAttr(e, t)) }, removeAttr: function(e, t) { var n, r, i = 0, o = t && t.match(pe); if (o && 1 === e.nodeType) for (; n = o[i++];) r = Z.propFix[n] || n, Z.expr.match.bool.test(n) && (e[r] = !1), e.removeAttribute(n) }, attrHooks: { type: { set: function(e, t) { if (!Q.radioValue && "radio" === t && Z.nodeName(e, "input")) { var n = e.value; return e.setAttribute("type", t), n && (e.value = n), t } } } } }), it = { set: function(e, t, n) { return t === !1 ? Z.removeAttr(e, n) : e.setAttribute(n, n), n } }, Z.each(Z.expr.match.bool.source.match(/\w+/g), function(e, t) { var n = ot[t] || Z.find.attr; ot[t] = function(e, t, r) { var i, o; return r || (o = ot[t], ot[t] = i, i = null != n(e, t, r) ? t.toLowerCase() : null, ot[t] = o), i } }); var st = /^(?:input|select|textarea|button)$/i; Z.fn.extend({ prop: function(e, t) { return me(this, Z.prop, e, t, arguments.length > 1) }, removeProp: function(e) { return this.each(function() { delete this[Z.propFix[e] || e] }) } }), Z.extend({ propFix: { "for": "htmlFor", "class": "className" }, prop: function(e, t, n) { var r, i, o, s = e.nodeType; if (e && 3 !== s && 8 !== s && 2 !== s) return o = 1 !== s || !Z.isXMLDoc(e), o && (t = Z.propFix[t] || t, i = Z.propHooks[t]), void 0 !== n ? i && "set" in i && void 0 !== (r = i.set(e, n, t)) ? r : e[t] = n : i && "get" in i && null !== (r = i.get(e, t)) ? r : e[t] }, propHooks: { tabIndex: { get: function(e) { return e.hasAttribute("tabindex") || st.test(e.nodeName) || e.href ? e.tabIndex : -1 } } } }), Q.optSelected || (Z.propHooks.selected = { get: function(e) { var t = e.parentNode; return t && t.parentNode && t.parentNode.selectedIndex, null } }), Z.each(["tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable"], function() { Z.propFix[this.toLowerCase()] = this }); var at = /[\t\r\n\f]/g; Z.fn.extend({ addClass: function(e) { var t, n, r, i, o, s, a = "string" == typeof e && e, u = 0, l = this.length; if (Z.isFunction(e)) return this.each(function(t) { Z(this).addClass(e.call(this, t, this.className)) }); if (a) for (t = (e || "").match(pe) || []; l > u; u++) if (n = this[u], r = 1 === n.nodeType && (n.className ? (" " + n.className + " ").replace(at, " ") : " ")) { for (o = 0; i = t[o++];) r.indexOf(" " + i + " ") < 0 && (r += i + " "); s = Z.trim(r), n.className !== s && (n.className = s) } return this }, removeClass: function(e) { var t, n, r, i, o, s, a = 0 === arguments.length || "string" == typeof e && e, u = 0, l = this.length; if (Z.isFunction(e)) return this.each(function(t) { Z(this).removeClass(e.call(this, t, this.className)) }); if (a) for (t = (e || "").match(pe) || []; l > u; u++) if (n = this[u], r = 1 === n.nodeType && (n.className ? (" " + n.className + " ").replace(at, " ") : "")) { for (o = 0; i = t[o++];) for (; r.indexOf(" " + i + " ") >= 0;) r = r.replace(" " + i + " ", " "); s = e ? Z.trim(r) : "", n.className !== s && (n.className = s) } return this }, toggleClass: function(e, t) { var n = typeof e; return "boolean" == typeof t && "string" === n ? t ? this.addClass(e) : this.removeClass(e) : this.each(Z.isFunction(e) ? function(n) { Z(this).toggleClass(e.call(this, n, this.className, t), t) } : function() { if ("string" === n) for (var t, r = 0, i = Z(this), o = e.match(pe) || []; t = o[r++];) i.hasClass(t) ? i.removeClass(t) : i.addClass(t); else(n === Ne || "boolean" === n) && (this.className && ve.set(this, "__className__", this.className), this.className = this.className || e === !1 ? "" : ve.get(this, "__className__") || "") }) }, hasClass: function(e) { for (var t = " " + e + " ", n = 0, r = this.length; r > n; n++) if (1 === this[n].nodeType && (" " + this[n].className + " ").replace(at, " ").indexOf(t) >= 0) return !0; return !1 } }); var ut = /\r/g; Z.fn.extend({ val: function(e) { var t, n, r, i = this[0]; return arguments.length ? (r = Z.isFunction(e), this.each(function(n) { var i; 1 === this.nodeType && (i = r ? e.call(this, n, Z(this).val()) : e, null == i ? i = "" : "number" == typeof i ? i += "" : Z.isArray(i) && (i = Z.map(i, function(e) { return null == e ? "" : e + "" })), t = Z.valHooks[this.type] || Z.valHooks[this.nodeName.toLowerCase()], t && "set" in t && void 0 !== t.set(this, i, "value") || (this.value = i)) })) : i ? (t = Z.valHooks[i.type] || Z.valHooks[i.nodeName.toLowerCase()], t && "get" in t && void 0 !== (n = t.get(i, "value")) ? n : (n = i.value, "string" == typeof n ? n.replace(ut, "") : null == n ? "" : n)) : void 0 } }), Z.extend({ valHooks: { option: { get: function(e) { var t = Z.find.attr(e, "value"); return null != t ? t : Z.trim(Z.text(e)) } }, select: { get: function(e) { for (var t, n, r = e.options, i = e.selectedIndex, o = "select-one" === e.type || 0 > i, s = o ? null : [], a = o ? i + 1 : r.length, u = 0 > i ? a : o ? i : 0; a > u; u++) if (n = r[u], !(!n.selected && u !== i || (Q.optDisabled ? n.disabled : null !== n.getAttribute("disabled")) || n.parentNode.disabled && Z.nodeName(n.parentNode, "optgroup"))) { if (t = Z(n).val(), o) return t; s.push(t) } return s }, set: function(e, t) { for (var n, r, i = e.options, o = Z.makeArray(t), s = i.length; s--;) r = i[s], (r.selected = Z.inArray(r.value, o) >= 0) && (n = !0); return n || (e.selectedIndex = -1), o } } } }), Z.each(["radio", "checkbox"], function() { Z.valHooks[this] = { set: function(e, t) { return Z.isArray(t) ? e.checked = Z.inArray(Z(e).val(), t) >= 0 : void 0 } }, Q.checkOn || (Z.valHooks[this].get = function(e) { return null === e.getAttribute("value") ? "on" : e.value }) }), Z.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "), function(e, t) { Z.fn[t] = function(e, n) { return arguments.length > 0 ? this.on(t, null, e, n) : this.trigger(t) } }), Z.fn.extend({ hover: function(e, t) { return this.mouseenter(e).mouseleave(t || e) }, bind: function(e, t, n) { return this.on(e, null, t, n) }, unbind: function(e, t) { return this.off(e, null, t) }, delegate: function(e, t, n, r) { return this.on(t, e, n, r) }, undelegate: function(e, t, n) { return 1 === arguments.length ? this.off(e, "**") : this.off(t, e || "**", n) } }); var lt = Z.now(), ct = /\?/; Z.parseJSON = function(e) { return JSON.parse(e + "") }, Z.parseXML = function(e) { var t, n; if (!e || "string" != typeof e) return null; try { n = new DOMParser, t = n.parseFromString(e, "text/xml") } catch (r) { t = void 0 } return (!t || t.getElementsByTagName("parsererror").length) && Z.error("Invalid XML: " + e), t }; var ft = /#.*$/, dt = /([?&])_=[^&]*/, pt = /^(.*?):[ \t]*([^\r\n]*)$/gm, ht = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, gt = /^(?:GET|HEAD)$/, mt = /^\/\//, vt = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/, yt = {}, xt = {}, bt = "*/".concat("*"), wt = e.location.href, Tt = vt.exec(wt.toLowerCase()) || []; Z.extend({ active: 0, lastModified: {}, etag: {}, ajaxSettings: { url: wt, type: "GET", isLocal: ht.test(Tt[1]), global: !0, processData: !0, async: !0, contentType: "application/x-www-form-urlencoded; charset=UTF-8", accepts: { "*": bt, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, converters: { "* text": String, "text html": !0, "text json": Z.parseJSON, "text xml": Z.parseXML }, flatOptions: { url: !0, context: !0 } }, ajaxSetup: function(e, t) { return t ? M(M(e, Z.ajaxSettings), t) : M(Z.ajaxSettings, e) }, ajaxPrefilter: F(yt), ajaxTransport: F(xt), ajax: function(e, t) { function n(e, t, n, s) { var u, c, v, y, b, T = t; 2 !== x && (x = 2, a && clearTimeout(a), r = void 0, o = s || "", w.readyState = e > 0 ? 4 : 0, u = e >= 200 && 300 > e || 304 === e, n && (y = R(f, w, n)), y = W(f, y, w, u), u ? (f.ifModified && (b = w.getResponseHeader("Last-Modified"), b && (Z.lastModified[i] = b), b = w.getResponseHeader("etag"), b && (Z.etag[i] = b)), 204 === e || "HEAD" === f.type ? T = "nocontent" : 304 === e ? T = "notmodified" : (T = y.state, c = y.data, v = y.error, u = !v)) : (v = T, (e || !T) && (T = "error", 0 > e && (e = 0))), w.status = e, w.statusText = (t || T) + "", u ? h.resolveWith(d, [c, T, w]) : h.rejectWith(d, [w, T, v]), w.statusCode(m), m = void 0, l && p.trigger(u ? "ajaxSuccess" : "ajaxError", [w, f, u ? c : v]), g.fireWith(d, [w, T]), l && (p.trigger("ajaxComplete", [w, f]), --Z.active || Z.event.trigger("ajaxStop"))) } "object" == typeof e && (t = e, e = void 0), t = t || {}; var r, i, o, s, a, u, l, c, f = Z.ajaxSetup({}, t), d = f.context || f, p = f.context && (d.nodeType || d.jquery) ? Z(d) : Z.event, h = Z.Deferred(), g = Z.Callbacks("once memory"), m = f.statusCode || {}, v = {}, y = {}, x = 0, b = "canceled", w = { readyState: 0, getResponseHeader: function(e) { var t; if (2 === x) { if (!s) for (s = {}; t = pt.exec(o);) s[t[1].toLowerCase()] = t[2]; t = s[e.toLowerCase()] } return null == t ? null : t }, getAllResponseHeaders: function() { return 2 === x ? o : null }, setRequestHeader: function(e, t) { var n = e.toLowerCase(); return x || (e = y[n] = y[n] || e, v[e] = t), this }, overrideMimeType: function(e) { return x || (f.mimeType = e), this }, statusCode: function(e) { var t; if (e) if (2 > x) for (t in e) m[t] = [m[t], e[t]]; else w.always(e[w.status]); return this }, abort: function(e) { var t = e || b; return r && r.abort(t), n(0, t), this } }; if (h.promise(w).complete = g.add, w.success = w.done, w.error = w.fail, f.url = ((e || f.url || wt) + "").replace(ft, "").replace(mt, Tt[1] + "//"), f.type = t.method || t.type || f.method || f.type, f.dataTypes = Z.trim(f.dataType || "*").toLowerCase().match(pe) || [""], null == f.crossDomain && (u = vt.exec(f.url.toLowerCase()), f.crossDomain = !(!u || u[1] === Tt[1] && u[2] === Tt[2] && (u[3] || ("http:" === u[1] ? "80" : "443")) === (Tt[3] || ("http:" === Tt[1] ? "80" : "443")))), f.data && f.processData && "string" != typeof f.data && (f.data = Z.param(f.data, f.traditional)), P(yt, f, t, w), 2 === x) return w; l = Z.event && f.global, l && 0 === Z.active++ && Z.event.trigger("ajaxStart"), f.type = f.type.toUpperCase(), f.hasContent = !gt.test(f.type), i = f.url, f.hasContent || (f.data && (i = f.url += (ct.test(i) ? "&" : "?") + f.data, delete f.data), f.cache === !1 && (f.url = dt.test(i) ? i.replace(dt, "$1_=" + lt++) : i + (ct.test(i) ? "&" : "?") + "_=" + lt++)), f.ifModified && (Z.lastModified[i] && w.setRequestHeader("If-Modified-Since", Z.lastModified[i]), Z.etag[i] && w.setRequestHeader("If-None-Match", Z.etag[i])), (f.data && f.hasContent && f.contentType !== !1 || t.contentType) && w.setRequestHeader("Content-Type", f.contentType), w.setRequestHeader("Accept", f.dataTypes[0] && f.accepts[f.dataTypes[0]] ? f.accepts[f.dataTypes[0]] + ("*" !== f.dataTypes[0] ? ", " + bt + "; q=0.01" : "") : f.accepts["*"]); for (c in f.headers) w.setRequestHeader(c, f.headers[c]); if (f.beforeSend && (f.beforeSend.call(d, w, f) === !1 || 2 === x)) return w.abort(); b = "abort"; for (c in { success: 1, error: 1, complete: 1 }) w[c](f[c]); if (r = P(xt, f, t, w)) { w.readyState = 1, l && p.trigger("ajaxSend", [w, f]), f.async && f.timeout > 0 && (a = setTimeout(function() { w.abort("timeout") }, f.timeout)); try { x = 1, r.send(v, n) } catch (T) { if (!(2 > x)) throw T; n(-1, T) } } else n(-1, "No Transport"); return w }, getJSON: function(e, t, n) { return Z.get(e, t, n, "json") }, getScript: function(e, t) { return Z.get(e, void 0, t, "script") } }), Z.each(["get", "post"], function(e, t) { Z[t] = function(e, n, r, i) { return Z.isFunction(n) && (i = i || r, r = n, n = void 0), Z.ajax({ url: e, type: t, dataType: i, data: n, success: r }) } }), Z._evalUrl = function(e) { return Z.ajax({ url: e, type: "GET", dataType: "script", async: !1, global: !1, "throws": !0 }) }, Z.fn.extend({ wrapAll: function(e) { var t; return Z.isFunction(e) ? this.each(function(t) { Z(this).wrapAll(e.call(this, t)) }) : (this[0] && (t = Z(e, this[0].ownerDocument).eq(0).clone(!0), this[0].parentNode && t.insertBefore(this[0]), t.map(function() { for (var e = this; e.firstElementChild;) e = e.firstElementChild; return e }).append(this)), this) }, wrapInner: function(e) { return this.each(Z.isFunction(e) ? function(t) { Z(this).wrapInner(e.call(this, t)) } : function() { var t = Z(this), n = t.contents(); n.length ? n.wrapAll(e) : t.append(e) }) }, wrap: function(e) { var t = Z.isFunction(e); return this.each(function(n) { Z(this).wrapAll(t ? e.call(this, n) : e) }) }, unwrap: function() { return this.parent().each(function() { Z.nodeName(this, "body") || Z(this).replaceWith(this.childNodes) }).end() } }), Z.expr.filters.hidden = function(e) { return e.offsetWidth <= 0 && e.offsetHeight <= 0 }, Z.expr.filters.visible = function(e) { return !Z.expr.filters.hidden(e) }; var Ct = /%20/g, kt = /\[\]$/, Nt = /\r?\n/g, Et = /^(?:submit|button|image|reset|file)$/i, jt = /^(?:input|select|textarea|keygen)/i; Z.param = function(e, t) { var n, r = [], i = function(e, t) { t = Z.isFunction(t) ? t() : null == t ? "" : t, r[r.length] = encodeURIComponent(e) + "=" + encodeURIComponent(t) }; if (void 0 === t && (t = Z.ajaxSettings && Z.ajaxSettings.traditional), Z.isArray(e) || e.jquery && !Z.isPlainObject(e)) Z.each(e, function() { i(this.name, this.value) }); else for (n in e) I(n, e[n], t, i); return r.join("&").replace(Ct, "+") }, Z.fn.extend({ serialize: function() { return Z.param(this.serializeArray()) }, serializeArray: function() { return this.map(function() { var e = Z.prop(this, "elements"); return e ? Z.makeArray(e) : this }).filter(function() { var e = this.type; return this.name && !Z(this).is(":disabled") && jt.test(this.nodeName) && !Et.test(e) && (this.checked || !ke.test(e)) }).map(function(e, t) { var n = Z(this).val(); return null == n ? null : Z.isArray(n) ? Z.map(n, function(e) { return { name: t.name, value: e.replace(Nt, "\r\n") } }) : { name: t.name, value: n.replace(Nt, "\r\n") } }).get() } }), Z.ajaxSettings.xhr = function() { try { return new XMLHttpRequest } catch (e) {} }; var St = 0, Dt = {}, At = { 0: 200, 1223: 204 }, Lt = Z.ajaxSettings.xhr(); e.attachEvent && e.attachEvent("onunload", function() { for (var e in Dt) Dt[e]() }), Q.cors = !!Lt && "withCredentials" in Lt, Q.ajax = Lt = !!Lt, Z.ajaxTransport(function(e) { var t; return Q.cors || Lt && !e.crossDomain ? { send: function(n, r) { var i, o = e.xhr(), s = ++St; if (o.open(e.type, e.url, e.async, e.username, e.password), e.xhrFields) for (i in e.xhrFields) o[i] = e.xhrFields[i]; e.mimeType && o.overrideMimeType && o.overrideMimeType(e.mimeType), e.crossDomain || n["X-Requested-With"] || (n["X-Requested-With"] = "XMLHttpRequest"); for (i in n) o.setRequestHeader(i, n[i]); t = function(e) { return function() { t && (delete Dt[s], t = o.onload = o.onerror = null, "abort" === e ? o.abort() : "error" === e ? r(o.status, o.statusText) : r(At[o.status] || o.status, o.statusText, "string" == typeof o.responseText ? { text: o.responseText } : void 0, o.getAllResponseHeaders())) } }, o.onload = t(), o.onerror = t("error"), t = Dt[s] = t("abort"); try { o.send(e.hasContent && e.data || null) } catch (a) { if (t) throw a } }, abort: function() { t && t() } } : void 0 }), Z.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function(e) { return Z.globalEval(e), e } } }), Z.ajaxPrefilter("script", function(e) { void 0 === e.cache && (e.cache = !1), e.crossDomain && (e.type = "GET") }), Z.ajaxTransport("script", function(e) { if (e.crossDomain) { var t, n; return { send: function(r, i) { t = Z("<script>").prop({ async: !0, charset: e.scriptCharset, src: e.url }).on("load error", n = function(e) { t.remove(), n = null, e && i("error" === e.type ? 404 : 200, e.type) }), J.head.appendChild(t[0]) }, abort: function() { n && n() } } } }); var qt = [], Ht = /(=)\?(?=&|$)|\?\?/; Z.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var e = qt.pop() || Z.expando + "_" + lt++; return this[e] = !0, e } }), Z.ajaxPrefilter("json jsonp", function(t, n, r) { var i, o, s, a = t.jsonp !== !1 && (Ht.test(t.url) ? "url" : "string" == typeof t.data && !(t.contentType || "").indexOf("application/x-www-form-urlencoded") && Ht.test(t.data) && "data"); return a || "jsonp" === t.dataTypes[0] ? (i = t.jsonpCallback = Z.isFunction(t.jsonpCallback) ? t.jsonpCallback() : t.jsonpCallback, a ? t[a] = t[a].replace(Ht, "$1" + i) : t.jsonp !== !1 && (t.url += (ct.test(t.url) ? "&" : "?") + t.jsonp + "=" + i), t.converters["script json"] = function() { return s || Z.error(i + " was not called"), s[0] }, t.dataTypes[0] = "json", o = e[i], e[i] = function() { s = arguments }, r.always(function() { e[i] = o, t[i] && (t.jsonpCallback = n.jsonpCallback, qt.push(i)), s && Z.isFunction(o) && o(s[0]), s = o = void 0 }), "script") : void 0 }), Z.parseHTML = function(e, t, n) { if (!e || "string" != typeof e) return null; "boolean" == typeof t && (n = t, t = !1), t = t || J; var r = se.exec(e), i = !n && []; return r ? [t.createElement(r[1])] : (r = Z.buildFragment([e], t, i), i && i.length && Z(i).remove(), Z.merge([], r.childNodes)) }; var Ot = Z.fn.load; Z.fn.load = function(e, t, n) { if ("string" != typeof e && Ot) return Ot.apply(this, arguments); var r, i, o, s = this, a = e.indexOf(" "); return a >= 0 && (r = Z.trim(e.slice(a)), e = e.slice(0, a)), Z.isFunction(t) ? (n = t, t = void 0) : t && "object" == typeof t && (i = "POST"), s.length > 0 && Z.ajax({ url: e, type: i, dataType: "html", data: t }).done(function(e) { o = arguments, s.html(r ? Z("<div>").append(Z.parseHTML(e)).find(r) : e) }).complete(n && function(e, t) { s.each(n, o || [e.responseText, t, e]) }), this }, Z.each(["ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend"], function(e, t) { Z.fn[t] = function(e) { return this.on(t, e) } }), Z.expr.filters.animated = function(e) { return Z.grep(Z.timers, function(t) { return e === t.elem }).length }; var Ft = e.document.documentElement; Z.offset = { setOffset: function(e, t, n) { var r, i, o, s, a, u, l, c = Z.css(e, "position"), f = Z(e), d = {}; "static" === c && (e.style.position = "relative"), a = f.offset(), o = Z.css(e, "top"), u = Z.css(e, "left"), l = ("absolute" === c || "fixed" === c) && (o + u).indexOf("auto") > -1, l ? (r = f.position(), s = r.top, i = r.left) : (s = parseFloat(o) || 0, i = parseFloat(u) || 0), Z.isFunction(t) && (t = t.call(e, n, a)), null != t.top && (d.top = t.top - a.top + s), null != t.left && (d.left = t.left - a.left + i), "using" in t ? t.using.call(e, d) : f.css(d) } }, Z.fn.extend({ offset: function(e) { if (arguments.length) return void 0 === e ? this : this.each(function(t) { Z.offset.setOffset(this, e, t) }); var t, n, r = this[0], i = { top: 0, left: 0 }, o = r && r.ownerDocument; return o ? (t = o.documentElement, Z.contains(t, r) ? (typeof r.getBoundingClientRect !== Ne && (i = r.getBoundingClientRect()), n = $(o), { top: i.top + n.pageYOffset - t.clientTop, left: i.left + n.pageXOffset - t.clientLeft }) : i) : void 0 }, position: function() { if (this[0]) { var e, t, n = this[0], r = { top: 0, left: 0 }; return "fixed" === Z.css(n, "position") ? t = n.getBoundingClientRect() : (e = this.offsetParent(), t = this.offset(), Z.nodeName(e[0], "html") || (r = e.offset()), r.top += Z.css(e[0], "borderTopWidth", !0), r.left += Z.css(e[0], "borderLeftWidth", !0)), { top: t.top - r.top - Z.css(n, "marginTop", !0), left: t.left - r.left - Z.css(n, "marginLeft", !0) } } }, offsetParent: function() { return this.map(function() { for (var e = this.offsetParent || Ft; e && !Z.nodeName(e, "html") && "static" === Z.css(e, "position");) e = e.offsetParent; return e || Ft }) } }), Z.each({ scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function(t, n) { var r = "pageYOffset" === n; Z.fn[t] = function(i) { return me(this, function(t, i, o) { var s = $(t); return void 0 === o ? s ? s[n] : t[i] : void(s ? s.scrollTo(r ? e.pageXOffset : o, r ? o : e.pageYOffset) : t[i] = o) }, t, i, arguments.length, null) } }), Z.each(["top", "left"], function(e, t) { Z.cssHooks[t] = T(Q.pixelPosition, function(e, n) { return n ? (n = w(e, t), Be.test(n) ? Z(e).position()[t] + "px" : n) : void 0 }) }), Z.each({ Height: "height", Width: "width" }, function(e, t) { Z.each({ padding: "inner" + e, content: t, "": "outer" + e }, function(n, r) { Z.fn[r] = function(r, i) { var o = arguments.length && (n || "boolean" != typeof r), s = n || (r === !0 || i === !0 ? "margin" : "border"); return me(this, function(t, n, r) { var i; return Z.isWindow(t) ? t.document.documentElement["client" + e] : 9 === t.nodeType ? (i = t.documentElement, Math.max(t.body["scroll" + e], i["scroll" + e], t.body["offset" + e], i["offset" + e], i["client" + e])) : void 0 === r ? Z.css(t, n, s) : Z.style(t, n, r, s) }, t, o ? r : void 0, o, null) } }) }), Z.fn.size = function() { return this.length }, Z.fn.andSelf = Z.fn.addBack, "function" == typeof define && define.amd && define("jquery", [], function() { return Z }); var Pt = e.jQuery, Mt = e.$; return Z.noConflict = function(t) { return e.$ === Z && (e.$ = Mt), t && e.jQuery === Z && (e.jQuery = Pt), Z }, typeof t === Ne && (e.jQuery = e.$ = Z), Z }), function(e) { "use strict"; e.fn.fitVids = function(t) { var n = { customSelector: null, ignore: null }; if (!document.getElementById("fit-vids-style")) { var r = document.head || document.getElementsByTagName("head")[0], i = ".fluid-width-video-wrapper{width:100%;position:relative;padding:0;}.fluid-width-video-wrapper iframe,.fluid-width-video-wrapper object,.fluid-width-video-wrapper embed {position:absolute;top:0;left:0;width:100%;height:100%;}", o = document.createElement("div"); o.innerHTML = '<p>x</p><style id="fit-vids-style">' + i + "</style>", r.appendChild(o.childNodes[1]) } return t && e.extend(n, t), this.each(function() { var t = ['iframe[src*="player.vimeo.com"]', 'iframe[src*="youtube.com"]', 'iframe[src*="youtube-nocookie.com"]', 'iframe[src*="kickstarter.com"][src*="video.html"]', "object", "embed"]; n.customSelector && t.push(n.customSelector); var r = ".fitvidsignore"; n.ignore && (r = r + ", " + n.ignore); var i = e(this).find(t.join(",")); i = i.not("object object"), i = i.not(r), i.each(function() { var t = e(this); if (!(t.parents(r).length > 0 || "embed" === this.tagName.toLowerCase() && t.parent("object").length || t.parent(".fluid-width-video-wrapper").length)) { t.css("height") || t.css("width") || !isNaN(t.attr("height")) && !isNaN(t.attr("width")) || (t.attr("height", 9), t.attr("width", 16)); var n = "object" === this.tagName.toLowerCase() || t.attr("height") && !isNaN(parseInt(t.attr("height"), 10)) ? parseInt(t.attr("height"), 10) : t.height(), i = isNaN(parseInt(t.attr("width"), 10)) ? t.width() : parseInt(t.attr("width"), 10), o = n / i; if (!t.attr("name")) { var s = "fitvid" + e.fn.fitVids._count; t.attr("name", s), e.fn.fitVids._count++ } t.wrap('<div class="fluid-width-video-wrapper"></div>').parent(".fluid-width-video-wrapper").css("padding-top", 100 * o + "%"), t.removeAttr("height").removeAttr("width") } }) }) }, e.fn.fitVids._count = 0 }(window.jQuery || window.Zepto), function(e) { "use strict"; e(document).ready(function() { function t() { n(), e(".video").fitVids(), e(window).load(function() { u(), y && initDunkedLightbox(".gallery", !0) }) } function n() { c && c.addEventListener("click", function(e) { history.pushState(null, null, "/"), i() }), g[0].addEventListener("click", function(t) { var n = t.target; d && n !== m[0] && !e(n).parents("#modal-content").length && (history.pushState(null, null, "/"), i()) }) } function r() { d = !0, l.addClass("show-modal"), g.animate({ scrollTop: 0 }, 300), g.addClass("modal--show"), v.addClass("loading--show"), m.addClass("modal-content--show") } function i() { d = !1, m.find(".project").removeClass("project--show"), setTimeout(function() { m.html(""), f.removeClass("button--close--show"), m.removeClass("modal-content--show"), l.removeClass("show-modal"), g.css("-webkit-overflow-scrolling", "auto"), g.removeClass("modal--show") }, 400) } function o() { v.removeClass("loading--show"), m.find(".project").addClass("project--show"), f.addClass("button--close--show"), setTimeout(function() { g.css("-webkit-overflow-scrolling", "touch") }, 250) } function s() { r(), setTimeout(function() { m.find(".project").removeClass("project--show"), setTimeout(function() { m.html("") }, 400) }, 300), f.removeClass("button--close--show"), v.addClass("loading--show") } function a(t) { e.get(t, function(t) { var n = e(t).find("#ajax-content"), r = e(n).attr("data-id"); if (m.html(n), picturefill(), e(".video").fitVids(), n.find("img").length > 0 ? n.find("img").on("load", function() { o() }) : setTimeout(function() { o() }, 200), y) { var i = n.find(".gallery").attr({ "data-pswp-uid": r }); i.length && initDunkedLightbox(".gallery", !0) } }) } function u() { e("#loading-body").fadeOut("300", function() { e(this).removeClass("loading--show") }), h.find(".brick").each(function(t) { var n = e(this), r = Math.floor(100 * Math.random() + 101) * t; setTimeout(function() { n.addClass("brick--show"), setTimeout(function() { "no-image" !== n.data("img-url") && n.css({ "background-image": "url(" + n.data("img-url") + ")" }) }, r + 20) }, r) }) } var l = e("body"), c = document.getElementById("close-button"), f = e(c), d = !1, p = e(".list-pages").find("a").not('[data-link-type="page-redirect"]'), h = e("#ajax-projects-feed"), g = (e(".project"), e("#modal")), m = e("#modal-content"), v = e("#loading"), y = l.hasClass("lightbox-enabled"); h.on("click", ".project a", function(t) { //t.preventDefault(), history.pushState(null, null, this.href), r(), a(e(this).attr("href")) }), p.on("click", function(t) { //t.preventDefault(), history.pushState(null, null, this.href), r(), a(e(this).attr("href")) }), e(window).on("popstate", function(e) { var t = history.location || document.location; if ("/" != t.pathname) { h.find('.project a[href="' + t.href + '"]'); s(), a(t.href) } else d && i() }), t() }) }(window.jQuery);
/** * The reveal.js markdown plugin. Handles parsing of * markdown inside of presentations as well as loading * of external markdown documents. */ (function(){ if( typeof marked === 'undefined' ) { throw 'The reveal.js Markdown plugin requires marked to be loaded'; } if( typeof hljs !== 'undefined' ) { marked.setOptions({ highlight: function( lang, code ) { return hljs.highlightAuto( lang, code ).value; } }); } /** * Retrieves the markdown contents of a slide section * element. Normalizes leading tabs/whitespace. */ function getMarkdownFromSlide( section ) { var template = section.querySelector( 'script' ); // strip leading whitespace so it isn't evaluated as code var text = ( template || section ).textContent; var leadingWs = text.match( /^\n?(\s*)/ )[1].length, leadingTabs = text.match( /^\n?(\t*)/ )[1].length; if( leadingTabs > 0 ) { text = text.replace( new RegExp('\\n?\\t{' + leadingTabs + '}','g'), '\n' ); } else if( leadingWs > 1 ) { text = text.replace( new RegExp('\\n? {' + leadingWs + '}','g'), '\n' ); } return text; } /** * Given a markdown slide section element, this will * return all arguments that aren't related to markdown * parsing. Used to forward any other user-defined arguments * to the output markdown slide. */ function getForwardedAttributes( section ) { var attributes = section.attributes; var result = []; for( var i = 0, len = attributes.length; i < len; i++ ) { var name = attributes[i].name, value = attributes[i].value; // disregard attributes that are used for markdown loading/parsing if( /data\-(markdown|separator|vertical|notes)/gi.test( name ) ) continue; if( value ) { result.push( name + '=' + value ); } else { result.push( name ); } } return result.join( ' ' ); } /** * Helper function for constructing a markdown slide. */ function createMarkdownSlide( data ) { var content = data.content || data; if( data.notes ) { content += '<aside class="notes" data-markdown>' + data.notes + '</aside>'; } return '<script type="text/template">' + content + '</script>'; } /** * Parses a data string into multiple slides based * on the passed in separator arguments. */ function slidifyMarkdown( markdown, options ) { options = options || {}; options.separator = options.separator || '^\n---\n$'; options.notesSeparator = options.notesSeparator || 'note:'; options.attributes = options.attributes || ''; var separatorRegex = new RegExp( options.separator + ( options.verticalSeparator ? '|' + options.verticalSeparator : '' ), 'mg' ), horizontalSeparatorRegex = new RegExp( options.separator ), notesSeparatorRegex = new RegExp( options.notesSeparator, 'mgi' ); var matches, noteMatch, lastIndex = 0, isHorizontal, wasHorizontal = true, content, notes, slide, sectionStack = []; // iterate until all blocks between separators are stacked up while( matches = separatorRegex.exec( markdown ) ) { notes = null; // determine direction (horizontal by default) isHorizontal = horizontalSeparatorRegex.test( matches[0] ); if( !isHorizontal && wasHorizontal ) { // create vertical stack sectionStack.push( [] ); } // pluck slide content from markdown input content = markdown.substring( lastIndex, matches.index ); noteMatch = content.split( notesSeparatorRegex ); if( noteMatch.length === 2 ) { content = noteMatch[0]; notes = noteMatch[1].trim(); } slide = { content: content, notes: notes || '' }; if( isHorizontal && wasHorizontal ) { // add to horizontal stack sectionStack.push( slide ); } else { // add to vertical stack sectionStack[sectionStack.length-1].push( slide ); } lastIndex = separatorRegex.lastIndex; wasHorizontal = isHorizontal; } // add the remaining slide ( wasHorizontal ? sectionStack : sectionStack[sectionStack.length-1] ).push( markdown.substring( lastIndex ) ); var markdownSections = ''; // flatten the hierarchical stack, and insert <section data-markdown> tags for( var i = 0, len = sectionStack.length; i < len; i++ ) { // vertical if( sectionStack[i].propertyIsEnumerable( length ) && typeof sectionStack[i].splice === 'function' ) { markdownSections += '<section '+ options.attributes +'>' + '<section data-markdown>' + sectionStack[i].map( createMarkdownSlide ).join( '</section><section data-markdown>' ) + '</section>' + '</section>'; } else { markdownSections += '<section '+ options.attributes +' data-markdown>' + createMarkdownSlide( sectionStack[i] ) + '</section>'; } } return markdownSections; } function loadExternalMarkdown() { var sections = document.querySelectorAll( '[data-markdown]'), section; for( var i = 0, len = sections.length; i < len; i++ ) { section = sections[i]; if( section.getAttribute( 'data-markdown' ).length ) { var xhr = new XMLHttpRequest(), url = section.getAttribute( 'data-markdown' ); datacharset = section.getAttribute( 'data-charset' ); // see https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute#Notes if( datacharset != null && datacharset != '' ) { xhr.overrideMimeType( 'text/html; charset=' + datacharset ); } xhr.onreadystatechange = function() { if( xhr.readyState === 4 ) { if ( xhr.status >= 200 && xhr.status < 300 ) { section.outerHTML = slidifyMarkdown( xhr.responseText, { separator: section.getAttribute( 'data-separator' ), verticalSeparator: section.getAttribute( 'data-vertical' ), notesSeparator: section.getAttribute( 'data-notes' ), attributes: getForwardedAttributes( section ) }); } else { section.outerHTML = '<section data-state="alert">' + 'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' + 'Check your browser\'s JavaScript console for more details.' + '<p>Remember that you need to serve the presentation HTML from a HTTP server.</p>' + '</section>'; } } }; xhr.open( 'GET', url, false ); try { xhr.send(); } catch ( e ) { alert( 'Failed to get the Markdown file ' + url + '. Make sure that the presentation and the file are served by a HTTP server and the file can be found there. ' + e ); } } else if( section.getAttribute( 'data-separator' ) ) { section.outerHTML = slidifyMarkdown( getMarkdownFromSlide( section ), { separator: section.getAttribute( 'data-separator' ), verticalSeparator: section.getAttribute( 'data-vertical' ), notesSeparator: section.getAttribute( 'data-notes' ), attributes: getForwardedAttributes( section ) }); } } } function convertMarkdownToHTML() { var sections = document.querySelectorAll( '[data-markdown]'); for( var i = 0, len = sections.length; i < len; i++ ) { var section = sections[i]; var notes = section.querySelector( 'aside.notes' ); var markdown = getMarkdownFromSlide( section ); section.innerHTML = marked( markdown ); // If there were notes, we need to re-add them after // having overwritten the section's HTML if( notes ) { section.appendChild( notes ); } } } loadExternalMarkdown(); convertMarkdownToHTML(); })();
'use strict'; var app = require('../../app'); var request = require('supertest'); var newExpense; describe('Expense API:', function() { describe('GET /api/expenses', function() { var expenses; beforeEach(function(done) { request(app) .get('/api/expenses') .expect(200) .expect('Content-Type', /json/) .end(function(err, res) { if (err) { return done(err); } expenses = res.body; done(); }); }); it('should respond with JSON array', function() { expenses.should.be.instanceOf(Array); }); }); describe('POST /api/expenses', function() { beforeEach(function(done) { request(app) .post('/api/expenses') .send({ name: 'New Expense', info: 'This is the brand new expense!!!' }) .expect(201) .expect('Content-Type', /json/) .end(function(err, res) { if (err) { return done(err); } newExpense = res.body; done(); }); }); it('should respond with the newly created expense', function() { newExpense.name.should.equal('New Expense'); newExpense.info.should.equal('This is the brand new expense!!!'); }); }); describe('GET /api/expenses/:id', function() { var expense; beforeEach(function(done) { request(app) .get('/api/expenses/' + newExpense._id) .expect(200) .expect('Content-Type', /json/) .end(function(err, res) { if (err) { return done(err); } expense = res.body; done(); }); }); afterEach(function() { expense = {}; }); it('should respond with the requested expense', function() { expense.name.should.equal('New Expense'); expense.info.should.equal('This is the brand new expense!!!'); }); }); describe('PUT /api/expenses/:id', function() { var updatedExpense beforeEach(function(done) { request(app) .put('/api/expenses/' + newExpense._id) .send({ name: 'Updated Expense', info: 'This is the updated expense!!!' }) .expect(200) .expect('Content-Type', /json/) .end(function(err, res) { if (err) { return done(err); } updatedExpense = res.body; done(); }); }); afterEach(function() { updatedExpense = {}; }); it('should respond with the updated expense', function() { updatedExpense.name.should.equal('Updated Expense'); updatedExpense.info.should.equal('This is the updated expense!!!'); }); }); describe('DELETE /api/expenses/:id', function() { it('should respond with 204 on successful removal', function(done) { request(app) .delete('/api/expenses/' + newExpense._id) .expect(204) .end(function(err, res) { if (err) { return done(err); } done(); }); }); it('should respond with 404 when expense does not exist', function(done) { request(app) .delete('/api/expenses/' + newExpense._id) .expect(404) .end(function(err, res) { if (err) { return done(err); } done(); }); }); }); });
import Ember from 'ember'; import config from './config/environment'; var Router = Ember.Router.extend({ location: config.locationType }); Router.map(function() { this.resource('items', function() { this.route('new'); this.resource('item', { path: '/:item_id' }); }); }); export default Router;
module.exports = (() => { 'use strict'; return { write(buffer, value, offset) { return buffer.writeInt16BE(value, offset); }, read(buffer, offset) { return buffer.readInt16BE(offset); }, getByteLength(value) { return 2; }, getName() { return 'int16'; } }; })();
import { isNumber, isPlainObject, isFunction, isString, isArray, toggle, isEmptyString, checkNumberLength, isEmail, isPhone, formatDate, arrayMax } from '../src/index'; describe('isNumber', () => { it('returns false if input is not a number', () => { expect( isNumber([]) ).toEqual(false) }); it('returns true if input is a number', () => { expect( isNumber(100) ).toEqual(true); }); }); describe('isPlainObject', () => { it('should return false if input is not a plain object', () => { expect( isPlainObject([]) ).toEqual(false) }); it('should return true if input is a plain object', () => { expect( isPlainObject({}) ).toEqual(true) }); }); describe('isFunction', () => { it('should return false if input is not a function', () => { expect( isFunction('hello world') ).toEqual(false) }); it('should return true if input is a function', () => { expect( isFunction(() => { }) ).toEqual(true) }); }); describe('isString', () => { it('should return false if input is not a string', () => { expect( isString({hello: 'world'}) ).toEqual(false) }); it('should return true if input is a string', () => { expect( isString('hello') ).toEqual(true) }); }); describe('isArray', () => { it('should return false if input is not an array', () => { expect( isArray({hello: 'world'}) ).toEqual(false) }); it('should return true if input is an array', () => { expect( isArray([]) ).toEqual(true) }); }); describe('toggle', () => { it('should throw when not defining trigger and element', () => { expect(() => { toggle({}) }).toThrow(Error) }) it('should throw when complete is not a function', () => { expect(() => { toggle({element: 'div', complete: ''}) }).toThrow(Error); }) it('should throw if argument given is not an object', () => { expect(() => { toggle('') }).toThrow(Error); }) }) describe('isEmptyString', () => { it('should return true when input is empty', () => { expect( isEmptyString('test') ).toEqual(false) }) }) describe('checkNumberLength', () => { it('should return false if input length is higher than set max length', () => { expect( checkNumberLength('123456789', 8) ).toEqual(false) }) }) describe('isEmail', () => { it('should return false if does not match', () => { expect( isEmail('hell.com') ).toEqual(false) }); it('should return true if it matches regex', () => { expect( isEmail('oyvind@ludensreklame.no') ).toEqual(true) }); }); describe('isPhone', () => { it('should return false if does not match', () => { expect( isPhone('232323') ).toEqual(false) }); it('should return true if it matches regex', () => { expect( isPhone(12345678) ).toEqual(true) }); }); describe('formatDate', () => { it('should return correct output', () => { const now = new Date(); expect( formatDate(now) ).toEqual(formatDate(now)) }); }); describe('arrayMax', () => { it('should return the heighest number in given array', () => { expect( arrayMax([1, 2, 300, 100, 10]) ).toEqual(300); }) })
'use strict' const multibase = require('multibase') const { cidToString } = require('../../../utils/cid') module.exports = { command: 'links <key>', describe: 'Outputs the links pointed to by the specified object', builder: { 'cid-base': { describe: 'Number base to display CIDs in. Note: specifying a CID base for v0 CIDs will have no effect.', type: 'string', choices: multibase.names } }, handler ({ getIpfs, print, key, cidBase, resolve }) { resolve((async () => { const ipfs = await getIpfs() const links = await ipfs.object.links(key, { enc: 'base58' }) links.forEach((link) => { const cidStr = cidToString(link.Hash, { base: cidBase, upgrade: false }) print(`${cidStr} ${link.Tsize} ${link.Name}`) }) })()) } }
var Exit = Class.create(Brick, { initialize: function($super) { $super(); this.isDraggable = false; this.isRemoveable = false; this.isInFront = false; this.hasShadow = false; }, drawShape: function(context) { var checkerBoardSize = 5, checkerSize = Brick.SIZE / checkerBoardSize, counter = 0, i, j; for (i = 0; i < checkerBoardSize; i++) { for (j = 0; j < checkerBoardSize; j++) { if (counter % 2 === 0) { context.fillRect(checkerSize * j, checkerSize * i, checkerSize, checkerSize); } counter++; } } }, createShapes: function(body) { var shapeDefinition = new b2PolygonDef(); shapeDefinition.vertexCount = 4; shapeDefinition.restitution = 0; shapeDefinition.friction = 0.9; shapeDefinition.vertices[0].Set(0.3, 0.3); shapeDefinition.vertices[1].Set(-0.3, 0.3); shapeDefinition.vertices[2].Set(-0.3, -0.3); shapeDefinition.vertices[3].Set(0.3, -0.3); shapeDefinition.isSensor = true; body.CreateShape(shapeDefinition); var myScope = this; body.onCollision = function(contact) { myScope.onCollision(contact); }; }, onCollision: function(contact) { if (contact.shape1.GetBody().ballInstance || contact.shape2.GetBody().ballInstance) { this.parent.parent.onBallExit(); if (this.parent.trackLength && this.parent.bricks.length > 2) { this.parent.validTrack = true; $('publishButton').addClassName('activePublish'); $('publishButtonWarning').style.visibility = "hidden"; } } }, rotate: function() { return; } }); Exit.prototype.type = "Exit";
var searchData= [ ['handle_165',['handle',['../classfly_1_1net_1_1detail_1_1_base_socket.html#a7b7c69b085673b626119eb8fbc87da15',1,'fly::net::detail::BaseSocket::handle()'],['../classfly_1_1net_1_1_listen_socket.html#a7b7c69b085673b626119eb8fbc87da15',1,'fly::net::ListenSocket::handle()'],['../classfly_1_1net_1_1_tcp_socket.html#a7b7c69b085673b626119eb8fbc87da15',1,'fly::net::TcpSocket::handle()'],['../classfly_1_1net_1_1_udp_socket.html#a7b7c69b085673b626119eb8fbc87da15',1,'fly::net::UdpSocket::handle()']]], ['has_5ferror_166',['has_error',['../classfly_1_1detail_1_1_basic_format_parse_context.html#a5bbe8729ba852013ab40344ed7757f4a',1,'fly::detail::BasicFormatParseContext']]], ['hash_3c_20fly_3a_3ajson_20_3e_167',['hash&lt; fly::Json &gt;',['../structstd_1_1hash_3_01fly_1_1_json_01_4.html',1,'std']]], ['header_168',['header',['../classfly_1_1_bit_stream_reader.html#ae94a974ec686bffc6dd7a91d0b1cf2dc',1,'fly::BitStreamReader']]], ['host_5forder_169',['host_order',['../classfly_1_1net_1_1_i_pv4_address.html#a1d0ec2ac0277e767ed2d9b69a39f0ed0',1,'fly::net::IPv4Address']]], ['hostname_5fto_5faddress_170',['hostname_to_address',['../classfly_1_1net_1_1_udp_socket.html#a9b1fab0441484dec8a46cb5f40401e5c',1,'fly::net::UdpSocket::hostname_to_address()'],['../classfly_1_1net_1_1_tcp_socket.html#a9b1fab0441484dec8a46cb5f40401e5c',1,'fly::net::TcpSocket::hostname_to_address()'],['../classfly_1_1net_1_1detail_1_1_base_socket.html#a9b1fab0441484dec8a46cb5f40401e5c',1,'fly::net::detail::BaseSocket::hostname_to_address()']]], ['huffman_5fencoder_5fchunk_5fsize_171',['huffman_encoder_chunk_size',['../classfly_1_1coders_1_1_coder_config.html#a2b08b99b14cfc04082ae858895235f4f',1,'fly::coders::CoderConfig']]], ['huffman_5fencoder_5fmax_5fcode_5flength_172',['huffman_encoder_max_code_length',['../classfly_1_1coders_1_1_coder_config.html#a46fb539c53da77af972e89466659f635',1,'fly::coders::CoderConfig']]], ['huffmancode_173',['HuffmanCode',['../structfly_1_1coders_1_1_huffman_code.html',1,'fly::coders::HuffmanCode'],['../structfly_1_1coders_1_1_huffman_code.html#ab5f9bbe661705633a2f20fb56bbb42d2',1,'fly::coders::HuffmanCode::HuffmanCode() noexcept'],['../structfly_1_1coders_1_1_huffman_code.html#a0ff8c030a228cb6b4a524e366a7ae555',1,'fly::coders::HuffmanCode::HuffmanCode(symbol_type symbol, code_type code, length_type length) noexcept'],['../structfly_1_1coders_1_1_huffman_code.html#a078860559bf39a783bab03fb8f6b2485',1,'fly::coders::HuffmanCode::HuffmanCode(HuffmanCode &amp;&amp;code) noexcept']]], ['huffmandecoder_174',['HuffmanDecoder',['../classfly_1_1coders_1_1_huffman_decoder.html',1,'fly::coders::HuffmanDecoder'],['../classfly_1_1coders_1_1_huffman_decoder.html#af4ce3b54ab518dd6db4dbe10d5381360',1,'fly::coders::HuffmanDecoder::HuffmanDecoder()']]], ['huffmanencoder_175',['HuffmanEncoder',['../classfly_1_1coders_1_1_huffman_encoder.html',1,'fly::coders::HuffmanEncoder'],['../classfly_1_1coders_1_1_huffman_encoder.html#af4e3279e0e4f109d05b22a7585c6b974',1,'fly::coders::HuffmanEncoder::HuffmanEncoder()']]], ['huffmannode_176',['HuffmanNode',['../structfly_1_1coders_1_1_huffman_node.html',1,'fly::coders::HuffmanNode'],['../structfly_1_1coders_1_1_huffman_node.html#ac48e1849ce9969416c01b771e20ed3ce',1,'fly::coders::HuffmanNode::HuffmanNode()']]], ['huffmannodecomparator_177',['HuffmanNodeComparator',['../structfly_1_1coders_1_1_huffman_node_comparator.html',1,'fly::coders']]] ];
import user from './user'; import auth from './auth'; export default { ...user, ...auth };