code
stringlengths
2
1.05M
'use strict'; exports.foobar = 'yadan';
export default { isLoading: true, stream: null, streams: {}, ui: { isOtherChatActive: false, chatSize: localStorage ? Number(localStorage.getItem('chatSize')) || 400 : 400, }, self: { isLoggedIn: false, profile: { err: null, isFetching: false, data: null, }, }, users: [], };
import config from './config' import * as data from './data' export default { name: "mk-app-stock-type-card-test", version: "1.0.0", description: "mk-app-stock-type-card-test", meta: data.getMeta(), components: [], config: config, load: (cb) => { require.ensure([], require => { cb(require('./component'), require('./action'), require('./reducer')) }, "mk-app-stock-type-card-test") } }
var Element=(function(){ function Element(element){ this._construct(element); }; ClassUtil.extend(Element,EventDispatcher); ClassUtil.implement(Element,IElement); var prototype= { _element:null, _construct:function(element){ this._element = element; }, getElement:function(){ return this._element?this._element:this._element=document.createElement("DIV"); }, getY : function(node) { return Number(node?node:this.getElement().style.top.replace("px", "")); }, getX : function(node) { return Number(node?node:this.getElement().style.left.replace("px", "")); } }; ClassUtil.proto(Element,prototype); return Element; })();
System.register(['angular2/core', 'angular2/router', './classroom.service'], function(exports_1, context_1) { "use strict"; var __moduleName = context_1 && context_1.id; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1, router_1, classroom_service_1; var StudentJoinComponent; return { setters:[ function (core_1_1) { core_1 = core_1_1; }, function (router_1_1) { router_1 = router_1_1; }, function (classroom_service_1_1) { classroom_service_1 = classroom_service_1_1; }], execute: function() { StudentJoinComponent = (function () { function StudentJoinComponent(_router, _classroomService) { this._router = _router; this._classroomService = _classroomService; this.errorCodeState = this._classroomService.getErrorState(); // end of constructor } StudentJoinComponent.prototype.submitSecretCode = function (secretCode) { console.log("submit secret code"); this._classroomService.submitSecretCode(secretCode); // if (this._classroomService.correctSecretCode) { // this._router.navigate(['Student-dashboard']); // } else { // // don't let them pass through // // inform user that the code is wrong and ask the instructor for the code // // red box focus console.log(this.errorCodeState); // } }; StudentJoinComponent = __decorate([ core_1.Component({ selector: 'student-join', styles: ["\n .chicken {\n }\n "], template: "\n <menu title=\"Angular2\" class=\"ui fluid one item menu navPanel\">\n <a class=\"item navHeader\">Ready</a>\n </menu>\n <div class=\"contentBody\">\n <input type=\"text\" [(ngModel)]=\"inputValue\" placeholder=\"Enter Secret Code\" autocomplete=\"off\" required autofocus />\n <button [disabled]=\"!inputValue\" class=\"ui button wideButton\" (click)=\"submitSecretCode(inputValue)\">LET'S GO!</button>\n <div *ngIf=\"errorCodeState.secretCodeError\">\n <p class=\"paragraphText ui\">KEEP GUESSING OR STARE AT YOUR INSTRUCTOR FOR THE SECRET CODE </p>\n </div>\n </div>\n ", }), __metadata('design:paramtypes', [router_1.Router, classroom_service_1.ClassroomService]) ], StudentJoinComponent); return StudentJoinComponent; }()); exports_1("StudentJoinComponent", StudentJoinComponent); } } }); //# sourceMappingURL=student-join.component.js.map
$(document).ready(function(){ var isUeReady = false; //ueditor编辑器是否初始化完成 var $btn_publish = $('#btn_publish'); //按钮发布 var $btn_draft = $('#btn_draft'); //按钮暂存 var $btn_preview = $('#btn_preview'); //按钮预览 $btn_publish.attr('disabled','disabled'); $btn_draft.attr('disabled','disabled'); $btn_preview.attr('disabled','disabled'); var $form = $('#form'); window.commonTools.initBSFileInput($('#input_appendix')); //实例化ueditor编辑器 var ue = UE.getEditor('container'); //初始化完成后,解除按钮禁用状态 ue.ready(function(){ isUeReady = true; $btn_publish.attr('disabled',false); $btn_draft.attr('disabled',false); $btn_preview.attr('disabled',false); }); //发布 $btn_publish.click(function(){ if(!$(this).attr('disabled')) { if(checkValidation()) { //此处提交数据,提交成功后,返回上级页面 window.location.href='operate-orgstar.html'; } } else { toastr.warning('富文本编辑器未初始化完成,请稍等...'); } }); //暂存 $btn_draft.click(function(){ if(!$(this).attr('disabled')) { if(checkValidation()) { //此处提交数据,提交成功后,弹出如下提示 toastr.success('您编辑的内容已暂存'); } } else { toastr.warning('富文本编辑器未初始化完成,请稍等...'); } }); //预览 $btn_preview.click(function(){ if(!$(this).attr('disabled')) { if(checkValidation()) { //取图片地址,如空,取默认图片 var logoUrl = commonTools.getFilePath($("#input_appendix")); if(logoUrl == '' || !logoUrl) logoUrl = '../images/rcs-empty.jpg'; //获取专业领域内容 var field_1 = $('#field_1').val(); var field_2 = $('#field_2').val(); var field_3 = $('#field_3').val(); field_1 = field_1.length == 0 ? '' : field_1 + ','; field_2 = field_2.length == 0 ? '' : field_2 + ','; var fields = field_1 + field_2 + field_3; var fields_info = '<div class="org-li-info">企业领域:' + field_1 + field_2 + field_3 + '</div>'; if(fields.length == 0) { fields_info = ''; } var htmlStr = '<div class="row-space-common">' + '<div class="row">' + '<div class="col-xs-12">' + '<div class="org-li static">' + '<div class="org-li-img">' + '<img src="' + logoUrl + '">' + '</div>' + '<div class="org-li-content">' + '<div class="org-li-title">' + $('#orgname').val() + '</div>' + '<div class="org-li-info">企业行业:' + $('#industry').val() + '</div>' + fields_info + '</div>' + '</div>' + '</div>' + '<div class="col-xs-12">' + '<div class="section-title">' + '<div class="section-title-icon"></div>' + '<div class="section-title-text">企业详情介绍</div>' + '</div>' + '<div class="article-content">' + ue.getContent() + '</div>' + '</div>' + '</div>' + '</div>'; BSModal.confirm({ title : '预览', content : htmlStr, width : '90%', btnOK : '确定', btnCancel : '', maxHeight: '450px' }); } } else { toastr.warning('富文本编辑器未初始化完成,请稍等...'); } }); $form.bootstrapValidator({ fields: { industry: { message: '企业行业验证失败', validators: { notEmpty: { message: '请输入企业行业' } } }, orgname: { message: '企业名称验证失败', validators: { notEmpty: { message: '请输入企业名称' } } } } }); //判断必填项是否都已填入内容 function checkValidation() { if(ue.getContent().length == 0) { toastr.warning('请输入编辑内容'); return false; } else { var bsValidator = $form.data('bootstrapValidator'); bsValidator.validate(); var result = bsValidator.isValid(); if(!result) { toastr.warning('您输入的表单信息验证未通过'); } return result; } } });
"use strict"; const extend = require( 'extend' ); const util = require( 'util' ); class PluginTags { static onHandleTag( ev ) { ev.data.tag.forEach( function( item ) { if ( ( item.access === null ) && ( item.name[ item.name.length - 1 ] === '_' ) ) { item.access = 'private'; } } ); } }; module.exports = PluginTags;
module.exports = { path: 'centered', getComponent(nextState, cb) { require.ensure([], (require) => { cb(null, require('./components/Centered')); }); } };
(function(){ 'use strict'; var _ = require('lodash'); var PrivateMatch = function() { this.waitingText = null; this.dots = 0; this.nextDot = 0; }; PrivateMatch.prototype.create = function() { this.game.socketHandler.startPrivateMatch(); this.game.stage.backgroundColor = '#C8F7C5'; this.sendLinkText = this.add.text( this.world.centerX, this.world.centerY - 150, 'Send this link to your opponent:', { font: '45pt hallo_sansblack', fill: '#e67e22', align: 'center' } ); this.sendLinkText.anchor.setTo(0.5, 0.5); this.waitingText = this.add.text( -999, this.world.centerY+250, 'Waiting for a player to join', { font: '30pt hallo_sansblack', fill: '#f1c40f', align: 'center' } ); // Can't anchor it as it would move around when the dots are added to its string. this.waitingText.x = this.world.width/2 - this.waitingText.width/2; this.matchInput = document.querySelector('#match-input'); this.matchInput.style.display = 'inline'; this.matchInput.focus(); this.smallMenuButton = this.add.button(this.world.centerX, this.world.centerY+170, 'menuButton', this.startMenu, this, 1, 0, 0); this.smallMenuButton.scale.setTo(0.6, 0,6); this.smallMenuButton.anchor.setTo(0.5, 0.5); }; PrivateMatch.prototype.setLink = function(matchID) { window.location.hash = matchID; this.matchInput.value = window.location.href; }; PrivateMatch.prototype.update = function() { if (this.time.now > this.nextDot) { if (this.dots === 3) { this.dots = 0; } this.dots++; var dotString = ''; for (var i = 0; i < this.dots; i++) { dotString += '.'; } this.waitingText.setText('Waiting for a player to join' + dotString); this.nextDot = this.time.now + 500; } }; PrivateMatch.prototype.shutdown = function() { this.matchInput.style.display = 'none'; }; PrivateMatch.prototype.startMenu = function() { this.game.socketHandler.stopPrivateMatch(); window.location.hash = ''; this.game.state.start('Menu'); }; module.exports = PrivateMatch; })();
/** * This file includes the required ext-all js and css files based upon "theme" and "direction" * url parameters. It first searches for these parameters on the page url, and if they * are not found there, it looks for them on the script tag src query string. * For example, to include the neptune flavor of ext from an index page in a subdirectory * of extjs/examples/: * <script type="text/javascript" src="../../examples/shared/include-ext.js?theme=neptune"></script> */ (function() { function getQueryParam(name) { var regex = RegExp('[?&]' + name + '=([^&]*)'); var match = regex.exec(location.search) || regex.exec(path); return match && decodeURIComponent(match[1]); } function hasOption(opt, queryString) { var s = queryString || location.search; var re = new RegExp('(?:^|[&?])' + opt + '(?:[=]([^&]*))?(?:$|[&])', 'i'); var m = re.exec(s); return m ? (m[1] === undefined || m[1] === '' ? true : m[1]) : false; } function getCookieValue(name){ var cookies = document.cookie.split('; '), i = cookies.length, cookie, value; while(i--) { cookie = cookies[i].split('='); if (cookie[0] === name) { value = cookie[1]; } } return value; } var scriptEls = document.getElementsByTagName('script'), path = scriptEls[scriptEls.length - 1].src, rtl = getQueryParam('rtl'), theme = getQueryParam('theme') || 'neptune', includeCSS = !hasOption('nocss', path), neptune = (theme === 'neptune'), repoDevMode = getCookieValue('ExtRepoDevMode'), suffix = [], i = 3, neptunePath; rtl = rtl && rtl.toString() === 'true' while (i--) { path = path.substring(0, path.lastIndexOf('/')); } if (theme && theme !== 'classic') { suffix.push(theme); } if (rtl) { suffix.push('rtl'); } suffix = (suffix.length) ? ('-' + suffix.join('-')) : ''; if (includeCSS) { document.write('<link rel="stylesheet" type="text/css" href="' + path + '/resources/css/ext-all' + suffix + '-debug.css"/>'); } document.write('<script type="text/javascript" src="' + path + '/ext-all-debug-w-comments' + (rtl ? '-rtl' : '') + '.js"></script>'); if (neptune) { // since document.write('<script>') does not block execution in IE, we need to // makes sure we prevent ext-theme-neptune.js from executing before ext-all.js // normally this can be done using the defer attribute on the script tag, however // this method does not work in IE when in repoDevMode. It seems the reason for // this is because in repoDevMode ext-all.js is simply a script that loads other // scripts and so Ext is still undefined when the neptune overrides are executed. // To work around this we use the _beforereadyhandler hook to load the neptune // overrides dynamically after Ext has been defined. neptunePath = (repoDevMode ? path + '/..' : path) + '/packages/ext-theme-neptune/build/ext-theme-neptune' + (repoDevMode ? '-dev' : '') + '.js'; if (repoDevMode && window.ActiveXObject) { Ext = { _beforereadyhandler: function() { Ext.Loader.loadScript({ url: neptunePath }); } }; } else { document.write('<script type="text/javascript" src="' + neptunePath + '" defer></script>'); } } })();
// flow-typed signature: 4c4d15d7be5e11edd59bb9e69070cf20 // flow-typed version: <<STUB>>/@babel/cli_v^7.12.10/flow_v0.143.1 /** * This is an autogenerated libdef stub for: * * '@babel/cli' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module '@babel/cli' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module '@babel/cli/bin/babel-external-helpers' { declare module.exports: any; } declare module '@babel/cli/bin/babel' { declare module.exports: any; } declare module '@babel/cli/lib/babel-external-helpers' { declare module.exports: any; } declare module '@babel/cli/lib/babel/dir' { declare module.exports: any; } declare module '@babel/cli/lib/babel/file' { declare module.exports: any; } declare module '@babel/cli/lib/babel' { declare module.exports: any; } declare module '@babel/cli/lib/babel/options' { declare module.exports: any; } declare module '@babel/cli/lib/babel/util' { declare module.exports: any; } // Filename aliases declare module '@babel/cli/bin/babel-external-helpers.js' { declare module.exports: $Exports<'@babel/cli/bin/babel-external-helpers'>; } declare module '@babel/cli/bin/babel.js' { declare module.exports: $Exports<'@babel/cli/bin/babel'>; } declare module '@babel/cli/index' { declare module.exports: $Exports<'@babel/cli'>; } declare module '@babel/cli/index.js' { declare module.exports: $Exports<'@babel/cli'>; } declare module '@babel/cli/lib/babel-external-helpers.js' { declare module.exports: $Exports<'@babel/cli/lib/babel-external-helpers'>; } declare module '@babel/cli/lib/babel/dir.js' { declare module.exports: $Exports<'@babel/cli/lib/babel/dir'>; } declare module '@babel/cli/lib/babel/file.js' { declare module.exports: $Exports<'@babel/cli/lib/babel/file'>; } declare module '@babel/cli/lib/babel/index' { declare module.exports: $Exports<'@babel/cli/lib/babel'>; } declare module '@babel/cli/lib/babel/index.js' { declare module.exports: $Exports<'@babel/cli/lib/babel'>; } declare module '@babel/cli/lib/babel/options.js' { declare module.exports: $Exports<'@babel/cli/lib/babel/options'>; } declare module '@babel/cli/lib/babel/util.js' { declare module.exports: $Exports<'@babel/cli/lib/babel/util'>; }
var searchData= [ ['macierz',['Macierz',['../class_macierz.html',1,'']]], ['macierz_2ecpp',['macierz.cpp',['../macierz_8cpp.html',1,'']]], ['macierz_2ehh',['macierz.hh',['../macierz_8hh.html',1,'']]], ['main',['main',['../main_8cpp.html#ae66f6b31b5ad750f1fe042a706a4e3d4',1,'main.cpp']]], ['main_2ecpp',['main.cpp',['../main_8cpp.html',1,'']]] ];
//Part of the DuskWolf engine //Licensed under the MIT license, see COPYING.txt for details "use strict"; load.provide("test", function() { /** This is a namespace that allows tests to be ran. * @since 0.0.20-alpha * @namespace * @alias test */ var test = {}; /** The currently running test package, should be set at the top of every testing package. * @type string */ test.package = ""; /** The test results, as an object, where each key is a package name, and each key of each * package is a test name. The result is a boolean which says whether the test passed or not. * @type object */ test.results = {}; /** Whether to invoke the debugger if a test fails. * @type boolean */ test.debug = false; /** An array of all testing functions. Each value is a pair of `[packageName, function]` * @type array * @private * @since 0.0.21-alpha */ var _tests = []; /** Loads a dependancy file that contains only tests. This will be used with `{@link test.testAll}` * to run all the tests. * @param {string} url The url of the file. * @return {Promise()} A promise that fullfills when downloading is complete. */ test.loadTests = function(url) { return load.importList(url).then(function(data) { var importl = []; for(var i = data.packages.length-1; i >= 0; i--) { importl.push(load.import(data.packages[i][1][0])); } return Promise.all(importl); }); }; /** Registers a function as a test; it will be called when tests are ran. * @param {string} pack The package name of the test function. * @param {function():undefined} test The test function. */ test.registerTestFunction = function(pack, test) { _tests.push([pack, test]); }; /** Calls all testing functions; running all tests. * @since 0.0.21-alpha */ test.testAll = function() { console.log("%cStarting tests", "color:#005500"); var pArr = []; var testers = []; for(var i = _tests.length-1; i >= 0; i --){ var tester = new test.Tester(_tests[i][0]); try { pArr.push(_tests[i][1](tester)); }catch(e){ tester.except(e); } testers.push(tester); } Promise.all(pArr).then(function(outputs) { var pass = true; for(var i = 0; i < testers.length; i ++) { if(testers[i].failed) { pass = false; } } if(pass) { console.log("%cAll tests passed!", "color:#005500"); }else{ console.log("%cSome tests failed...", "color:#770000"); } }, function(e) { console.log("%cSome tests failed...", "color:#770000"); }); }; /** Calls `{@link test.loadTests}` followed by `{@link test.testAll}`. * * @param {string} url The url of the deps file for the tests. * @since 0.0.21-alpha */ test.loadAndTestAll = function(url) { test.loadTests(url).then(test.testAll); } /** A test runner * @memberof test */ class Tester { /** Creates a new test runner * * @param {string} pack The package name to test */ constructor(pack) { /** The package name * @type string * @memberof! test.Tester# */ this.package = pack; /** Whether the test has failed or not * @type boolean * @memberof! test.Tester# */ this.failed = false; } /** Starts running a test, it is assumed it passes unless it explictly fails. * @param {string} name The name of the test. */ start(name) { if(!(this.package in test.results)) test.results[this.package] = {}; console.log("%c"+this.package, "color:#999999", name); test.results[this.package][name] = true; this._current = name; } /** Fails a test, with the given reason. * @param {string} reason The reason for failure. * @param {function()} reject If it fails, this function will be called with the reason. */ fail(reason, reject) { if(this._current) { test.results[this.package][this._current] = false; console.error("***** Test '"+this._current+"' of "+this.package+" failed!"); console.error(reason); }else { console.error("***** Package "+this.package+" failed before reaching a package!"); console.error(reason); } this.failed = true; if(test.debug) debugger; if(reject) reject(reason); } /** If an exception happens somewhere (from whatever is running the tests), feed it to this. * @param {Error} e The exception. */ except(e) { console.error("***** Package "+this.package+" threw a "+e.name+"!"); console.error(e); this.failed = true; if(test.debug) debugger; } /** Fails the test if the assertion that the arguments are equal fails. * @param {*} a The first object. * @param {*} b The second object. * @param {function()} reject If it fails, this function will be called with the reason. */ assertEqual(a, b, reject) { if(!_equals(a, b)) { this.fail("Assertion "+a+" = "+b+" failed.", reject); } } /** Fails the test if the assertion that the arguments are not equal fails. * @param {*} a The first object. * @param {*} b The second object. * @param {function()} reject If it fails, this function will be called with the reason. */ assertNotEqual(a, b, reject) { if(_equals(a, b)) { this.fail("Assertion "+a+" != "+b+" failed.", reject); } } /** Fails the test if the assertion that the argument is not null or undefined fails. * @param {*} a The object to check. * @param {function()} reject If it fails, this function will be called with the reason. */ assertExists(a, reject) { if(a === undefined || a === null) { this.fail("Assertion "+a+" exists failed.", reject); } } /** Fails the test if the assertion that the argument is not null or undefined fails. * @param {*} a The object to check. * @param {function()} reject If it fails, this function will be called with the reason. * @since 0.0.21-alpha */ assertNotExists(a, reject) { if(!(a === undefined || a === null)) { this.fail("Assertion "+a+" does not exist failed.", reject); } } /** Fails the test if the assertion that the argument is true fails. * @param {*} a The object to check. * @param {function()} reject If it fails, this function will be called with the reason. */ assertTrue(a, reject) { if(!a) { this.fail("Assertion "+a+" is true failed.", reject); } } /** Fails the test if the assertion that the argument is false fails. * @param {*} a The object to check. * @param {function()} reject If it fails, this function will be called with the reason. */ assertFalse(a, reject) { if(a) { this.fail("Assertion "+a+" is false failed.", reject); } } } test.Tester = Tester; /** Returns true if the two arguments are equal, this works intuitivley, and compares the elements * for objects and arrays. * @param {*} a The first object. * @param {*} b The second object. * @return {boolean} Whether they are equal. * @private */ var _equals = function(a, b) { if(a == b) return true; if(typeof a != typeof b) return false; if(a instanceof HTMLCanvasElement && b instanceof HTMLCanvasElement) return a.toDataURL() == b.toDataURL(); if(Array.isArray(a) && !Array.isArray(b)) return false; if(!Array.isArray(a) && Array.isArray(b)) return false; if(Array.isArray(a) && Array.isArray(b)) { if(a.length != b.length) return false; for(var i = a.length-1; i >= 0; i --) { if(!_equals(a[i], b[i])) return false; } return true; }else if(typeof a == "object" && typeof b == "object") { if(Object.keys(a).length != Object.keys(b).length) return false; for(var p in a) { if(!_equals(a[p], b[p])) return false; } return true; } return false; }; return test; }, {"alsoSeal":["Tester"]});
var starMadeAdminServices = angular.module('starMadeAdminServices', ['ngResource']); starMadeAdminServices.factory('Api', ['$resource', function($resource){ return $resource( '/app_dev.php/:resourceName/:entityId\.json?apikey=asdasdasd&limit=:limit&offset=:offset&term=:term&order=:order' , {} , { query: { method:'GET' , params:{ resourceName :'' ,entityId:'' ,limit:5 ,offset:0 ,term:'' ,order:'' } , isArray:false } } ); }]);
var unit = require("deadunit/deadunit.browser") var ajax = require('../ajax') var testFileContents = require("raw!./testFile.txt") unit.test(function(t) { this.count(2) ajax('testFile.txt').then(function(response) { t.ok(response.text === testFileContents) }).done() ajax('nonExistantFile.txt').catch(function(e) { t.ok(e.message === "Error in request: Status 400") }).done() }).writeHtml($('body'))
var mongodb = require('mongodb-core'); var each = require('each-series'); var oid = mongodb.BSON.ObjectID.createPk; var cmdkeys = { insert: 'nInserted', delete: 'nRemoved', update: 'nUpserted' }; var Bulk = (function () { function Bulk(colName, ordered, onserver, dbname) { this.colName = colName; this.cmdList = []; this.currCmd = null; this.ordered = ordered; this._onserver = onserver; this.dbName = dbname; } Bulk.prototype.find = function (query) { var self = this; var removeFn = function (lim) { if (!self.currCmd) { self.currCmd = { delete: self.colName, deletes: [], ordered: self.ordered, writeConcern: { w: 1 } }; } if (!self.currCmd.delete) { self.cmdList.push(self.currCmd); self.currCmd = { delete: self.colName, deletes: [], ordered: self.ordered, writeConcern: { w: 1 } }; } self.currCmd.deletes.push({ q: query, limit: lim }); }; var updateFn = function (updObj, multi) { if (!self.currCmd) { self.currCmd = { update: self.colName, updates: [], ordered: self.ordered, writeConcern: { w: 1 } }; } if (!self.currCmd.update) { self.cmdList.push(self.currCmd); self.currCmd = { update: self.colName, updates: [], ordered: self.ordered, writeConcern: { w: 1 } }; } self.currCmd.updates.push({ q: query, u: updObj, multi: multi, upsert: false }); }; var findobj = { remove: function () { removeFn(0); }, removeOne: function () { removeFn(1); }, update: function (updObj) { updateFn(updObj, true); }, updateOne: function (updObj) { updateFn(updObj, false); } }; return findobj; }; Bulk.prototype.insert = function (doc) { if (!this.currCmd) { this.currCmd = { insert: this.colName, documents: [], ordered: this.ordered, writeConcern: { w: 1 } }; } if (!this.currCmd.insert) { this.cmdList.push(this.currCmd); this.currCmd = { insert: this.colName, documents: [], ordered: this.ordered, writeConcern: { w: 1 } }; } if (!doc._id) { doc._id = oid(); } this.currCmd.documents.push(doc); }; Bulk.prototype.tojson = function () { var obj = { nInsertOps: 0, nUpdateOps: 0, nRemoveOps: 0, nBatches: this.cmdList.length }; this.cmdList.forEach(function (cmd) { if (cmd.update) { obj.nUpdateOps += cmd.updates.length; } else if (cmd.insert) { obj.nInsertOps += cmd.documents.length; } else if (cmd.delete) { obj.nRemoveOps += cmd.deletes.length; } }); return obj; }; Bulk.prototype.execute = function (cb) { var self = this; var result = { writeErrors: [], writeConcernErrors: [], nInserted: 0, nUpserted: 0, nMatched: 0, nModified: 0, nRemoved: 0, upserted: [], ok: 0 }; this.cmdList.push(this.currCmd); this._onserver(function (err, server) { if (err) { return cb(err); } each(self.cmdList, function (cmd, i, done) { server.command(self.dbName + '.$cmd', cmd, function (err, res) { if (err) return done(err); result[cmdkeys[Object.keys(cmd)[0]]] += res.result.n; done(); }); }, function (err) { if (err) return cb(err); result.ok = 1; cb(null, result); }); }); }; return Bulk; })(); ; module.exports = Bulk; //# sourceMappingURL=bulk.js.map
version https://git-lfs.github.com/spec/v1 oid sha256:ff4e4975ef403004f8fe8e59008db7ad47f54b10d84c72eb90e728d1ec9157ce size 94020
/*jslint browser: true, node: true */ /*global require, module, describe, it */ "use strict"; var assert = require("assert"); var fs = require('fs'); var nifti = require('../src/nifti.js'); var buf = fs.readFileSync('./tests/data/little.nii.gz'); var data = nifti.Utils.toArrayBuffer(buf); var nifti1 = null; describe('NIFTI-Reader-JS', function () { describe('nifti-1 little endian test', function () { it('isCompressed() should return true', function () { assert.equal(true, nifti.isCompressed(data)); }); it('should not throw error when decompressing', function (done) { assert.doesNotThrow(function() { data = nifti.decompress(data); done(); }); }); it('isNIFTI1() should return true', function () { assert.equal(true, nifti.isNIFTI1(data)); }); it('should not throw error when reading header', function (done) { assert.doesNotThrow(function() { nifti1 = nifti.readHeader(data); done(); }); }); it('numBitsPerVoxel should be 32', function () { assert.equal(32, nifti1.numBitsPerVoxel); }); it('littleEndian should be true', function () { assert.equal(true, nifti1.littleEndian); }); it('dims[1] should be 64', function () { assert.equal(64, nifti1.dims[1]); }); it('dims[2] should be 64', function () { assert.equal(64, nifti1.dims[2]); }); it('dims[3] should be 21', function () { assert.equal(21, nifti1.dims[3]); }); it('image data checksum should equal 4006845507', function () { var imageData = nifti.readImage(nifti1, data); var checksum = nifti.Utils.crc32(new DataView(imageData)); assert.equal(checksum, 4006845507); }); }); });
// Get all subscriptions var config = require('../config'); var utils = require('../utils'); var collection = require('../collections/clients'); module.exports.handler = function(request, reply) { if (config.get('publicList')) { collection .list() .then(function(doc) { reply(doc); }) .catch(function(err) { return reply(utils.formatError('Internal MongoDB error', err)).code( 500 ); }); } else { return reply().code(401); } };
'use strict'; // Use Application configuration module to register a new module ApplicationConfiguration.registerModule('followed');
const gulp = require('gulp'); const sass = require('gulp-sass'); const rename = require('gulp-rename'); const autoprefixer = require('gulp-autoprefixer'); // Cactu scss source const cactuUrl = './scss/**/*.scss'; const docUrl = './_sass/**/*.scss'; const sassOpts = { outputStyle: 'compressed', precison: 3, errLogToConsole: true }; function styles() { return gulp.src(cactuUrl) .pipe(sass({ outputStyle: 'expanded' }).on('error', sass.logError)) .pipe(autoprefixer({ browsers: ['last 2 versions'], cascade: false })) .pipe(gulp.dest('./css')) }; function docStyles() { return gulp.src(docUrl) .pipe(sass(sassOpts).on('error', sass.logError)) .pipe(autoprefixer({ browsers: ['last 2 versions'], cascade: false })) .pipe(rename({ suffix: ".min" })) .pipe(gulp.dest('./assets/css')) } function compressedStyles() { return gulp.src(cactuUrl) .pipe(sass(sassOpts).on('error', sass.logError)) .pipe(autoprefixer({ browsers: ['last 2 versions'], cascade: false })) .pipe(rename({ suffix: ".min" })) .pipe(gulp.dest('./css')) } gulp.task('sass', styles); gulp.task('sass-doc', docStyles); gulp.task('sass-compressed', compressedStyles); gulp.task('cactu-build', gulp.parallel(styles, compressedStyles)); gulp.task('watch', () => { gulp.watch([cactuUrl, docUrl], gulp.series(styles, compressedStyles, docStyles)); });
const moment = require('moment'); const util = require('../core/util'); const _ = require('lodash'); const log = require('../core/log'); const marketData = require('./coinfalcon-markets.json'); const CoinFalcon = require('coinfalcon'); var Trader = function(config) { _.bindAll(this); if (_.isObject(config)) { this.key = config.key; this.secret = config.secret; this.currency = config.currency.toUpperCase(); this.asset = config.asset.toUpperCase(); } this.pair = this.asset + '-' + this.currency; this.name = 'coinfalcon'; this.coinfalcon = new CoinFalcon.Client(this.key, this.secret); }; var recoverableErrors = new RegExp( /(SOCKETTIMEDOUT|TIMEDOUT|CONNRESET|CONNREFUSED|NOTFOUND|429|522)/ ); Trader.prototype.retry = function(method, args, error) { var self = this; // make sure the callback (and any other fn) is bound to Trader _.each(args, function(arg, i) { if (_.isFunction(arg)) { args[i] = _.bind(arg, self); } }); log.debug('[CoinFalcon] ', this.name, "Retrying..."); if (!error || !error.message.match(recoverableErrors)) { log.error('[CoinFalcon] ', this.name, 'returned an irrecoverable error'); _.each(args, function(arg, i) { if (_.isFunction(arg)) { arg(error, null); return; } }); return; } var wait = +moment.duration(5, 'seconds'); // run the failed method again with the same arguments after wait setTimeout(function() { method.apply(self, args); }, wait); }; Trader.prototype.getTicker = function(callback) { var success = function(res) { callback(null, {bid: +res.data.bids[0].price, ask: +res.data.asks[0].price}) }; var failure = function(err) { log.error('[CoinFalcon] error getting ticker', err); callback(err, null); }; var url = "markets/" + this.pair + "/orders?level=1" this.coinfalcon.get(url).then(success).catch(failure); }; Trader.prototype.getFee = function(callback) { var fees = 0.25; // 0.25% for both sell & buy callback(false, fees / 100); }; Trader.prototype.getPortfolio = function(callback) { var success = function(res) { if (_.has(res, 'error')) { var err = new Error(res.error); callback(err, null); } else { var portfolio = res.data.map(function(account) { return { name: account.currency, amount: parseFloat(account.available) } }); callback(null, portfolio); } }; var failure = function(err) { log.error('[CoinFalcon] error getting portfolio', err); callback(err, null); } this.coinfalcon.get('user/accounts').then(success).catch(failure); }; Trader.prototype.addOrder = function(type, amount, price, callback) { var args = _.toArray(arguments); var success = function(res) { if (_.has(res, 'error')) { var err = new Error(res.error); failure(err); } else { callback(false, res.data.id) } }; var failure = function(err) { log.error('[CoinFalcon] unable to ' + type.toLowerCase(), err); return this.retry(this.addOrder, args, err); }.bind(this); var payload = { order_type: type, operation_type: 'limit_order', market: this.pair, size: amount, price: price } this.coinfalcon.post('user/orders', payload).then(success).catch(failure); }; ['buy', 'sell'].map(function(type) { Trader.prototype[type] = function(amount, price, callback) { this.addOrder(type, amount, price, callback); }; }); Trader.prototype.getOrder = function(order, callback) { var success = function(res) { if (_.has(res, 'error')) { var err = new Error(res.error); failure(err); } else { var price = parseFloat(res.data.price); var amount = parseFloat(res.data.size); var date = moment(res.data.created_at); callback(false, { price, amount, date }); } }; var failure = function(err) { log.error('[CoinFalcon] unable to getOrder', err); callback(err, null); }.bind(this); this.coinfalcon.get('user/orders/' + order).then(success).catch(failure); }; Trader.prototype.checkOrder = function(order, callback) { var success = function(res) { if (_.has(res, 'error')) { var err = new Error(res.error); failure(err); } else { var filled = res.data.status == "canceled" || res.data.status == "fulfilled"; callback(false, filled); } }; var failure = function(err) { log.error('[CoinFalcon] unable to checkOrder', err); callback(err, null); }.bind(this); this.coinfalcon.get('user/orders/' + order).then(success).catch(failure); }; Trader.prototype.cancelOrder = function(order, callback) { var args = _.toArray(arguments); var success = function(res) { if (_.has(res, 'error')) { var err = new Error(res.error); failure(err); } else { callback(false, res.data.id) } }; var failure = function(err) { log.error('[CoinFalcon] unable to cancel', err); return this.retry(this.cancelOrder, args, err); }.bind(this); this.coinfalcon.delete('user/orders?id=' + order).then(success).catch(failure); }; Trader.prototype.getTrades = function(since, callback, descending) { var args = _.toArray(arguments); var success = function(res) { var parsedTrades = []; _.each( res.data, function(trade) { parsedTrades.push({ tid: trade.id, date: moment(trade.created_at).unix(), price: parseFloat(trade.price), amount: parseFloat(trade.size), }); }, this ); if (descending) { callback(null, parsedTrades); } else { callback(null, parsedTrades.reverse()); } }.bind(this); var failure = function (err) { err = new Error(err); log.error('[CoinFalcon] error getting trades', err); return this.retry(this.getTrades, args, err); }.bind(this); var url = "markets/" + this.pair + "/trades" if (since) { url += '?since_time=' + (_.isString(since) ? since : since.format()); } this.coinfalcon.get(url).then(success).catch(failure); }; Trader.getCapabilities = function () { return { name: 'CoinFalcon', slug: 'coinfalcon', assets: marketData.assets, currencies: marketData.currencies, markets: marketData.markets, requires: ['key', 'secret'], providesHistory: 'date', providesFullHistory: true, tid: 'tid', tradable: true, forceReorderDelay: false }; } module.exports = Trader;
let QuotesLambdaFunction = require('../obj/src/container/QuotesLambdaFunction').QuotesLambdaFunction; module.exports = new QuotesLambdaFunction().getHandler();
import GoCardless from './GoCardless'; module.exports = GoCardless;
import angular from 'angular'; import getUniqueName from './getUniqueName'; let dependencyMap = new Map(); let defaultModule = angular.module(getUniqueName(), []); export default class DependencyManager { static findImplementation(clazz) { return dependencyMap.get(clazz); } static getDefaultModuleName() { return defaultModule.name; } static bind(iface) { return { to: impl => dependencyMap.set(iface, impl), toValue: val => defaultModule.config(['$provide', x => x.value(iface.$name, val)]) }; } }
require(['js/config'], function(){ require(['jquery'], function($){ function Walker() { var x, y; var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); x = canvas.width/2; y = canvas.height/2; this.display = function(){ ctx.stroke(); ctx.beginPath(); ctx.fillRect(x,y,1,1); ctx.closePath(); }; this.step1 = function(){ var choice = Math.floor( Math.random() * 4); if(choice == 0){ x++; } else if(choice == 1){ x--; } else if(choice == 2){ y++; } else if(choice == 3){ y--; } }; this.step2 = function() { //Yields -1, 0, or 1 var stepx = Math.floor(Math.random() * 3)-1; var stepy = Math.floor(Math.random() * 3)-1; x += stepx; y += stepy; }; this.step3 = function() { var stepx = Math.random() * 2 - 1; var stepy = Math.random() * 2 - 1; x += stepx; y += stepy; }; var currentMousePos = { x: -1, y: -1 }; $(document).mousemove(function(event) { currentMousePos.x = event.pageX; currentMousePos.y = event.pageY; }); this.stepTowardMouse = function(){ var r= Math.random(); dx = currentMousePos.x - x; dy = currentMousePos.y - y; if(r < .5){ var rx = Math.random() * 2 - 1; var ry = Math.random() * 2 - 1; if(0 < rx && rx < (dx / Math.abs(dx + dy))){ x++; } if((dx / Math.abs(dx + dy)) < rx && rx < 0){ x--; } if(0 < ry && ry < (dy / Math.abs(dx + dy))){ y++; } if((dy / Math.abs(dx + dy)) < ry && ry < 0){ y--; } } else { this.step3(); } }; this.stepGaussian = function(){ function rnd_snd() { return (Math.random()*2-1)+(Math.random()*2-1)+(Math.random()*2-1); } function rnd(mean, stdev) { return Math.round(rnd_snd()*stdev+mean); } var stepx = rnd(0, 2); var stepy = rnd(0, 2); x += stepx; y += stepy; }; this.montecarlo = function() { //We do this “forever” until we find a qualifying random value. while (true) { //Pick a random value. var r1 = Math.random(); //Assign a probability. var probability = r1; //Pick a second random value. var r2 = Math.random(); //Does it qualify? If so, we’re done! if (r2 < probability) { return r1; } } }; this.stepMontecarlo = function(){ var stepx = (1 - this.montecarlo())*2; var stepy = this.montecarlo() * 2 - 1; x += stepx; y += stepy; }; this.uniformStepSize = function(){ var stepsize = Math.random() * 10; var stepx = Math.random() * 2 * stepsize - stepsize; var stepy = Math.random() * 2 * stepsize - stepsize; x += stepx; y += stepy; } } var w; function draw(){ //w.uniformStepSize(); w.stepTowardMouse(); w.display(); } w = new Walker(); setInterval(draw, 1); }); });
/* ************************************************************** Copyright 2011 Zoovy, 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. ************************************************************** */ /* An extension for acquiring and displaying 'lists' of categories. The functions here are designed to work with 'reasonable' size lists of categories. //while called 'store_search', these extension is also used in the admin. */ var store_search = function(_app) { var r = { vars : { //a list of the templates used by this extension. //if this is a custom extension and you are loading system extensions (prodlist, etc), then load ALL templates you'll need here. "ajaxRequest" : {}, "universalFilters":[] }, //////////////////////////////////// CALLS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ calls : { /* P is the params object. something like: var P = {} P.mode = 'elastic-search'; P.size = 250; P.filter = { 'and':{ 'filters':[ {'term':{'profile':'E31'}},{'term':{'tags':'IS_SALE'}} ] } } or instead of P.filter, you may have P.query = { 'and':{ 'filters':[ {'term':{'profile':'E31'}},{'term':{'tags':'IS_SALE'}} ] } }; */ appPublicProductSearch : { init : function(obj,tagObj,Q) { // _app.u.dump("BEGIN _app.ext.store_search.calls.appPublicSearch"); var universalFilters = $.extend(true, [], _app.ext.store_search.vars.universalFilters); if(universalFilters.length){ if(obj.filter){ var tmp = obj.filter; obj.filter = { "and" : universalFilters } obj.filter.and.push(tmp); } else if(obj.query){ var tmp = obj.query; obj.query = { "filtered" : { "query" : tmp, "filter" : { "and" : universalFilters } } } } else{ //This is not going to end well, but let's let Elastic tell you that. } } this.dispatch(obj,tagObj,Q) return 1; }, dispatch : function(obj,tagObj,Q) { obj['_cmd'] = "appPublicSearch"; obj.type = 'product'; obj['_tag'] = tagObj; // _app.u.dump(obj); _app.model.addDispatchToQ(obj,Q); } }, //appPublicSearch //no local caching (fetch) of results yet. need to work with the new search a bit // to get a good handle on what datapointers should look like. appPublicSearch : { init : function(obj,tagObj,Q) { var universalFilters = $.extend(true, [], _app.ext.store_search.vars.universalFilters); if(universalFilters.length){ if(obj.filter){ var tmp = obj.filter; obj.filter = { "and" : universalFilters } obj.filter.and.push(tmp); } else if(obj.query){ var tmp = obj.query; obj.query = { "filtered" : { "query" : tmp, "filter" : { "and" : universalFilters } } } } else{ //This is not going to end well, but let's let Elastic tell you that. } } this.dispatch(obj,tagObj,Q) return 1; }, dispatch : function(obj,tagObj,Q) { obj['_cmd'] = "appPublicSearch"; obj['_tag'] = tagObj; // _app.u.dump("BEGIN _app.ext.store_search.calls.appPublicSearch"); // _app.u.dump(obj); _app.model.addDispatchToQ(obj,Q); } } //appPublicSearch }, //calls //////////////////////////////////// CALLBACKS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ callbacks : { //callbacks.init need to return either a true or a false, depending on whether or not the file will execute properly based on store account configuration. Use this for any config or dependencies that need to occur. //the callback is auto-executed as part of the extensions loading process. init : { onSuccess : function() { // _app.u.dump('BEGIN _app.ext.store_navcats.init.onSuccess '); var r = true; //return false if extension won't load for some reason (account config, dependencies, etc). return r; }, onError : function() { //errors will get reported for this callback as part of the extensions loading. This is here for extra error handling purposes. //you may or may not need it. _app.u.dump('BEGIN _app.ext.store_navcats.callbacks.init.onError'); } }, //the request that uses this as a callback should have the following params set for _tag: // parentID, templateID (template used on each item in the results) and datapointer. //the request that uses this as a callback should have the following params set for _tag: // parentID, templateID (template used on each item in the results) and datapointer. handleElasticResults : { onSuccess : function(_rtag) { var L = _app.data[_rtag.datapointer]['_count']; var $list = _rtag.list; if($list && $list.length) { //*** 201336 -> setting data-app-role on the element was a bad idea. it may have already been set and it doesn't appear to get used at all. $list.empty().removeClass('loadingBG'); //.attr('data-app-role','searchResults'); $list.closest('.previewListContainer').find('.resultsHeader').empty().remove(); //remove any previous results multipage headers if(L == 0) { $list.append("Your query returned zero results."); } else { var $parent; if($list.is('tbody')) {$parent = $list.closest('table').parent(); _app.u.dump("LIST is a tbody");} else if($list.is('table')) {$parent = $list.parent();} else {$parent = $list.parent()} //put items into list (most likely a ul or tbody $list.append(_app.ext.store_search.u.getElasticResultsAsJQObject(_rtag)); //prioritize w/ getting product in front of buyer if(_rtag.title) { $list.before("<h2 class='searchHeader'>"+_rtag.title+"</h2>"); } if(_app.ext.admin) { $list.hideLoading(); _app.u.handleAppEvents($parent); } var EQ = $list.data('elastic-query'); //Elastic Query if(EQ) { var _tag = $.extend(true,{},_rtag); //create a copy so original is not modified. delete _tag.pipeUUID; delete _tag.status; //the status would already be 'requesting' or 'completed', which means this request wouldn't run. var $header = _app.ext.store_search.u.buildResultsHeader($list,_rtag.datapointer), //# of results and keyword display. // $sortMenu = _app.ext.store_search.u.buildSortMenu($list,_rtag), //sorting options as ul $pageMenu = _app.ext.store_search.u.buildPagination($list,_tag), //pagination as ul $multipage = _app.ext.store_search.u.buildPaginationButtons($list,_tag), //next/prev buttons $menuContainer = $("<div \/>").addClass('resultsMenuContainer'), //used to hold menus. imp for abs. positioning. $controlsContainer = $("<div \/>").addClass('ui-widget ui-widget-content resultsHeader clearfix ui-corner-bottom'); //used to hold menus and buttons. // $menuContainer.append($sortMenu); //sorting not working. commented out for now. !!! $parent.find(".resultsHeader").remove(); //make sure headers don't stack when using pagination. // ### TODO -> test this. $header.prependTo($parent); //pageMenu will be false if there are no pages. If there's no pagination, no further output is needed. if($pageMenu) { $menuContainer.append($pageMenu); $menuContainer.appendTo($controlsContainer); $multipage.appendTo($controlsContainer); //multipage nav is at the top and bottom $controlsContainer.prependTo($parent); //add to DOM prior to running menu. helps it to not barf. $pageMenu.menu(); // $sortMenu.menu(); } } else { //no error gets thrown here. it is an acceptable use case to display search results w/ no multipage functionality. } } } else { $('#globalMessaging').anymessage({'message':'In store_search.callbacks.handleElasticResults, $list ['+typeof _rtag.list+'] was not defined, not a jquery object ['+(_rtag.list instanceof jQuery)+'] or does not exist ['+_rtag.list.length+'].',gMessage:true}); _app.u.dump("handleElasticResults _rtag.list: "); _app.u.dump(_rtag.list); } //this gets run whether there are results or not. It is the events responsibility to make sure results were returned. // That way, it can handle a no-results action. $list.trigger('listcomplete',_rtag); } } }, //callbacks //////////////////////////////////// UTIL [u] \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ u : { //!!! The header and pagination handling all relies on a query->query_string->query type object. With more complex elastic searches we must add handling //list is the UL or whatever element type contains the list of product. buildResultsHeader : function($list,datapointer,vars) { // _app.u.dump("BEGIN store_search.u.buildMultipageHeader"); vars = vars || {}; var $header = false, //will be a jquery object IF the necesarry data is present. EQ = $list.data('elastic-query'); //Elastic Query if(datapointer && $list && EQ) { $header = $("<div \/>").addClass('ui-widget ui-widget-header resultsHeader clearfix ui-corner-top hideInMinimalMode'); // note - resultsHeader is used to search/replace any existing headers. if(EQ.query && EQ.query.query_string && EQ.query.query_string.query){ $header.text(_app.data[datapointer].hits.total+" Results for: "+EQ.query.query_string.query); } else { $header.text(_app.data[datapointer].hits.total+" Results for your query"); } } else if(!EQ) { _app.u.dump("NOTICE! the search results container did not contain data('elastic-filter') so no multipage data is present.",'warn'); } else if(!$list) { $('#globalMessaging').anymessage({'message':'In store_search.u.buildResultsHeader, no $list object specified','gMessage':true}) } else { $list.parent.anymessage({'message':'In store_search.u.buildResultsHeader, no datapointer specified','gMessage':true}); } return $header; }, buildPaginationButtons : function($list,_rtag) { _app.u.dump("BEGIN store_search.u.buildPaginationButtons"); var $controls, EQ = $list.data('elastic-query'); //Elastic Query // _app.u.dump(" -> EQ: "); _app.u.dump(EQ); if($list && EQ && _rtag && _rtag.datapointer) { // _app.u.dump("EQ: "); _app.u.dump(EQ); var data = _app.data[_rtag.datapointer], //shortcut from = EQ.from || 0, pageInFocus = $list.data('page-in-focus') || 1, //start at 1, not zero, so page 1 = 1 totalPageCount = Math.ceil(data.hits.total / EQ.size) //total # of pages for this list. _app.u.dump(" -> pageInFocus: "+pageInFocus); $controls = $("<div \/>").addClass(''); //SANITY -> the classes on these buttons are used in quickstart. var $prevPageBtn = $("<button \/>").text("Previous Page").button({icons: {primary: "ui-icon-circle-triangle-w"},text: false}).addClass('prevPageButton').on('click.multipagePrev',function(event){ event.preventDefault(); _app.ext.store_search.u.changePage($list,(pageInFocus - 1),_rtag); }); var $nextPageBtn = $("<button \/>").text("Next Page").button({icons: {primary: "ui-icon-circle-triangle-e"},text: false}).addClass('nextPageButton').on('click.multipageNext',function(event){ event.preventDefault(); _app.ext.store_search.u.changePage($list,(pageInFocus + 1),_rtag); }); if(pageInFocus == 1) {$prevPageBtn.button('disable');} else if(totalPageCount == pageInFocus){$nextPageBtn.button('disable')} //!!! disable next button if on last page. else {} $nextPageBtn.appendTo($controls); $prevPageBtn.appendTo($controls); } else if($list) {} //$list is defined but not EQ. do not show errors for this. it may be intentional. else { $('#globalMessaging').anymessage({'message':'In store_search.u.buildPaginationButtons, $list or datapointer not specified','gMessage':true}); } return $controls; }, //add the elastic query as data to the results container so that it can be used for multipage. //this is a function because the code block was duplicated a lot and the query needs to be added in a specific manner //extend is used to create a copy so that further changes to query are not added to DOM (such as _tag which contains this element and causes recursion issues). updateDataOnListElement : function($list,query,pageInFocus) { $list.data('elastic-query',$.extend(true,{},query)); $list.data('page-in-focus',pageInFocus); }, changePage : function($list,newPage,_tag) { if($list && newPage) { var EQ = $list.data('elastic-query'); //Elastic Query // _app.u.dump(" -> newPage: " + newPage); if(EQ) { var query = EQ; // _app.u.dump("EQ:"); // _app.u.dump(EQ); //query.size = EQ.size; //use original size, not what's returned in buildSimple... query.from = (newPage - 1) * EQ.size; //page is passed in, which starts at 1. but elastic starts at 0. _app.ext.store_search.u.updateDataOnListElement($list,query,newPage); _app.ext.store_search.calls.appPublicSearch.init(query,_tag); _app.model.dispatchThis(); } else { $('#globalMessaging').anymessage({'message':'In store_search.u.changePage, $list set but missing data(elastic-query).','gMessage':true}); } } else { $('#globalMessaging').anymessage({'message':'In store_search.u.changePage, $list or newPage not specified','gMessage':true}); } }, buildPagination : function($list,_tag) { var $pagination = false; //what is returned. Either an unordered list of pages or false if an error occured. if($list && _tag) { var EQ = $list.data('elastic-query'); //Elastic Query if(EQ) { var pageInFocus = $list.data('page-in-focus') || 1, //start at 1, not zero, so page 1 = 1 data = _app.data[_tag.datapointer], totalPageCount = Math.ceil(data.hits.total / EQ.size) //total # of pages for this list. if(totalPageCount <= 1) { //if there is only 1 page or something went wrong, don't show pagination. // _app.u.dump(" -> no pagination for results. totalPageCount: "+totalPageCount); } else { $pagination = $("<ul \/>").addClass('pagination resultsMenu'); $pagination.addClass('hideInMinimalMode').append($("<li \/>").html("<a href='#'>Page "+pageInFocus+" of "+totalPageCount+"<\/a>")); var $pages = $("<ul \/>"); for(var i = 1; i <= totalPageCount; i+= 1) { $("<li \/>").html("<a href='#' data-page='"+i+"'>Page "+i+"<\/a>").appendTo($pages); } $("li:first",$pagination).append($pages); $("a",$pages).each(function(){ $(this).on('click',function(event){ event.preventDefault(); _app.ext.store_search.u.changePage($list,$(this).data('page'),_tag); }) }); } } else { $('#globalMessaging').anymessage({'message':'In store_search.u.buildPagination, $list set but missing data(elastic-query).','gMessage':true}); } } else { $('#globalMessaging').anymessage({'message':'In store_search.u.buildPagination, either $list ['+typeof $list+'] or _tag ['+typeof _tag+'] not passed','gMessage':true}); } return $pagination; }, //buildPagination buildSortMenu : function($list,_tag){ var $sort = $("<ul \/>").addClass('sortMethods resultsMenu'), $ul = $("<ul \/>"), EQ = $list.data('elastic-query'); //Elastic Query $sort.addClass('hideInMinimalMode').append($("<li \/>").append("<a href='#'>sort by</a>")); $("<li \/>").html("<a href='#'>Relevance</a>").appendTo($ul); $("<li \/>").html("<a href='#'>Alphabetical (a to z)</a>").appendTo($ul); $("<li \/>").html("<a href='#'>Price (low to high)</a>").appendTo($ul); $("li:first",$sort).append($ul); //adds ul of sorts to the li w/ the sort by prompt. //add click events to the href's $("a",$ul).each(function(){ $(this).on('click',function(event){ event.preventDefault(); _app.u.dump(" -> change sort order"); var query = _app.ext.store_search.u.buildElasticSimpleQuery(EQ.query.query_string); query.size = EQ.size; //use original size, not what's returned in buildSimple... query.from = 0; query.sort = [{'base_price':{'order':'asc'}}]; _app.ext.store_search.u.updateDataOnListElement($list,query,1); _app.ext.store_search.calls.appPublicSearch.init(query,_tag); _app.model.dispatchThis(); }); }) return $sort; }, //buildSortMenu getAlternativeQueries : function(keywords,tagObj) { var keywordsArray = new Array(); keywordsArray = keywords.split(' '); // _app.u.dump(" -> number of words = "+keywordsArray.length); var permutations = this.getPermutationsOfArray(keywordsArray); // _app.u.dump(" -> number of permutations = "+permutations.length); var L = permutations.length; var mode = $('#headerModeInput').val(); var catalog = $('#headerCatalog').val(); var thisKeyword; for(var i = 0; i < L; i += 1) { thisKeyword = this.getPermArrayIntoString(permutations[i]); _app.ext.store_search.calls.searchResult.init({"KEYWORDS":thisKeyword,"CATALOG":catalog,"MODE":mode},tagObj); } }, //getAlternativeQueries getPermArrayIntoString : function(a) { var r = ''; for(var i = 0; i < a.length; i +=1) { r += a[i]+' '; } // _app.u.dump("permArrayToString = "+r); return r; }, //pass in an array of keywords and all combinations will be returned. //handy for breaking down a search query and letting the user see what //may return better results. getPermutationsOfArray : function(keywordsArray) { //found here: http://snippets.dzone.com/posts/show/3545 var combine = function(a) { var fn = function(n, src, got, all) { if (n == 0) { if (got.length > 0) { all[all.length] = got; } return; } for (var j = 0; j < src.length; j++) { fn(n - 1, src.slice(j + 1), got.concat([src[j]]), all); } return; } var all = []; for (var i=0; i < a.length; i++) { fn(i, a, [], all); } all.push(a); return all; } return combine(keywordsArray); }, //getPermutationsOfArray /* Will return the results a jquery object for display. append the return from this function to your list (or other element) P should contain the following: P.datapointer - pointer to where in _app.data the results are stored. P.templateID - what productList template to use P.parentID - The parent ID is used as the pointer in the multipage controls object. _app.ext.store_prodlist.vars[POINTER] #### note - not all these are used yet, but will be soon. */ getElasticResultsAsJQObject : function(P) { // _app.u.dump("BEGIN store_search.u.getElasticResultsAsJQObject ["+P.datapointer+"]") var pid;//recycled shortcut to product id. var L = _app.data[P.datapointer]['_count'] || _app.data[P.datapointer].hits.hits.length; var $r = $("<ul />"); //when this was a blank jquery object, it didn't work. so instead, we append all content to this imaginary list, then just return the children. // _app.u.dump(" -> parentID: "+P.parentID); //resultsProductListContainer // _app.u.dump(" -> L: "+L); for(var i = 0; i < L; i += 1) { pid = _app.data[P.datapointer].hits.hits[i]['_id']; // _app.u.dump(" -> "+i+" pid: "+pid); $r.append(new tlc().runTLC({'templateid':P.templateID,'dataset':_app.data[P.datapointer].hits.hits[i]['_source']}).attr('data-pid',pid).removeClass('loadingBG')); // $r.append(_app.renderFunctions.transmogrify({'id':pid,'pid':pid},P.templateID,_app.data[P.datapointer].hits.hits[i]['_source'])); } return $r.children(); }, //Adds elastic search params to a new raw elasticsearch object //Example of an obj would be {'filter':{'term':{'tags':'IS_BESTSELLER'}}} -- IE a full query or filter- just adding the required params here. buildElasticRaw : function(elasticsearch) { var es = $.extend(true, {}, elasticsearch); es.type = 'product'; es.mode = 'elastic-search'; es.size = 250; return es; }, //Example of an obj would be: {'query':'some search string'} OR {'query':'some search string','fields':'prod_keywords'} buildElasticSimpleQuery : function(obj) { var query = {}; //what is returned. false if error occurs. if(obj && obj.query) { query.type = 'product'; query.mode = 'elastic-search'; query.size = 250; query.query = {"query_string" : obj}; } else { $('#globalMessaging').anymessage({'message':'In store_search.u.buildElasticSimpleQuery, obj.query was empty. ',gMessage:true}); query = false; } return query; }, //This is used by quickstart for simple tag and keyword searches as well as by analyzer and admin interface (product editor and probably finder). handleElasticSimpleQuery : function(keywords,_tag) { var qObj = this.buildElasticSimpleQuery({'query':keywords}); _tag = _tag || {}; _tag.datapointer = "appPublicSearch|"+keywords; var r = _app.ext.store_search.calls.appPublicSearch.init(qObj,_tag); _app.model.dispatchThis(); return r; } } //util } //r object. return r; }
var PropTypes = require('prop-types'); var React = require('react'); var createReactClass = require('create-react-class'); var SetupMixin = require('./mixins/rangeFinderSetupMixin.js'); var MakerMixin = require('./mixins/componentMakerMixin.js'); var CalcMixin = require('./mixins/calculatedPropertyMixin.js'); var ScrollableSVG = require('./components/scrollableSVG.js'); var DefaultCoverageLabel = require('./components/defaultCoverageLabel.js'); require('./react-range-finder.scss'); var RangeFinder = createReactClass({ displayName: 'RangeFinder', findValue: function(args) { for(var key in args) { var arg = args[key]; if(arg || arg === 0) { return arg; } } return 0; }, getInitialState: function() { var selectedRange = this.props.selectedRange || {}; var valueRange = this.getValueRange(this.props); var min = this.findValue([this.props.min, valueRange.min, selectedRange.start, 0]); var max = this.findValue([this.props.max, valueRange.max, selectedRange.end, 100]); var start = selectedRange.start || min; var end = selectedRange.end || max; start = Math.max(start, min); end = Math.min(end, max); start = Math.min(start, end); //Limit start to end value return { min: min, max: max, start: start, end: end }; }, mixins: [SetupMixin, MakerMixin, CalcMixin], consts: { marginTop: 0, marginLeft: 0, marginRight: 40, marginBottom: 40, coverageBarMargin: 10, labelCharacterLimit: 20, tickSize: 10, sliderRadius: 5, ghostSize: 30, labelSideMargin: 1, textMargin: 20, textSize: 15, gradientId: 'mainGradient', scrollWidth: 10, borderRadius: 5, coverageGap: 4, }, getDefaultProps: function() { return { width: 860, height: 800, headerBarHeight: 50, labelColumnWidth: 160, coverageBarHeight: 20, maxCoverageHeight: 750, stepSize: 1, selectedRange: null, data: [], title: 'Value Range', coverageLabel: DefaultCoverageLabel, coverageLabelProps: {}, densityLowColor: {r: 0, g: 0, b: 0}, densityMidColor: null, densityHighColor: {r: 255, g: 255, b: 255}, onDragRangeStart: function() {}, onReleaseRangeStart: function() {}, onDrag: function() {}, onDragRangeEnd: function() {}, onReleaseRangeEnd: function() {}, onRelease: function() {}, onUpdateData: function() {} }; }, propTypes: { width: PropTypes.number, height: PropTypes.number, headerBarHeight: PropTypes.number, labelColumnWidth: PropTypes.number, maxCoverageHeight: PropTypes.number, coverageBarHeight: PropTypes.number, min: PropTypes.number, max: PropTypes.number, selectedRange: PropTypes.shape({ start: PropTypes.number, end: PropTypes.number, }), stepSize: PropTypes.number, title: PropTypes.string, consts: PropTypes.object, //coverageLabel: React.PropTypes.element, coverageLabelProps: PropTypes.object, data: PropTypes.arrayOf(PropTypes.object).isRequired, rowLabelProperties: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.string), PropTypes.string]).isRequired, valueProperty: PropTypes.string.isRequired, metadataProperty: PropTypes.string, colors: PropTypes.array, onStartDragMove: PropTypes.func, onStartDragEnd: PropTypes.func, onEndDragMove: PropTypes.func, onEndDragEnd: PropTypes.func, onUpdateData: PropTypes.func, }, componentWillReceiveProps: function(props) { this.updateSelectedRange(props.selectedRange, this.props.selectedRange); }, updateSelectedRange: function(newRange, oldRange) { if(newRange === null) { return; } if(oldRange === null) { this.setState(newRange); return; } if(newRange.start === oldRange.start && newRange.end === oldRange.end) { return; } newRange.start = Math.max(newRange.start, this.state.min); newRange.end = Math.min(newRange.end, this.state.max); this.setState(newRange); }, componentWillMount: function() { if(this.props.data === null || this.props.data.length === 0) { throw new Error('You must supply some data'); } for (var key in this.props.consts) { this.consts[key] = this.props.consts[key]; } this.barX = this.props.labelColumnWidth; this.barY = this.consts.marginTop; }, calculateCoverage: function(start, end) { if(!this.needsCoverage) { return 0; } var dataDensity = this.dataDensity; var sum = 0; for(var i = start; i <= end; i++) { if(dataDensity[i]) { sum += dataDensity[i]; } } return sum / (end - start + 1); }, setScrollUpdater: function(func) { this.scrollUpdaterFunc = func; }, render: function() { var snapGrid = this.snapGrid; var gradient = null; //this.makeGradient(); var ticks = this.makeTicks(snapGrid); var sliders = this.makeSliders(snapGrid); var coverage = this.makeCoverage(); var coverageGrouping = this.makeCoverageGrouping(); var gapFillers = this.makeGapFillers(); var unselected = this.makeUnselectedOverlay(); var titleX = this.props.labelColumnWidth / 2; var valueLabelY = this.barY + (this.props.headerBarHeight - this.consts.tickSize) / 2 + this.consts.textSize / 2; var coverageDetails = null; var densityLabel = null; if(coverage.length > 0) { var barBottom = this.barY + this.props.headerBarHeight + this.consts.coverageGap; coverageDetails = ( <ScrollableSVG y={barBottom} width={this.componentWidth} height={this.fullCoverageHeight} maxDisplayedHeight={this.coverageHeight} scrollWidth={this.consts.scrollWidth} setScrollUpdater={this.setScrollUpdater} className="rf-coverage-section"> <rect x={0} y={0} width={this.props.width} height={this.fullCoverageHeight} className="rf-coverage-background" fill="#F4F4F4" /> {coverage} {coverageGrouping} </ScrollableSVG> ) var density = this.calculateCoverage(this.state.start, this.state.end); densityLabel = ( <text x={titleX} y={this.barY + this.props.headerBarHeight / 2 + this.consts.textSize} fontSize={12} textAnchor="middle" className="rf-label rf-label-bold rf-density-label"> {Math.floor(100 * density) + '% coverage'} </text> ); } var topBarWidth = this.componentWidth; var topBarHeight = this.props.headerBarHeight + this.consts.borderRadius; var offset = 100 - 100 * (this.consts.borderRadius / topBarHeight); offset += '%' return ( <svg id={this.props.id} width={this.fullComponentWidth} height={this.fullComponentHeight} className="range-finder"> <defs> <linearGradient id={this.consts.gradientId} x1='0%' x2='0%' y1='0%' y2='100%'> <stop offset='0%' stopColor='#CFCFCF' stopOpacity='100%'/> <stop offset={offset} stopColor='#CFCFCF' stopOpacity='100%'/> <stop offset={offset} stopColor='#CFCFCF' stopOpacity='0%'/> <stop offset='100%' stopColor='#CFCFCF' stopOpacity='0%'/> </linearGradient> </defs> <rect x={0} y={this.barY} width={topBarWidth} height={topBarHeight} rx={this.consts.borderRadius} ry={this.consts.borderRadius} stroke={'url(#' + this.consts.gradientId + ')'} fill={'url(#' + this.consts.gradientId + ')'} className="rf-range-bar"/> <text x={titleX} y={this.barY + this.props.headerBarHeight / 2} textAnchor="middle" className="rf-label rf-label-bold rf-title-label"> {this.props.title} </text> <text x={this.barX} y={valueLabelY} fontSize={this.consts.textSize} textAnchor="start" className="rf-label rf-label-bold rf-value-label"> {this.state.min} </text> <text x={this.componentWidth - this.consts.labelSideMargin} y={valueLabelY} fontSize={this.consts.textSize} textAnchor="end" className="rf-label rf-label-bold rf-value-label"> {this.state.max} </text> {densityLabel} <g className="rf-ticks">{ticks}</g> {coverageDetails} {gapFillers} {unselected} {sliders} </svg> ) }, }); module.exports = RangeFinder
$(document).ready(function() { test("Basic plugin tests", function() { ok($("a").prepare_links(), "Should immediately respond as a jQuery plugin"); }); test("Should open external links in new window.", function() { UnitTest.setup.sandbox(); UnitTest.setup.links([ {id : 'google', url : 'http://google.com'}, {id : 'current_domain', url : window.location.host}, {id : 'current_domain', url : 'www' + window.location.host}, {id : 'relative_path', url : 'relative/path/'}, {id : 'absolute_path', url : '/absolute/path/'}, {id : 'subdomain', url : 'http://subdomain' + window.location.host}, {id : 'localhost', url : 'http://localhost'}, {id : 'localhost3000', url : 'http://localhost:3000'} ]); $("#sandbox a").prepare_links(); equal($("#google").attr('target'), "_blank", "Target should be _blank"); equal($("#current_domain").attr('target'), "", "Target should be empty for current domain"); equal($("#subdomain").attr('target'), "", "Target should be empty for current subdomain"); equal($("#relative_path").attr('target'), "", "Target should be empty for relative path"); equal($("#absolute_path").attr('target'), "", "Target should be empty for absolute path"); equal($("#localhost3000").attr('target'), "", "Target should be empty for local host with subdomain"); equal($("#localhost").attr('target'), "", "Target should be empty for localhost"); equal($("#localhost3000").attr('target'), "", "Target should be empty for local host with port"); UnitTest.teardown.sandbox(); }); test("Should provide options for additional \"internal\" links.", function() { UnitTest.setup.sandbox(); UnitTest.setup.links([ {id : 'affiliate_site', url : 'http://affiliatesite.com'} ]); $("#sandbox a").prepare_links({additional_internal_sites : ['http://affiliatesite.com']}); equal($("#affiliate_site").attr('target'), "", "Target should be empty"); UnitTest.teardown.sandbox(); }); test("Should allow subdomains to be considered external links.", function() { UnitTest.setup.sandbox(); UnitTest.setup.links([ {id : 'affiliate_site', url : 'http://blog.' + location.host} ]); $("#sandbox a").prepare_links({subdomains_are_external : false}); equal($("#affiliate_site").attr('target'), "", "Target should be not be _blank"); $("#sandbox a").prepare_links({subdomains_are_external : true}); equal($("#affiliate_site").attr('target'), "_blank", "Target should be _blank"); UnitTest.teardown.sandbox(); }); });
var Surface = require('@src/traces/surface'); var Plotly = require('@lib/index'); var failTest = require('../assets/fail_test'); var createGraphDiv = require('../assets/create_graph_div'); var destroyGraphDiv = require('../assets/destroy_graph_div'); var Lib = require('@src/lib'); describe('Test surface', function() { 'use strict'; describe('supplyDefaults', function() { var supplyDefaults = Surface.supplyDefaults; var defaultColor = '#444'; var layout = {_dfltTitle: {colorbar: 'cb'}}; var traceIn, traceOut; beforeEach(function() { traceOut = {}; }); it('should set \'visible\' to false if \'z\' isn\'t provided', function() { traceIn = {}; supplyDefaults(traceIn, traceOut, defaultColor, layout); expect(traceOut.visible).toBe(false); }); it('should NOT fill \'x\' and \'y\' if not provided', function() { // this happens later on now traceIn = { z: [[1, 2, 3], [2, 1, 2]] }; supplyDefaults(traceIn, traceOut, defaultColor, layout); expect(traceOut.x).toBeUndefined(); expect(traceOut.y).toBeUndefined(); }); it('should coerce \'project\' if contours or highlight lines are enabled', function() { traceIn = { z: [[1, 2, 3], [2, 1, 2]], contours: { x: {}, y: { show: true }, z: { show: false, highlight: false } } }; var fullOpts = { show: false, highlight: true, project: { x: false, y: false, z: false }, highlightcolor: '#444', highlightwidth: 2 }; supplyDefaults(traceIn, traceOut, defaultColor, layout); expect(traceOut.contours.x).toEqual(fullOpts); expect(traceOut.contours.y).toEqual(Lib.extendDeep({}, fullOpts, { show: true, color: '#444', width: 2, usecolormap: false })); expect(traceOut.contours.z).toEqual({ show: false, highlight: false }); }); it('should coerce contour style attributes if contours lines are enabled', function() { traceIn = { z: [[1, 2, 3], [2, 1, 2]], contours: { x: { show: true } } }; supplyDefaults(traceIn, traceOut, defaultColor, layout); expect(traceOut.contours.x.color).toEqual('#444'); expect(traceOut.contours.x.width).toEqual(2); expect(traceOut.contours.x.usecolormap).toEqual(false); ['y', 'z'].forEach(function(ax) { expect(traceOut.contours[ax].color).toBeUndefined(); expect(traceOut.contours[ax].width).toBeUndefined(); expect(traceOut.contours[ax].usecolormap).toBeUndefined(); }); }); it('should coerce colorscale and colorbar attributes', function() { traceIn = { z: [[1, 2, 3], [2, 1, 2]] }; supplyDefaults(traceIn, traceOut, defaultColor, layout); expect(traceOut.cauto).toBe(true); expect(traceOut.cmin).toBeUndefined(); expect(traceOut.cmax).toBeUndefined(); expect(traceOut.colorscale).toEqual([ [0, 'rgb(5,10,172)'], [0.35, 'rgb(106,137,247)'], [0.5, 'rgb(190,190,190)'], [0.6, 'rgb(220,170,132)'], [0.7, 'rgb(230,145,90)'], [1, 'rgb(178,10,28)'] ]); expect(traceOut.showscale).toBe(true); expect(traceOut.colorbar).toBeDefined(); }); it('should coerce \'c\' attributes with \'z\' if \'c\' isn\'t present', function() { traceIn = { z: [[1, 2, 3], [2, 1, 2]], zauto: false, zmin: 0, zmax: 10 }; supplyDefaults(traceIn, traceOut, defaultColor, layout); expect(traceOut.cauto).toEqual(false); expect(traceOut.cmin).toEqual(0); expect(traceOut.cmax).toEqual(10); }); it('should coerce \'c\' attributes with \'c\' values regardless of `\'z\' if \'c\' is present', function() { traceIn = { z: [[1, 2, 3], [2, 1, 2]], zmin: 0, zmax: 10, cmin: -10, cmax: 20 }; supplyDefaults(traceIn, traceOut, defaultColor, layout); expect(traceOut.cauto).toEqual(false); expect(traceOut.cmin).toEqual(-10); expect(traceOut.cmax).toEqual(20); }); it('should default \'c\' attributes with if \'surfacecolor\' is present', function() { traceIn = { z: [[1, 2, 3], [2, 1, 2]], surfacecolor: [[2, 1, 2], [1, 2, 3]], zauto: false, zmin: 0, zmax: 10 }; supplyDefaults(traceIn, traceOut, defaultColor, layout); expect(traceOut.cauto).toEqual(true); expect(traceOut.cmin).toBeUndefined(); expect(traceOut.cmax).toBeUndefined(); }); it('should inherit layout.calendar', function() { traceIn = { z: [[1, 2, 3], [2, 1, 2]] }; supplyDefaults(traceIn, traceOut, defaultColor, Lib.extendFlat({calendar: 'islamic'}, layout)); // we always fill calendar attributes, because it's hard to tell if // we're on a date axis at this point. expect(traceOut.xcalendar).toBe('islamic'); expect(traceOut.ycalendar).toBe('islamic'); expect(traceOut.zcalendar).toBe('islamic'); }); it('should take its own calendars', function() { var traceIn = { z: [[1, 2, 3], [2, 1, 2]], xcalendar: 'coptic', ycalendar: 'ethiopian', zcalendar: 'mayan' }; supplyDefaults(traceIn, traceOut, defaultColor, layout); expect(traceOut.xcalendar).toBe('coptic'); expect(traceOut.ycalendar).toBe('ethiopian'); expect(traceOut.zcalendar).toBe('mayan'); }); }); describe('Test dimension and expected visibility tests', function() { var gd; beforeEach(function() { gd = createGraphDiv(); }); afterEach(function() { Plotly.purge(gd); destroyGraphDiv(); }); function assertVisibility(exp, msg) { expect(gd._fullData[0]).not.toBe(undefined, 'no visibility!'); expect(gd._fullData[0].visible).toBe(exp, msg); } it('@gl surface should be invisible when the z array is empty', function(done) { Plotly.plot(gd, [{ 'type': 'surface', 'z': [] }]) .then(function() { assertVisibility(false, 'not to be visible'); }) .catch(failTest) .then(done); }); it('@gl surface should be invisible when the x array is defined but is empty', function(done) { Plotly.plot(gd, [{ 'type': 'surface', 'x': [], 'y': [0, 1], 'z': [] }]) .then(function() { assertVisibility(false, 'not to be visible'); }) .catch(failTest) .then(done); }); it('@gl surface should be invisible when the y array is defined but is empty', function(done) { Plotly.plot(gd, [{ 'type': 'surface', 'x': [0, 1], 'y': [], 'z': [] }]) .then(function() { assertVisibility(false, 'not to be visible'); }) .catch(failTest) .then(done); }); it('@gl surface should be invisible when the x array is defined and has at least one item', function(done) { Plotly.plot(gd, [{ 'type': 'surface', 'x': [0], 'y': [0, 1], 'z': [[1], [2]] }]) .then(function() { assertVisibility(true, 'to be visible'); }) .catch(failTest) .then(done); }); it('@gl surface should be invisible when the y array is defined and has at least one item', function(done) { Plotly.plot(gd, [{ 'type': 'surface', 'x': [0, 1], 'y': [0], 'z': [[1, 2]] }]) .then(function() { assertVisibility(true, 'to be visible'); }) .catch(failTest) .then(done); }); it('@gl surface should be visible when the x and y are not provided; but z array is provided', function(done) { Plotly.plot(gd, [{ 'type': 'surface', 'z': [[1, 2], [3, 4]] }]) .then(function() { assertVisibility(true, 'to be visible'); }) .catch(failTest) .then(done); }); it('@gl surface should be invisible when the x and y are provided; but z array is not provided', function(done) { Plotly.plot(gd, [{ 'type': 'surface', 'x': [0, 1], 'y': [0, 1] }]) .then(function() { assertVisibility(false, 'to be invisible'); }) .catch(failTest) .then(done); }); }); });
window.AvatarUploaderModel = new qq.FineUploader({ element: $('#manual-fine-uploader')[0], request: { endpoint: '../logged/api/account/1/photos/avatar', customHeaders: { Accept: 'application/json' } }, autoUpload: false, validation: { allowedExtensions: ['jpeg', 'jpg', 'gif', 'png'], sizeLimit: 512000 // 50 kB = 50 * 1024 bytes }, text: { uploadButton: '<i class="icon-plus icon-white"></i> Select Avatar' }, callbacks: { onComplete: function(id, fileName, responseJSON) { var model = responseJSON.photo; var id = $('#acc_id').val(); $('#avatar').html("<img src='../image/avatar/" +id+"' />"); } } });
'use strict'; var config = require('../config'); var SSHConfig = require('../lib/ssh-config-reader'); var sqliteDb = require('../db'); var JsonStore = require('../lib/json-store'); var dbRoutes = require('./database'); var excludedTables = new JsonStore('excluded-tables').getAll(); sqliteDb.connect(); function Routes() {} Routes.prototype.use = function (webApp) { webApp.get('/', function(req, resp){ resp.render('index'); }); webApp.get('/configuration', function(req, resp){ resp.render('configuration'); }); webApp.get('/getConfig', function(req, resp) { resp.json(config); }); webApp.post('/setConfig', function(req, resp) { for (var group in req.body) { if (req.body.hasOwnProperty(group)) { for (var key in req.body[group]) { if (req.body[group].hasOwnProperty(key)) { config[group][key] = req.body[group][key]; } } } } }); /** * Client Routes */ webApp.get('/Clients', function(req, resp){ resp.render('clients'); }); webApp.get('/Clients/getAll', function(req, resp){ sqliteDb.Client.getAll(function(data){ resp.json(data); }); }); webApp.post('/Clients/save', function(req, resp){ var params = req.body; if (params.id) { sqliteDb.Client.update(params, function(){ resp.json({}); }); } else { delete params['id']; sqliteDb.Client.insert(params, function(lastId){ resp.end(); }); } }); webApp.post('/Clients/delete', function(req, resp){ var id = req.body['id']; if (!id) { resp.end('Id is not set'); return false; } sqliteDb.Client.deleteBy('id', id, function(numChanges){ resp.end(); }); }); /** * Server Routes */ webApp.get('/Servers', function(req, resp){ resp.render('servers'); }); webApp.get('/Servers/getAll', function(req, resp){ sqliteDb.Server.getAllJoined(function(data){ resp.json(data); }); }); webApp.post('/Servers/save', function(req, resp){ var params = req.body; if (params['ssh_config']) { var sshEntry = SSHConfig.getHostByName(params['ssh_config']); params['ssh_host'] = sshEntry['host']; params['ssh_username'] = sshEntry['user']; delete params['ssh_config']; } if (params.id) { sqliteDb.Server.update(params, function(){ resp.json({}); }); } else { delete params['id']; sqliteDb.Server.insert(params, function(lastId){ resp.end(); }); } }); webApp.post('/Servers/delete', function(req, resp){ var id = req.body['id']; if (!id) { resp.end('Id is not set'); return false; } sqliteDb.Server.deleteBy('id', id, function(numChanges){ resp.end(); }); }); /** * Profile Routes */ webApp.get('/Profiles', function(req, resp){ resp.render('profiles/index'); }); webApp.get('/Profiles/new', function(req, resp){ resp.render('profiles/edit', {action: 'new'}); }); //webApp.get(/\/Profiles\/edit\/(.*)/g , function(req, resp){ webApp.get('/Profiles/edit/:id', function(req, resp, next){ var id = req.params['id']; if (!id) next(); sqliteDb.Profile.getByJoined('Profile.id', id, function(data){ resp.render('profiles/edit', {action: 'edit', profile: data[0]}); }); }); webApp.get('/Profiles/get', function(req, resp){ var params = req.body; if (params.id) { sqliteDb.Profile.getByJoined('id', params.id, function(data){ resp.json(data); }); } }); webApp.get('/Profiles/getAll', function(req, resp){ sqliteDb.Profile.getAllJoined(function(data){ resp.json(data); }); }); webApp.post('/Profiles/save', function(req, resp){ var params = req.body; params['excluded_tables'] = JSON.stringify(params['excluded_tables']); if (params.id) { sqliteDb.Profile.update(params, function(){ resp.json({}); }); } else { //Inserting default list of tables for now - will get tables from server in later release params['tables'] = JSON.stringify(excludedTables); sqliteDb.Profile.insert(params, function(lastId){ resp.end(); }); } }); webApp.post('/Profiles/delete', function(req, resp){ var id = req.body['id']; try { sqliteDb.Profile.deleteBy('id', id, function(numChanges){ resp.end(); }); } catch (e) { resp.send(500, e); resp.end(e); } }); webApp.get("/Profiles/run/:id", function(req, resp){ var id = req.params["id"]; if (!id) { resp.render('profiles/run', {profile: null}); } else { sqliteDb.Profile.getByJoined('Profile.id', id, function(data){ resp.render('profiles/run', {profile: data[0]}); }); } }); dbRoutes.use(webApp); webApp.get(/\/getSshConfig|\/SshConfig\/getAll/, function(req, resp){ resp.json(SSHConfig.getHosts()); }.bind(webApp)); webApp.get('/ExcludedTables/getAll', function(req, resp){ resp.json(excludedTables); }); }; module.exports = new Routes();
'use strict'; tripExchange.controller('SignUpCtrl', ['$scope', '$location', 'auth', 'notifier', function SignUpCtrl($scope, $location, auth, notifier) { $scope.emailPattern = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; $scope.signup = function(user) { auth.signup(user).then(function() { notifier.success('Registration successful!'); $location.path('/'); }) } }]);
// install : cordova plugin add cordova-plugin-device // link : https://github.com/apache/cordova-plugin-device //angular.module('ngCordova.plugins.device', []) angular.module('starter.services').factory('$cordovaDevice', [ function() { return { /** * Returns the whole device object. * * @see https://github.com/apache/cordova-plugin-device * @returns {Object} The device object. */ getDevice : function() { return device; }, /** * Returns the Cordova version. * * @see https://github.com/apache/cordova-plugin-device#devicecordova * @returns {String} The Cordova version. */ getCordova : function() { return device.cordova; }, /** * Returns the name of the device's model or product. * * @see https://github.com/apache/cordova-plugin-device#devicemodel * @returns {String} The name of the device's model or product. */ getModel : function() { return device.model; }, /** * @deprecated device.name is deprecated as of version 2.3.0. Use * device.model instead. * @returns {String} */ getName : function() { return device.name; }, /** * Returns the device's operating system name. * * @see https://github.com/apache/cordova-plugin-device#deviceplatform * @returns {String} The device's operating system name. */ getPlatform : function() { return device.platform; }, /** * Returns the device's Universally Unique Identifier. * * @see https://github.com/apache/cordova-plugin-device#deviceuuid * @returns {String} The device's Universally Unique Identifier */ getUUID : function() { return device.uuid; }, /** * Returns the operating system version. * * @see https://github.com/apache/cordova-plugin-device#deviceversion * @returns {String} */ getVersion : function() { return device.version; } }; } ]);
/** * Simulator process * Pokemon Showdown - http://pokemonshowdown.com/ * * This file is where the battle simulation itself happens. * * The most important part of the simulation happens in runEvent - * see that function's definition for details. * * @license MIT license */ //require('sugar'); //global.Config = require('./config/config.js'); // graceful crash - allow current battles to finish before restarting /*process.on('uncaughtException', function (err) { require('./crashlogger.js')(err, 'A simulator process'); });*/ /** * Converts anything to an ID. An ID must have only lowercase alphanumeric * characters. * If a string is passed, it will be converted to lowercase and * non-alphanumeric characters will be stripped. * If an object with an ID is passed, its ID will be returned. * Otherwise, an empty string will be returned. */ /*global.toId = function (text) { if (text && text.id) text = text.id; else if (text && text.userid) text = text.userid; return string(text).toLowerCase().replace(/[^a-z0-9]+/g, ''); };*/ /** * Validates a username or Pokemon nickname */ /*global.toName = function (name) { name = string(name); name = name.replace(/[\|\s\[\]\,]+/g, ' ').trim(); if (name.length > 18) name = name.substr(0, 18).trim(); return name; };*/ /** * Safely ensures the passed variable is a string * Simply doing '' + str can crash if str.toString crashes or isn't a function * If we're expecting a string and being given anything that isn't a string * or a number, it's safe to assume it's an error, and return '' */ /*global.string = function (str) { if (typeof str === 'string' || typeof str === 'number') return '' + str; return ''; };*/ //global.Tools = require('./tools.js'); var Battle, BattleSide, BattlePokemon; var Battles = {}; // Receive and process a message sent using Simulator.prototype.send in // another process. battleEngineFakeProcess.client.on('message', function (message) { //console.log('CHILD MESSAGE RECV: "' + message + '"'); var nlIndex = message.indexOf("\n"); var more = ''; if (nlIndex > 0) { more = message.substr(nlIndex + 1); message = message.substr(0, nlIndex); } var data = message.split('|'); if (data[1] === 'init') { if (!Battles[data[0]]) { try { Battles[data[0]] = Battle.construct(data[0], data[2], data[3]); } catch (err) { var stack = err.stack + '\n\n' + 'Additional information:\n' + 'message = ' + message; var fakeErr = {stack: stack}; if (!require('./crashlogger.js')(fakeErr, 'A battle')) { var ministack = ("" + err.stack).escapeHTML().split("\n").slice(0, 2).join("<br />"); battleEngineFakeProcess.client.send(data[0] + '\nupdate\n|html|<div class="broadcast-red"><b>A BATTLE PROCESS HAS CRASHED:</b> ' + ministack + '</div>'); } else { battleEngineFakeProcess.client.send(data[0] + '\nupdate\n|html|<div class="broadcast-red"><b>The battle crashed!</b><br />Don\'t worry, we\'re working on fixing it.</div>'); } } } } else if (data[1] === 'dealloc') { if (Battles[data[0]]) Battles[data[0]].destroy(); delete Battles[data[0]]; } else { var battle = Battles[data[0]]; if (battle) { var prevRequest = battle.currentRequest; var prevRequestDetails = battle.currentRequestDetails || ''; try { battle.receive(data, more); } catch (err) { var stack = err.stack + '\n\n' + 'Additional information:\n' + 'message = ' + message + '\n' + 'currentRequest = ' + prevRequest + '\n\n' + 'Log:\n' + battle.log.join('\n').replace(/\n\|split\n[^\n]*\n[^\n]*\n[^\n]*\n/g, '\n'); var fakeErr = {stack: stack}; require('./crashlogger.js')(fakeErr, 'A battle'); var logPos = battle.log.length; battle.add('html', '<div class="broadcast-red"><b>The battle crashed</b><br />You can keep playing but it might crash again.</div>'); var nestedError; try { battle.makeRequest(prevRequest, prevRequestDetails); } catch (e) { nestedError = e; } battle.sendUpdates(logPos); if (nestedError) { throw nestedError; } } } else if (data[1] === 'eval') { try { eval(data[2]); } catch (e) {} } } }); BattlePokemon = (function () { function BattlePokemon(set, side) { this.side = side; this.battle = side.battle; if (typeof set === 'string') set = {name: set}; // "pre-bound" functions for nicer syntax (avoids repeated use of `bind`) this.getHealth = BattlePokemon.getHealth.bind(this); this.getDetails = BattlePokemon.getDetails.bind(this); this.set = set; this.baseTemplate = this.battle.getTemplate(set.species || set.name); if (!this.baseTemplate.exists) { this.battle.debug('Unidentified species: ' + this.species); this.baseTemplate = this.battle.getTemplate('Unown'); } this.species = this.baseTemplate.species; if (set.name === set.species || !set.name || !set.species) { set.name = this.species; } this.name = (set.name || set.species || 'Bulbasaur').substr(0, 20); this.speciesid = toId(this.species); this.template = this.baseTemplate; this.moves = []; this.baseMoves = this.moves; this.movepp = {}; this.moveset = []; this.baseMoveset = []; this.level = this.battle.clampIntRange(set.forcedLevel || set.level || 100, 1, 1000); var genders = {M:'M', F:'F'}; this.gender = this.template.gender || genders[set.gender] || (Math.random() * 2 < 1 ? 'M' : 'F'); if (this.gender === 'N') this.gender = ''; this.happiness = typeof set.happiness === 'number' ? this.battle.clampIntRange(set.happiness, 0, 255) : 255; this.pokeball = this.set.pokeball || 'pokeball'; this.fullname = this.side.id + ': ' + this.name; this.details = this.species + (this.level === 100 ? '' : ', L' + this.level) + (this.gender === '' ? '' : ', ' + this.gender) + (this.set.shiny ? ', shiny' : ''); this.id = this.fullname; // shouldn't really be used anywhere this.statusData = {}; this.volatiles = {}; this.negateImmunity = {}; this.height = this.template.height; this.heightm = this.template.heightm; this.weight = this.template.weight; this.weightkg = this.template.weightkg; this.ignore = {}; this.baseAbility = toId(set.ability); this.ability = this.baseAbility; this.item = toId(set.item); this.canMegaEvo = (this.battle.getItem(this.item).megaEvolves === this.baseTemplate.baseSpecies); this.abilityData = {id: this.ability}; this.itemData = {id: this.item}; this.speciesData = {id: this.speciesid}; this.types = this.baseTemplate.types; this.typesData = []; for (var i = 0, l = this.types.length; i < l; i++) { this.typesData.push({ type: this.types[i], suppressed: false, isAdded: false }); } if (this.set.moves) { for (var i = 0; i < this.set.moves.length; i++) { var move = this.battle.getMove(this.set.moves[i]); if (!move.id) continue; if (move.id === 'hiddenpower') { if (!this.set.ivs || Object.values(this.set.ivs).every(31)) { this.set.ivs = this.battle.getType(move.type).HPivs; } move = this.battle.getMove('hiddenpower'); } this.baseMoveset.push({ move: move.name, id: move.id, pp: (move.noPPBoosts ? move.pp : move.pp * 8 / 5), maxpp: (move.noPPBoosts ? move.pp : move.pp * 8 / 5), target: (move.nonGhostTarget && !this.hasType('Ghost') ? move.nonGhostTarget : move.target), disabled: false, used: false }); this.moves.push(move.id); } } if (!this.set.evs) { this.set.evs = { hp: 84, atk: 84, def: 84, spa: 84, spd: 84, spe: 84 }; } if (!this.set.ivs) { this.set.ivs = { hp: 31, atk: 31, def: 31, spa: 31, spd: 31, spe: 31 }; } var stats = { hp: 31, atk: 31, def: 31, spe: 31, spa: 31, spd: 31}; for (var i in stats) { if (!this.set.evs[i]) this.set.evs[i] = 0; if (!this.set.ivs[i] && this.set.ivs[i] !== 0) this.set.ivs[i] = 31; } for (var i in this.set.evs) { this.set.evs[i] = this.battle.clampIntRange(this.set.evs[i], 0, 255); } for (var i in this.set.ivs) { this.set.ivs[i] = this.battle.clampIntRange(this.set.ivs[i], 0, 31); } var hpTypes = ['Fighting', 'Flying', 'Poison', 'Ground', 'Rock', 'Bug', 'Ghost', 'Steel', 'Fire', 'Water', 'Grass', 'Electric', 'Psychic', 'Ice', 'Dragon', 'Dark']; if (this.battle.gen && this.battle.gen === 2) { // Gen 2 specific Hidden Power check. IVs are still treated 0-31 so we get them 0-15 var atkDV = Math.floor(this.set.ivs.atk / 2); var defDV = Math.floor(this.set.ivs.def / 2); var speDV = Math.floor(this.set.ivs.spe / 2); var spcDV = Math.floor(this.set.ivs.spa / 2); this.hpType = hpTypes[4 * (atkDV % 4) + (defDV % 4)]; this.hpPower = Math.floor((5 * ((spcDV >> 3) + (2 * (speDV >> 3)) + (4 * (defDV >> 3)) + (8 * (atkDV >> 3))) + (spcDV > 2 ? 3 : spcDV)) / 2 + 31); } else { // Hidden Power check for gen 3 onwards var hpTypeX = 0, hpPowerX = 0; var i = 1; for (var s in stats) { hpTypeX += i * (this.set.ivs[s] % 2); hpPowerX += i * (Math.floor(this.set.ivs[s] / 2) % 2); i *= 2; } this.hpType = hpTypes[Math.floor(hpTypeX * 15 / 63)]; // In Gen 6, Hidden Power is always 60 base power this.hpPower = (this.battle.gen && this.battle.gen < 6) ? Math.floor(hpPowerX * 40 / 63) + 30 : 60; } this.boosts = { atk: 0, def: 0, spa: 0, spd: 0, spe: 0, accuracy: 0, evasion: 0 }; this.stats = {atk:0, def:0, spa:0, spd:0, spe:0}; this.baseStats = {atk:10, def:10, spa:10, spd:10, spe:10}; for (var statName in this.baseStats) { var stat = this.template.baseStats[statName]; stat = Math.floor(Math.floor(2 * stat + this.set.ivs[statName] + Math.floor(this.set.evs[statName] / 4)) * this.level / 100 + 5); var nature = this.battle.getNature(this.set.nature); if (statName === nature.plus) stat *= 1.1; if (statName === nature.minus) stat *= 0.9; this.baseStats[statName] = Math.floor(stat); } this.maxhp = Math.floor(Math.floor(2 * this.template.baseStats['hp'] + this.set.ivs['hp'] + Math.floor(this.set.evs['hp'] / 4) + 100) * this.level / 100 + 10); if (this.template.baseStats['hp'] === 1) this.maxhp = 1; // shedinja this.hp = this.hp || this.maxhp; this.baseIvs = this.set.ivs; this.baseHpType = this.hpType; this.baseHpPower = this.hpPower; this.clearVolatile(true); } BattlePokemon.prototype.trapped = false; BattlePokemon.prototype.maybeTrapped = false; BattlePokemon.prototype.hp = 0; BattlePokemon.prototype.maxhp = 100; BattlePokemon.prototype.illusion = null; BattlePokemon.prototype.fainted = false; BattlePokemon.prototype.lastItem = ''; BattlePokemon.prototype.ateBerry = false; BattlePokemon.prototype.status = ''; BattlePokemon.prototype.position = 0; BattlePokemon.prototype.lastMove = ''; BattlePokemon.prototype.moveThisTurn = ''; BattlePokemon.prototype.lastDamage = 0; BattlePokemon.prototype.lastAttackedBy = null; BattlePokemon.prototype.usedItemThisTurn = false; BattlePokemon.prototype.newlySwitched = false; BattlePokemon.prototype.beingCalledBack = false; BattlePokemon.prototype.isActive = false; BattlePokemon.prototype.isStarted = false; // has this pokemon's Start events run yet? BattlePokemon.prototype.transformed = false; BattlePokemon.prototype.duringMove = false; BattlePokemon.prototype.hpType = 'Dark'; BattlePokemon.prototype.hpPower = 60; BattlePokemon.prototype.speed = 0; BattlePokemon.prototype.toString = function () { var fullname = this.fullname; if (this.illusion) fullname = this.illusion.fullname; var positionList = 'abcdef'; if (this.isActive) return fullname.substr(0, 2) + positionList[this.position] + fullname.substr(2); return fullname; }; // "static" function BattlePokemon.getDetails = function (side) { if (this.illusion) return this.illusion.details + '|' + this.getHealth(side); return this.details + '|' + this.getHealth(side); }; BattlePokemon.prototype.update = function (init) { // reset for Light Metal etc this.weightkg = this.template.weightkg; // reset for diabled moves this.disabledMoves = {}; this.negateImmunity = {}; this.trapped = this.maybeTrapped = false; // reset for ignore settings this.ignore = {}; for (var i in this.moveset) { if (this.moveset[i]) this.moveset[i].disabled = false; } if (init) return; if (this.runImmunity('trapped')) this.battle.runEvent('MaybeTrapPokemon', this); for (var i = 0; i < this.battle.sides.length; ++i) { var side = this.battle.sides[i]; if (side === this.side) continue; for (var j = 0; j < side.active.length; ++j) { var pokemon = side.active[j]; if (!pokemon || pokemon.fainted || !pokemon.template.abilities) continue; for (var k in pokemon.template.abilities) { var ability = pokemon.template.abilities[k]; if (ability === pokemon.ability) { // This event was already run above so we don't need // to run it again. continue; } if ((k === 'H') && pokemon.template.unreleasedHidden) { // unreleased hidden ability continue; } if (this.runImmunity('trapped')) { this.battle.singleEvent('FoeMaybeTrapPokemon', this.battle.getAbility(ability), {}, this, pokemon); } } } } this.battle.runEvent('ModifyPokemon', this); this.speed = this.getStat('spe'); }; BattlePokemon.prototype.calculateStat = function (statName, boost, modifier) { statName = toId(statName); // var boost = this.boosts[statName]; if (statName === 'hp') return this.maxhp; // please just read .maxhp directly // base stat var stat = this.stats[statName]; // stat boosts // boost = this.boosts[statName]; var boostTable = [1, 1.5, 2, 2.5, 3, 3.5, 4]; if (boost > 6) boost = 6; if (boost < -6) boost = -6; if (boost >= 0) { stat = Math.floor(stat * boostTable[boost]); } else { stat = Math.floor(stat / boostTable[-boost]); } // stat modifier stat = this.battle.modify(stat, (modifier || 1)); if (this.battle.getStatCallback) { stat = this.battle.getStatCallback(stat, statName, this); } return stat; }; BattlePokemon.prototype.getStat = function (statName, unboosted, unmodified) { statName = toId(statName); if (statName === 'hp') return this.maxhp; // please just read .maxhp directly // base stat var stat = this.stats[statName]; // stat boosts if (!unboosted) { var boost = this.boosts[statName]; var boostTable = [1, 1.5, 2, 2.5, 3, 3.5, 4]; if (boost > 6) boost = 6; if (boost < -6) boost = -6; if (boost >= 0) { stat = Math.floor(stat * boostTable[boost]); } else { stat = Math.floor(stat / boostTable[-boost]); } } // stat modifier effects if (!unmodified) { var statTable = {atk:'Atk', def:'Def', spa:'SpA', spd:'SpD', spe:'Spe'}; var statMod = 1; statMod = this.battle.runEvent('Modify' + statTable[statName], this, null, null, statMod); stat = this.battle.modify(stat, statMod); } if (this.battle.getStatCallback) { stat = this.battle.getStatCallback(stat, statName, this); } return stat; }; BattlePokemon.prototype.getMoveData = function (move) { move = this.battle.getMove(move); for (var i = 0; i < this.moveset.length; i++) { var moveData = this.moveset[i]; if (moveData.id === move.id) { return moveData; } } return null; }; BattlePokemon.prototype.deductPP = function (move, amount, source) { move = this.battle.getMove(move); var ppData = this.getMoveData(move); var success = false; if (ppData) { ppData.used = true; } if (ppData && ppData.pp) { ppData.pp -= this.battle.runEvent('DeductPP', this, source || this, move, amount || 1); if (ppData.pp <= 0) { ppData.pp = 0; } success = true; } return success; }; BattlePokemon.prototype.moveUsed = function (move) { this.lastMove = this.battle.getMove(move).id; this.moveThisTurn = this.lastMove; }; BattlePokemon.prototype.gotAttacked = function (move, damage, source) { if (!damage) damage = 0; move = this.battle.getMove(move); this.lastAttackedBy = { pokemon: source, damage: damage, move: move.id, thisTurn: true }; }; BattlePokemon.prototype.getLockedMove = function () { var lockedMove = this.battle.runEvent('LockMove', this); if (lockedMove === true) lockedMove = false; return lockedMove; }; BattlePokemon.prototype.getMoves = function (lockedMove) { if (lockedMove) { lockedMove = toId(lockedMove); this.trapped = true; } if (lockedMove === 'recharge') { return [{ move: 'Recharge', id: 'recharge' }]; } var moves = []; var hasValidMove = false; for (var i = 0; i < this.moveset.length; i++) { var move = this.moveset[i]; if (lockedMove) { if (lockedMove === move.id) { return [{ move: move.move, id: move.id }]; } continue; } if (this.disabledMoves[move.id] || !move.pp && (this.battle.gen !== 1 || !this.volatiles['partialtrappinglock'])) { move.disabled = true; } else if (!move.disabled) { hasValidMove = true; } var moveName = move.move; if (move.id === 'hiddenpower') { moveName = 'Hidden Power ' + this.hpType; if (this.gen < 6) moveName += ' ' + this.hpPower; } moves.push({ move: moveName, id: move.id, pp: move.pp, maxpp: move.maxpp, target: move.target, disabled: move.disabled }); } if (lockedMove) { return [{ move: this.battle.getMove(lockedMove).name, id: lockedMove }]; } if (!hasValidMove) { return [{ move: 'Struggle', id: 'struggle' }]; } return moves; }; BattlePokemon.prototype.getRequestData = function () { var lockedMove = this.getLockedMove(); var data = {moves: this.getMoves(lockedMove)}; if (this.trapped) { data.trapped = true; } else if (this.maybeTrapped) { data.maybeTrapped = true; } return data; }; BattlePokemon.prototype.positiveBoosts = function () { var boosts = 0; for (var i in this.boosts) { if (this.boosts[i] > 0) boosts += this.boosts[i]; } return boosts; }; BattlePokemon.prototype.boostBy = function (boost) { var changed = false; for (var i in boost) { var delta = boost[i]; this.boosts[i] += delta; if (this.boosts[i] > 6) { delta -= this.boosts[i] - 6; this.boosts[i] = 6; } if (this.boosts[i] < -6) { delta -= this.boosts[i] - (-6); this.boosts[i] = -6; } if (delta) changed = true; } this.update(); return changed; }; BattlePokemon.prototype.clearBoosts = function () { for (var i in this.boosts) { this.boosts[i] = 0; } this.update(); }; BattlePokemon.prototype.setBoost = function (boost) { for (var i in boost) { this.boosts[i] = boost[i]; } this.update(); }; BattlePokemon.prototype.copyVolatileFrom = function (pokemon) { this.clearVolatile(); this.boosts = pokemon.boosts; for (var i in pokemon.volatiles) { if (this.battle.getEffect(i).noCopy) continue; // shallow clones this.volatiles[i] = Object.clone(pokemon.volatiles[i]); if (this.volatiles[i].linkedPokemon) { delete pokemon.volatiles[i].linkedPokemon; delete pokemon.volatiles[i].linkedStatus; this.volatiles[i].linkedPokemon.volatiles[this.volatiles[i].linkedStatus].linkedPokemon = this; } } pokemon.clearVolatile(); this.update(); for (var i in this.volatiles) { this.battle.singleEvent('Copy', this.getVolatile(i), this.volatiles[i], this); } }; BattlePokemon.prototype.transformInto = function (pokemon, user) { var template = pokemon.template; if (pokemon.fainted || pokemon.illusion || (pokemon.volatiles['substitute'] && this.battle.gen >= 5)) { return false; } if (!template.abilities || (pokemon && pokemon.transformed && this.battle.gen >= 2) || (user && user.transformed && this.battle.gen >= 5)) { return false; } if (!this.formeChange(template, true)) { return false; } this.transformed = true; this.typesData = []; for (var i = 0, l = pokemon.typesData.length; i < l; i++) { this.typesData.push({ type: pokemon.typesData[i].type, suppressed: false, isAdded: pokemon.typesData[i].isAdded }); } for (var statName in this.stats) { this.stats[statName] = pokemon.stats[statName]; } this.moveset = []; this.moves = []; this.set.ivs = (this.battle.gen >= 5 ? this.set.ivs : pokemon.set.ivs); this.hpType = (this.battle.gen >= 5 ? this.hpType : pokemon.hpType); this.hpPower = (this.battle.gen >= 5 ? this.hpPower : pokemon.hpPower); for (var i = 0; i < pokemon.moveset.length; i++) { var move = this.battle.getMove(this.set.moves[i]); var moveData = pokemon.moveset[i]; var moveName = moveData.move; if (moveData.id === 'hiddenpower') { moveName = 'Hidden Power ' + this.hpType; } this.moveset.push({ move: moveName, id: moveData.id, pp: move.noPPBoosts ? moveData.maxpp : 5, maxpp: this.battle.gen >= 5 ? (move.noPPBoosts ? moveData.maxpp : 5) : (this.battle.gen <= 2 ? move.pp : moveData.maxpp), target: moveData.target, disabled: false }); this.moves.push(toId(moveName)); } for (var j in pokemon.boosts) { this.boosts[j] = pokemon.boosts[j]; } this.battle.add('-transform', this, pokemon); this.setAbility(pokemon.ability); this.update(); return true; }; BattlePokemon.prototype.formeChange = function (template, dontRecalculateStats) { template = this.battle.getTemplate(template); if (!template.abilities) return false; this.illusion = null; this.template = template; this.types = template.types; this.typesData = []; this.types = template.types; for (var i = 0, l = this.types.length; i < l; i++) { this.typesData.push({ type: this.types[i], suppressed: false, isAdded: false }); } if (!dontRecalculateStats) { for (var statName in this.stats) { var stat = this.template.baseStats[statName]; stat = Math.floor(Math.floor(2 * stat + this.set.ivs[statName] + Math.floor(this.set.evs[statName] / 4)) * this.level / 100 + 5); // nature var nature = this.battle.getNature(this.set.nature); if (statName === nature.plus) stat *= 1.1; if (statName === nature.minus) stat *= 0.9; this.baseStats[statName] = this.stats[statName] = Math.floor(stat); } this.speed = this.stats.spe; } return true; }; BattlePokemon.prototype.clearVolatile = function (init) { this.boosts = { atk: 0, def: 0, spa: 0, spd: 0, spe: 0, accuracy: 0, evasion: 0 }; this.moveset = []; this.moves = []; // we're copying array contents // DO NOT "optimize" it to copy just the pointer // if you don't know what a pointer is, please don't // touch this code for (var i = 0; i < this.baseMoveset.length; i++) { this.moveset.push(this.baseMoveset[i]); this.moves.push(toId(this.baseMoveset[i].move)); } this.transformed = false; this.ability = this.baseAbility; this.set.ivs = this.baseIvs; this.hpType = this.baseHpType; this.hpPower = this.baseHpPower; for (var i in this.volatiles) { if (this.volatiles[i].linkedStatus) { this.volatiles[i].linkedPokemon.removeVolatile(this.volatiles[i].linkedStatus); } } this.volatiles = {}; this.switchFlag = false; this.lastMove = ''; this.moveThisTurn = ''; this.lastDamage = 0; this.lastAttackedBy = null; this.newlySwitched = true; this.beingCalledBack = false; this.formeChange(this.baseTemplate); this.update(init); }; BattlePokemon.prototype.hasType = function (type) { if (!type) return false; if (Array.isArray(type)) { for (var i = 0; i < type.length; i++) { if (this.hasType(type[i])) return true; } } else { if (this.getTypes().indexOf(type) > -1) return true; } return false; }; // returns the amount of damage actually dealt BattlePokemon.prototype.faint = function (source, effect) { if (this.fainted || this.status === 'fnt') return 0; var d = this.hp; this.hp = 0; this.switchFlag = false; this.status = 'fnt'; // this.fainted = true; this.battle.faintQueue.push({ target: this, source: source, effect: effect }); return d; }; BattlePokemon.prototype.damage = function (d, source, effect) { if (!this.hp) return 0; if (d < 1 && d > 0) d = 1; d = Math.floor(d); if (isNaN(d)) return 0; if (d <= 0) return 0; this.hp -= d; if (this.hp <= 0) { d += this.hp; this.faint(source, effect); } return d; }; BattlePokemon.prototype.tryTrap = function () { if (this.runImmunity('trapped')) { this.trapped = true; return true; } return false; }; BattlePokemon.prototype.hasMove = function (moveid) { moveid = toId(moveid); if (moveid.substr(0, 11) === 'hiddenpower') moveid = 'hiddenpower'; for (var i = 0; i < this.moveset.length; i++) { if (moveid === this.battle.getMove(this.moveset[i].move).id) { return moveid; } } return false; }; BattlePokemon.prototype.getValidMoves = function (lockedMove) { var pMoves = this.getMoves(lockedMove); var moves = []; for (var i = 0; i < pMoves.length; i++) { if (!pMoves[i].disabled) { moves.push(pMoves[i].id); } } if (!moves.length) return ['struggle']; return moves; }; // returns the amount of damage actually healed BattlePokemon.prototype.heal = function (d) { if (!this.hp) return false; d = Math.floor(d); if (isNaN(d)) return false; if (d <= 0) return false; if (this.hp >= this.maxhp) return false; this.hp += d; if (this.hp > this.maxhp) { d -= this.hp - this.maxhp; this.hp = this.maxhp; } return d; }; // sets HP, returns delta BattlePokemon.prototype.sethp = function (d) { if (!this.hp) return 0; d = Math.floor(d); if (isNaN(d)) return; if (d < 1) d = 1; d = d - this.hp; this.hp += d; if (this.hp > this.maxhp) { d -= this.hp - this.maxhp; this.hp = this.maxhp; } return d; }; BattlePokemon.prototype.trySetStatus = function (status, source, sourceEffect) { if (!this.hp) return false; if (this.status) return false; return this.setStatus(status, source, sourceEffect); }; BattlePokemon.prototype.cureStatus = function () { if (!this.hp) return false; // unlike clearStatus, gives cure message if (this.status) { this.battle.add('-curestatus', this, this.status); this.setStatus(''); } }; BattlePokemon.prototype.setStatus = function (status, source, sourceEffect, ignoreImmunities) { if (!this.hp) return false; status = this.battle.getEffect(status); if (this.battle.event) { if (!source) source = this.battle.event.source; if (!sourceEffect) sourceEffect = this.battle.effect; } if (!ignoreImmunities && status.id) { // the game currently never ignores immunities if (!this.runImmunity(status.id === 'tox' ? 'psn' : status.id)) { this.battle.debug('immune to status'); return false; } } if (this.status === status.id) return false; var prevStatus = this.status; var prevStatusData = this.statusData; if (status.id && !this.battle.runEvent('SetStatus', this, source, sourceEffect, status)) { this.battle.debug('set status [' + status.id + '] interrupted'); return false; } this.status = status.id; this.statusData = {id: status.id, target: this}; if (source) this.statusData.source = source; if (status.duration) { this.statusData.duration = status.duration; } if (status.durationCallback) { this.statusData.duration = status.durationCallback.call(this.battle, this, source, sourceEffect); } if (status.id && !this.battle.singleEvent('Start', status, this.statusData, this, source, sourceEffect)) { this.battle.debug('status start [' + status.id + '] interrupted'); // cancel the setstatus this.status = prevStatus; this.statusData = prevStatusData; return false; } this.update(); if (status.id && !this.battle.runEvent('AfterSetStatus', this, source, sourceEffect, status)) { return false; } return true; }; BattlePokemon.prototype.clearStatus = function () { // unlike cureStatus, does not give cure message return this.setStatus(''); }; BattlePokemon.prototype.getStatus = function () { return this.battle.getEffect(this.status); }; BattlePokemon.prototype.eatItem = function (item, source, sourceEffect) { if (!this.hp || !this.isActive) return false; if (!this.item) return false; var id = toId(item); if (id && this.item !== id) return false; if (!sourceEffect && this.battle.effect) sourceEffect = this.battle.effect; if (!source && this.battle.event && this.battle.event.target) source = this.battle.event.target; item = this.getItem(); if (this.battle.runEvent('UseItem', this, null, null, item) && this.battle.runEvent('EatItem', this, null, null, item)) { this.battle.add('-enditem', this, item, '[eat]'); this.battle.singleEvent('Eat', item, this.itemData, this, source, sourceEffect); this.lastItem = this.item; this.item = ''; this.itemData = {id: '', target: this}; this.usedItemThisTurn = true; this.ateBerry = true; this.battle.runEvent('AfterUseItem', this, null, null, item); return true; } return false; }; BattlePokemon.prototype.useItem = function (item, source, sourceEffect) { if (!this.isActive) return false; if (!this.item) return false; var id = toId(item); if (id && this.item !== id) return false; if (!sourceEffect && this.battle.effect) sourceEffect = this.battle.effect; if (!source && this.battle.event && this.battle.event.target) source = this.battle.event.target; item = this.getItem(); if (this.battle.runEvent('UseItem', this, null, null, item)) { switch (item.id) { case 'redcard': this.battle.add('-enditem', this, item, '[of] ' + source); break; default: if (!item.isGem) { this.battle.add('-enditem', this, item); } break; } this.battle.singleEvent('Use', item, this.itemData, this, source, sourceEffect); this.lastItem = this.item; this.item = ''; this.itemData = {id: '', target: this}; this.usedItemThisTurn = true; this.battle.runEvent('AfterUseItem', this, null, null, item); return true; } return false; }; BattlePokemon.prototype.takeItem = function (source) { if (!this.isActive) return false; if (!this.item) return false; if (!source) source = this; var item = this.getItem(); if (this.battle.runEvent('TakeItem', this, source, null, item)) { this.lastItem = ''; this.item = ''; this.itemData = {id: '', target: this}; return item; } return false; }; BattlePokemon.prototype.setItem = function (item, source, effect) { if (!this.hp || !this.isActive) return false; item = this.battle.getItem(item); this.lastItem = this.item; this.item = item.id; this.itemData = {id: item.id, target: this}; if (item.id) { this.battle.singleEvent('Start', item, this.itemData, this, source, effect); } if (this.lastItem) this.usedItemThisTurn = true; return true; }; BattlePokemon.prototype.getItem = function () { return this.battle.getItem(this.item); }; BattlePokemon.prototype.hasItem = function (item) { if (this.ignore['Item']) return false; var ownItem = this.item; if (!Array.isArray(item)) { return ownItem === toId(item); } return (item.map(toId).indexOf(ownItem) >= 0); }; BattlePokemon.prototype.clearItem = function () { return this.setItem(''); }; BattlePokemon.prototype.setAbility = function (ability, source, effect, noForce) { if (!this.hp) return false; ability = this.battle.getAbility(ability); var oldAbility = this.ability; if (noForce && oldAbility === ability.id) { return false; } if (ability.id in {illusion:1, multitype:1, stancechange:1}) return false; if (oldAbility in {multitype:1, stancechange:1}) return false; this.ability = ability.id; this.abilityData = {id: ability.id, target: this}; if (ability.id && this.battle.gen > 3) { this.battle.singleEvent('Start', ability, this.abilityData, this, source, effect); } return oldAbility; }; BattlePokemon.prototype.getAbility = function () { return this.battle.getAbility(this.ability); }; BattlePokemon.prototype.hasAbility = function (ability) { if (this.ignore['Ability']) return false; var ownAbility = this.ability; if (!Array.isArray(ability)) { return ownAbility === toId(ability); } return (ability.map(toId).indexOf(ownAbility) >= 0); }; BattlePokemon.prototype.clearAbility = function () { return this.setAbility(''); }; BattlePokemon.prototype.getNature = function () { return this.battle.getNature(this.set.nature); }; BattlePokemon.prototype.addVolatile = function (status, source, sourceEffect, linkedStatus) { var result; status = this.battle.getEffect(status); if (!this.hp && !status.affectsFainted) return false; if (this.battle.event) { if (!source) source = this.battle.event.source; if (!sourceEffect) sourceEffect = this.battle.effect; } if (this.volatiles[status.id]) { if (!status.onRestart) return false; return this.battle.singleEvent('Restart', status, this.volatiles[status.id], this, source, sourceEffect); } if (!this.runImmunity(status.id)) return false; result = this.battle.runEvent('TryAddVolatile', this, source, sourceEffect, status); if (!result) { this.battle.debug('add volatile [' + status.id + '] interrupted'); return result; } this.volatiles[status.id] = {id: status.id}; this.volatiles[status.id].target = this; if (source) { this.volatiles[status.id].source = source; this.volatiles[status.id].sourcePosition = source.position; } if (sourceEffect) { this.volatiles[status.id].sourceEffect = sourceEffect; } if (status.duration) { this.volatiles[status.id].duration = status.duration; } if (status.durationCallback) { this.volatiles[status.id].duration = status.durationCallback.call(this.battle, this, source, sourceEffect); } result = this.battle.singleEvent('Start', status, this.volatiles[status.id], this, source, sourceEffect); if (!result) { // cancel delete this.volatiles[status.id]; return result; } if (linkedStatus && source && !source.volatiles[linkedStatus]) { source.addVolatile(linkedStatus, this, sourceEffect, status); source.volatiles[linkedStatus].linkedPokemon = this; source.volatiles[linkedStatus].linkedStatus = status; this.volatiles[status].linkedPokemon = source; this.volatiles[status].linkedStatus = linkedStatus; } this.update(); return true; }; BattlePokemon.prototype.getVolatile = function (status) { status = this.battle.getEffect(status); if (!this.volatiles[status.id]) return null; return status; }; BattlePokemon.prototype.removeVolatile = function (status) { if (!this.hp) return false; status = this.battle.getEffect(status); if (!this.volatiles[status.id]) return false; this.battle.singleEvent('End', status, this.volatiles[status.id], this); var linkedPokemon = this.volatiles[status.id].linkedPokemon; var linkedStatus = this.volatiles[status.id].linkedStatus; delete this.volatiles[status.id]; if (linkedPokemon && linkedPokemon.volatiles[linkedStatus]) { linkedPokemon.removeVolatile(linkedStatus); } this.update(); return true; }; // "static" function BattlePokemon.getHealth = function (side) { if (!this.hp) return '0 fnt'; var hpstring; if ((side === true) || (this.side === side) || this.battle.getFormat().debug) { hpstring = '' + this.hp + '/' + this.maxhp; } else { var ratio = this.hp / this.maxhp; if (this.battle.reportPercentages) { // HP Percentage Mod mechanics var percentage = Math.ceil(ratio * 100); if ((percentage === 100) && (ratio < 1.0)) { percentage = 99; } hpstring = '' + percentage + '/100'; } else { // In-game accurate pixel health mechanics var pixels = Math.floor(ratio * 48) || 1; hpstring = '' + pixels + '/48'; if ((pixels === 9) && (ratio > 0.2)) { hpstring += 'y'; // force yellow HP bar } else if ((pixels === 24) && (ratio > 0.5)) { hpstring += 'g'; // force green HP bar } } } if (this.status) hpstring += ' ' + this.status; return hpstring; }; BattlePokemon.prototype.setType = function (newType, enforce) { // Arceus first type cannot be normally changed if (!enforce && this.template.num === 493) return false; this.typesData = [{ type: newType, suppressed: false, isAdded: false }]; return true; }; BattlePokemon.prototype.addType = function (newType) { // removes any types added previously and adds another one this.typesData = this.typesData.filter(function (typeData) { return !typeData.isAdded; }).concat([{ type: newType, suppressed: false, isAdded: true }]); return true; }; BattlePokemon.prototype.getTypes = function (getAll) { var types = []; for (var i = 0, l = this.typesData.length; i < l; i++) { if (getAll || !this.typesData[i].suppressed) { types.push(this.typesData[i].type); } } if (types.length) return types; if (this.battle.gen >= 5) return ['Normal']; return ['???']; }; BattlePokemon.prototype.runImmunity = function (type, message) { if (this.fainted) { return false; } if (!type || type === '???') { return true; } if (this.negateImmunity[type]) return true; if (!(this.negateImmunity['Type'] && type in this.battle.data.TypeChart)) { // Ring Target not active if (!this.battle.getImmunity(type, this)) { this.battle.debug('natural immunity'); if (message) { this.battle.add('-immune', this, '[msg]'); } return false; } } var immunity = this.battle.runEvent('Immunity', this, null, null, type); if (!immunity) { this.battle.debug('artificial immunity'); if (message && immunity !== null) { this.battle.add('-immune', this, '[msg]'); } return false; } return true; }; BattlePokemon.prototype.destroy = function () { // deallocate ourself // get rid of some possibly-circular references this.battle = null; this.side = null; }; return BattlePokemon; })(); BattleSide = (function () { function BattleSide(name, battle, n, team) { this.battle = battle; this.n = n; this.name = name; this.pokemon = []; this.active = [null]; this.sideConditions = {}; this.id = n ? 'p2' : 'p1'; switch (this.battle.gameType) { case 'doubles': this.active = [null, null]; break; case 'triples': case 'rotation': this.active = [null, null, null]; break; } this.team = this.battle.getTeam(this, team); for (var i = 0; i < this.team.length && i < 6; i++) { //console.log("NEW POKEMON: " + (this.team[i] ? this.team[i].name : '[unidentified]')); this.pokemon.push(new BattlePokemon(this.team[i], this)); } this.pokemonLeft = this.pokemon.length; for (var i = 0; i < this.pokemon.length; i++) { this.pokemon[i].position = i; } } BattleSide.prototype.isActive = false; BattleSide.prototype.pokemonLeft = 0; BattleSide.prototype.faintedLastTurn = false; BattleSide.prototype.faintedThisTurn = false; BattleSide.prototype.decision = null; BattleSide.prototype.foe = null; BattleSide.prototype.toString = function () { return this.id + ': ' + this.name; }; BattleSide.prototype.getData = function () { var data = { name: this.name, id: this.id, pokemon: [] }; for (var i = 0; i < this.pokemon.length; i++) { var pokemon = this.pokemon[i]; data.pokemon.push({ ident: pokemon.fullname, details: pokemon.details, condition: pokemon.getHealth(pokemon.side), active: (pokemon.position < pokemon.side.active.length), stats: { atk: pokemon.baseStats['atk'], def: pokemon.baseStats['def'], spa: pokemon.baseStats['spa'], spd: pokemon.baseStats['spd'], spe: pokemon.baseStats['spe'] }, moves: pokemon.moves.map(function (move) { if (move === 'hiddenpower') { return move + toId(pokemon.hpType) + (pokemon.hpPower === 70 ? '' : pokemon.hpPower); } return move; }), baseAbility: pokemon.baseAbility, item: pokemon.item, pokeball: pokemon.pokeball, canMegaEvo: pokemon.canMegaEvo }); } return data; }; BattleSide.prototype.randomActive = function () { var actives = this.active.filter(function (active) { return active && !active.fainted; }); if (!actives.length) return null; var i = Math.floor(Math.random() * actives.length); return actives[i]; }; BattleSide.prototype.addSideCondition = function (status, source, sourceEffect) { status = this.battle.getEffect(status); if (this.sideConditions[status.id]) { if (!status.onRestart) return false; return this.battle.singleEvent('Restart', status, this.sideConditions[status.id], this, source, sourceEffect); } this.sideConditions[status.id] = {id: status.id}; this.sideConditions[status.id].target = this; if (source) { this.sideConditions[status.id].source = source; this.sideConditions[status.id].sourcePosition = source.position; } if (status.duration) { this.sideConditions[status.id].duration = status.duration; } if (status.durationCallback) { this.sideConditions[status.id].duration = status.durationCallback.call(this.battle, this, source, sourceEffect); } if (!this.battle.singleEvent('Start', status, this.sideConditions[status.id], this, source, sourceEffect)) { delete this.sideConditions[status.id]; return false; } this.battle.update(); return true; }; BattleSide.prototype.getSideCondition = function (status) { status = this.battle.getEffect(status); if (!this.sideConditions[status.id]) return null; return status; }; BattleSide.prototype.removeSideCondition = function (status) { status = this.battle.getEffect(status); if (!this.sideConditions[status.id]) return false; this.battle.singleEvent('End', status, this.sideConditions[status.id], this); delete this.sideConditions[status.id]; this.battle.update(); return true; }; BattleSide.prototype.emitCallback = function () { this.battle.send('callback', this.id + "\n" + Array.prototype.slice.call(arguments).join('|')); }; BattleSide.prototype.emitRequest = function (update) { this.battle.send('request', this.id + "\n" + this.battle.rqid + "\n" + JSON.stringify(update)); }; BattleSide.prototype.destroy = function () { // deallocate ourself // deallocate children and get rid of references to them for (var i = 0; i < this.pokemon.length; i++) { if (this.pokemon[i]) this.pokemon[i].destroy(); this.pokemon[i] = null; } this.pokemon = null; for (var i = 0; i < this.active.length; i++) { this.active[i] = null; } this.active = null; if (this.decision) { delete this.decision.side; delete this.decision.pokemon; } this.decision = null; // get rid of some possibly-circular references this.battle = null; this.foe = null; }; return BattleSide; })(); Battle = (function () { var Battle = {}; Battle.construct = (function () { global.battleProtoCache = {}; return function (roomid, formatarg, rated) { var battle = Object.create((function () { if (battleProtoCache[formatarg] !== undefined) { return battleProtoCache[formatarg]; } // Scripts overrides Battle overrides Scripts overrides Tools var tools = Tools.mod(formatarg); var proto = Object.create(tools); for (var i in Battle.prototype) { proto[i] = Battle.prototype[i]; } var battle = Object.create(proto); var ret = Object.create(battle); tools.install(ret); return (battleProtoCache[formatarg] = ret); })()); Battle.prototype.init.call(battle, roomid, formatarg, rated); return battle; }; })(); Battle.prototype = {}; Battle.prototype.init = function (roomid, formatarg, rated) { var format = Tools.getFormat(formatarg); this.log = []; this.sides = [null, null]; this.roomid = roomid; this.id = roomid; this.rated = rated; this.weatherData = {id:''}; this.terrainData = {id:''}; this.pseudoWeather = {}; this.format = toId(format); this.formatData = {id:this.format}; this.effect = {id:''}; this.effectData = {id:''}; this.event = {id:''}; this.gameType = (format.gameType || 'singles'); this.queue = []; this.faintQueue = []; this.messageLog = []; // use a random initial seed (64-bit, [high -> low]) this.startingSeed = this.seed = [Math.floor(Math.random() * 0x10000), Math.floor(Math.random() * 0x10000), Math.floor(Math.random() * 0x10000), Math.floor(Math.random() * 0x10000)]; }; Battle.prototype.turn = 0; Battle.prototype.p1 = null; Battle.prototype.p2 = null; Battle.prototype.lastUpdate = 0; Battle.prototype.weather = ''; Battle.prototype.terrain = ''; Battle.prototype.ended = false; Battle.prototype.started = false; Battle.prototype.active = false; Battle.prototype.eventDepth = 0; Battle.prototype.lastMove = ''; Battle.prototype.activeMove = null; Battle.prototype.activePokemon = null; Battle.prototype.activeTarget = null; Battle.prototype.midTurn = false; Battle.prototype.currentRequest = ''; Battle.prototype.currentRequestDetails = ''; Battle.prototype.rqid = 0; Battle.prototype.lastMoveLine = 0; Battle.prototype.reportPercentages = false; Battle.prototype.toString = function () { return 'Battle: ' + this.format; }; // This function is designed to emulate the on-cartridge PRNG for Gens 3 and 4, as described in // http://www.smogon.com/ingame/rng/pid_iv_creation#pokemon_random_number_generator // This RNG uses a 32-bit initial seed // This function has three different results, depending on arguments: // - random() returns a real number in [0, 1), just like Math.random() // - random(n) returns an integer in [0, n) // - random(m, n) returns an integer in [m, n) // m and n are converted to integers via Math.floor. If the result is NaN, they are ignored. /* Battle.prototype.random = function (m, n) { this.seed = (this.seed * 0x41C64E6D + 0x6073) >>> 0; // truncate the result to the last 32 bits var result = this.seed >>> 16; // the first 16 bits of the seed are the random value m = Math.floor(m); n = Math.floor(n); return (m ? (n ? (result % (n - m)) + m : result % m) : result / 0x10000); }; */ // This function is designed to emulate the on-cartridge PRNG for Gen 5 and uses a 64-bit initial seed // This function has three different results, depending on arguments: // - random() returns a real number in [0, 1), just like Math.random() // - random(n) returns an integer in [0, n) // - random(m, n) returns an integer in [m, n) // m and n are converted to integers via Math.floor. If the result is NaN, they are ignored. Battle.prototype.random = function (m, n) { this.seed = this.nextFrame(); // Advance the RNG var result = (this.seed[0] << 16 >>> 0) + this.seed[1]; // Use the upper 32 bits m = Math.floor(m); n = Math.floor(n); result = (m ? (n ? Math.floor(result * (n - m) / 0x100000000) + m : Math.floor(result * m / 0x100000000)) : result / 0x100000000); this.debug('randBW(' + (m ? (n ? m + ', ' + n : m) : '') + ') = ' + result); return result; }; Battle.prototype.nextFrame = function (n) { var seed = this.seed; n = n || 1; for (var frame = 0; frame < n; ++frame) { // The RNG is a Linear Congruential Generator (LCG) in the form: x_{n + 1} = (a x_n + c) % m // Where: x_0 is the seed, x_n is the random number after n iterations, // a = 0x5D588B656C078965, c = 0x00269EC3 and m = 2^64 // Javascript doesnt handle such large numbers properly, so this function does it in 16-bit parts. // x_{n + 1} = (x_n * a) + c // Let any 64 bit number n = (n[0] << 48) + (n[1] << 32) + (n[2] << 16) + n[3] // Then x_{n + 1} = // ((a[3] x_n[0] + a[2] x_n[1] + a[1] x_n[2] + a[0] x_n[3] + c[0]) << 48) + // ((a[3] x_n[1] + a[2] x_n[2] + a[1] x_n[3] + c[1]) << 32) + // ((a[3] x_n[2] + a[2] x_n[3] + c[2]) << 16) + // a[3] x_n[3] + c[3] // Which can be generalised where b is the number of 16 bit words in the number: // (Notice how the a[] word starts at b-1, and decrements every time it appears again on the line; // x_n[] starts at b-<line#>-1 and increments to b-1 at the end of the line per line, limiting the length of the line; // c[] is at b-<line#>-1 for each line and the left shift is 16 * <line#>) // ((a[b-1] + x_n[b-1] + c[b-1]) << (16 * 0)) + // ((a[b-1] x_n[b-2] + a[b-2] x_n[b-1] + c[b-2]) << (16 * 1)) + // ((a[b-1] x_n[b-3] + a[b-2] x_n[b-2] + a[b-3] x_n[b-1] + c[b-3]) << (16 * 2)) + // ... // ((a[b-1] x_n[1] + a[b-2] x_n[2] + ... + a[2] x_n[b-2] + a[1] + x_n[b-1] + c[1]) << (16 * (b-2))) + // ((a[b-1] x_n[0] + a[b-2] x_n[1] + ... + a[1] x_n[b-2] + a[0] + x_n[b-1] + c[0]) << (16 * (b-1))) // Which produces this equation: \sum_{l=0}^{b-1}\left(\sum_{m=b-l-1}^{b-1}\left\{a[2b-m-l-2] x_n[m]\right\}+c[b-l-1]\ll16l\right) // This is all ignoring overflow/carry because that cannot be shown in a pseudo-mathematical equation. // The below code implements a optimised version of that equation while also checking for overflow/carry. var a = [0x5D58, 0x8B65, 0x6C07, 0x8965]; var c = [0, 0, 0x26, 0x9EC3]; var nextSeed = [0, 0, 0, 0]; var carry = 0; for (var cN = seed.length - 1; cN >= 0; --cN) { nextSeed[cN] = carry; carry = 0; var aN = seed.length - 1; var seedN = cN; for (; seedN < seed.length; --aN, ++seedN) { var nextWord = a[aN] * seed[seedN]; carry += nextWord >>> 16; nextSeed[cN] += nextWord & 0xFFFF; } nextSeed[cN] += c[cN]; carry += nextSeed[cN] >>> 16; nextSeed[cN] &= 0xFFFF; } seed = nextSeed; } return seed; }; Battle.prototype.setWeather = function (status, source, sourceEffect) { status = this.getEffect(status); if (sourceEffect === undefined && this.effect) sourceEffect = this.effect; if (source === undefined && this.event && this.event.target) source = this.event.target; if (this.weather === status.id) return false; if (this.weather && !status.id) { var oldstatus = this.getWeather(); this.singleEvent('End', oldstatus, this.weatherData, this); } var prevWeather = this.weather; var prevWeatherData = this.weatherData; this.weather = status.id; this.weatherData = {id: status.id}; if (source) { this.weatherData.source = source; this.weatherData.sourcePosition = source.position; } if (status.duration) { this.weatherData.duration = status.duration; } if (status.durationCallback) { this.weatherData.duration = status.durationCallback.call(this, source, sourceEffect); } if (!this.singleEvent('Start', status, this.weatherData, this, source, sourceEffect)) { this.weather = prevWeather; this.weatherData = prevWeatherData; return false; } this.update(); return true; }; Battle.prototype.clearWeather = function () { return this.setWeather(''); }; Battle.prototype.effectiveWeather = function (target) { if (this.event) { if (!target) target = this.event.target; } if (!this.runEvent('TryWeather', target)) return ''; return this.weather; }; Battle.prototype.isWeather = function (weather, target) { var ourWeather = this.effectiveWeather(target); if (!Array.isArray(weather)) { return ourWeather === toId(weather); } return (weather.map(toId).indexOf(ourWeather) >= 0); }; Battle.prototype.getWeather = function () { return this.getEffect(this.weather); }; Battle.prototype.setTerrain = function (status, source, sourceEffect) { status = this.getEffect(status); if (sourceEffect === undefined && this.effect) sourceEffect = this.effect; if (source === undefined && this.event && this.event.target) source = this.event.target; if (this.terrain === status.id) return false; if (this.terrain && !status.id) { var oldstatus = this.getTerrain(); this.singleEvent('End', oldstatus, this.terrainData, this); } var prevTerrain = this.terrain; var prevTerrainData = this.terrainData; this.terrain = status.id; this.terrainData = {id: status.id}; if (source) { this.terrainData.source = source; this.terrainData.sourcePosition = source.position; } if (status.duration) { this.terrainData.duration = status.duration; } if (status.durationCallback) { this.terrainData.duration = status.durationCallback.call(this, source, sourceEffect); } if (!this.singleEvent('Start', status, this.terrainData, this, source, sourceEffect)) { this.terrain = prevTerrain; this.terrainData = prevTerrainData; return false; } this.update(); return true; }; Battle.prototype.clearTerrain = function () { return this.setTerrain(''); }; Battle.prototype.effectiveTerrain = function (target) { if (this.event) { if (!target) target = this.event.target; } if (!this.runEvent('TryTerrain', target)) return ''; return this.terrain; }; Battle.prototype.isTerrain = function (terrain, target) { var ourTerrain = this.effectiveTerrain(target); if (!Array.isArray(terrain)) { return ourTerrain === toId(terrain); } return (terrain.map(toId).indexOf(ourTerrain) >= 0); }; Battle.prototype.getTerrain = function () { return this.getEffect(this.terrain); }; Battle.prototype.getFormat = function () { return this.getEffect(this.format); }; Battle.prototype.addPseudoWeather = function (status, source, sourceEffect) { status = this.getEffect(status); if (this.pseudoWeather[status.id]) { if (!status.onRestart) return false; return this.singleEvent('Restart', status, this.pseudoWeather[status.id], this, source, sourceEffect); } this.pseudoWeather[status.id] = {id: status.id}; if (source) { this.pseudoWeather[status.id].source = source; this.pseudoWeather[status.id].sourcePosition = source.position; } if (status.duration) { this.pseudoWeather[status.id].duration = status.duration; } if (status.durationCallback) { this.pseudoWeather[status.id].duration = status.durationCallback.call(this, source, sourceEffect); } if (!this.singleEvent('Start', status, this.pseudoWeather[status.id], this, source, sourceEffect)) { delete this.pseudoWeather[status.id]; return false; } this.update(); return true; }; Battle.prototype.getPseudoWeather = function (status) { status = this.getEffect(status); if (!this.pseudoWeather[status.id]) return null; return status; }; Battle.prototype.removePseudoWeather = function (status) { status = this.getEffect(status); if (!this.pseudoWeather[status.id]) return false; this.singleEvent('End', status, this.pseudoWeather[status.id], this); delete this.pseudoWeather[status.id]; this.update(); return true; }; Battle.prototype.setActiveMove = function (move, pokemon, target) { if (!move) move = null; if (!pokemon) pokemon = null; if (!target) target = pokemon; this.activeMove = move; this.activePokemon = pokemon; this.activeTarget = target; // Mold Breaker and the like this.update(); }; Battle.prototype.clearActiveMove = function (failed) { if (this.activeMove) { if (!failed) { this.lastMove = this.activeMove.id; } this.activeMove = null; this.activePokemon = null; this.activeTarget = null; // Mold Breaker and the like, again this.update(); } }; Battle.prototype.update = function () { var actives = this.p1.active; for (var i = 0; i < actives.length; i++) { if (actives[i]) actives[i].update(); } actives = this.p2.active; for (var i = 0; i < actives.length; i++) { if (actives[i]) actives[i].update(); } }; // bubbles up Battle.comparePriority = function (a, b) { // intentionally not in Battle.prototype a.priority = a.priority || 0; a.subPriority = a.subPriority || 0; a.speed = a.speed || 0; b.priority = b.priority || 0; b.subPriority = b.subPriority || 0; b.speed = b.speed || 0; if ((typeof a.order === 'number' || typeof b.order === 'number') && a.order !== b.order) { if (typeof a.order !== 'number') { return -1; } if (typeof b.order !== 'number') { return 1; } if (b.order - a.order) { return -(b.order - a.order); } } if (b.priority - a.priority) { return b.priority - a.priority; } if (b.speed - a.speed) { return b.speed - a.speed; } if (b.subOrder - a.subOrder) { return -(b.subOrder - a.subOrder); } return Math.random() - 0.5; }; Battle.prototype.getResidualStatuses = function (thing, callbackType) { var statuses = this.getRelevantEffectsInner(thing || this, callbackType || 'residualCallback', null, null, false, true, 'duration'); statuses.sort(Battle.comparePriority); //if (statuses[0]) this.debug('match ' + (callbackType || 'residualCallback') + ': ' + statuses[0].status.id); return statuses; }; Battle.prototype.eachEvent = function (eventid, effect, relayVar) { var actives = []; if (!effect && this.effect) effect = this.effect; for (var i = 0; i < this.sides.length;i++) { var side = this.sides[i]; for (var j = 0; j < side.active.length; j++) { if (side.active[j]) actives.push(side.active[j]); } } actives.sort(function (a, b) { if (b.speed - a.speed) { return b.speed - a.speed; } return Math.random() - 0.5; }); for (var i = 0; i < actives.length; i++) { if (actives[i].isStarted) { this.runEvent(eventid, actives[i], null, effect, relayVar); } } }; Battle.prototype.residualEvent = function (eventid, relayVar) { var statuses = this.getRelevantEffectsInner(this, 'on' + eventid, null, null, false, true, 'duration'); statuses.sort(Battle.comparePriority); while (statuses.length) { var statusObj = statuses.shift(); var status = statusObj.status; if (statusObj.thing.fainted) continue; if (statusObj.statusData && statusObj.statusData.duration) { statusObj.statusData.duration--; if (!statusObj.statusData.duration) { statusObj.end.call(statusObj.thing, status.id); continue; } } this.singleEvent(eventid, status, statusObj.statusData, statusObj.thing, relayVar); } }; // The entire event system revolves around this function // (and its helper functions, getRelevant * ) Battle.prototype.singleEvent = function (eventid, effect, effectData, target, source, sourceEffect, relayVar) { if (this.eventDepth >= 8) { // oh fuck this.add('message', 'STACK LIMIT EXCEEDED'); this.add('message', 'PLEASE REPORT IN BUG THREAD'); this.add('message', 'Event: ' + eventid); this.add('message', 'Parent event: ' + this.event.id); throw new Error("Stack overflow"); } //this.add('Event: ' + eventid + ' (depth ' + this.eventDepth + ')'); effect = this.getEffect(effect); var hasRelayVar = true; if (relayVar === undefined) { relayVar = true; hasRelayVar = false; } if (effect.effectType === 'Status' && target.status !== effect.id) { // it's changed; call it off return relayVar; } if (target.ignore && target.ignore[effect.effectType]) { this.debug(eventid + ' handler suppressed by Gastro Acid, Klutz or Magic Room'); return relayVar; } if (target.ignore && target.ignore[effect.effectType + 'Target']) { this.debug(eventid + ' handler suppressed by Air Lock'); return relayVar; } if (effect['on' + eventid] === undefined) return relayVar; var parentEffect = this.effect; var parentEffectData = this.effectData; var parentEvent = this.event; this.effect = effect; this.effectData = effectData; this.event = {id: eventid, target: target, source: source, effect: sourceEffect}; this.eventDepth++; var args = [target, source, sourceEffect]; if (hasRelayVar) args.unshift(relayVar); var returnVal; if (typeof effect['on' + eventid] === 'function') { returnVal = effect['on' + eventid].apply(this, args); } else { returnVal = effect['on' + eventid]; } this.eventDepth--; this.effect = parentEffect; this.effectData = parentEffectData; this.event = parentEvent; if (returnVal === undefined) return relayVar; return returnVal; }; /** * runEvent is the core of Pokemon Showdown's event system. * * Basic usage * =========== * * this.runEvent('Blah') * will trigger any onBlah global event handlers. * * this.runEvent('Blah', target) * will additionally trigger any onBlah handlers on the target, onAllyBlah * handlers on any active pokemon on the target's team, and onFoeBlah * handlers on any active pokemon on the target's foe's team * * this.runEvent('Blah', target, source) * will additionally trigger any onSourceBlah handlers on the source * * this.runEvent('Blah', target, source, effect) * will additionally pass the effect onto all event handlers triggered * * this.runEvent('Blah', target, source, effect, relayVar) * will additionally pass the relayVar as the first argument along all event * handlers * * You may leave any of these null. For instance, if you have a relayVar but * no source or effect: * this.runEvent('Damage', target, null, null, 50) * * Event handlers * ============== * * Items, abilities, statuses, and other effects like SR, confusion, weather, * or Trick Room can have event handlers. Event handlers are functions that * can modify what happens during an event. * * event handlers are passed: * function (target, source, effect) * although some of these can be blank. * * certain events have a relay variable, in which case they're passed: * function (relayVar, target, source, effect) * * Relay variables are variables that give additional information about the * event. For instance, the damage event has a relayVar which is the amount * of damage dealt. * * If a relay variable isn't passed to runEvent, there will still be a secret * relayVar defaulting to `true`, but it won't get passed to any event * handlers. * * After an event handler is run, its return value helps determine what * happens next: * 1. If the return value isn't `undefined`, relayVar is set to the return * value * 2. If relayVar is falsy, no more event handlers are run * 3. Otherwise, if there are more event handlers, the next one is run and * we go back to step 1. * 4. Once all event handlers are run (or one of them results in a falsy * relayVar), relayVar is returned by runEvent * * As a shortcut, an event handler that isn't a function will be interpreted * as a function that returns that value. * * You can have return values mean whatever you like, but in general, we * follow the convention that returning `false` or `null` means * stopping or interrupting the event. * * For instance, returning `false` from a TrySetStatus handler means that * the pokemon doesn't get statused. * * If a failed event usually results in a message like "But it failed!" * or "It had no effect!", returning `null` will suppress that message and * returning `false` will display it. Returning `null` is useful if your * event handler already gave its own custom failure message. * * Returning `undefined` means "don't change anything" or "keep going". * A function that does nothing but return `undefined` is the equivalent * of not having an event handler at all. * * Returning a value means that that value is the new `relayVar`. For * instance, if a Damage event handler returns 50, the damage event * will deal 50 damage instead of whatever it was going to deal before. * * Useful values * ============= * * In addition to all the methods and attributes of Tools, Battle, and * Scripts, event handlers have some additional values they can access: * * this.effect: * the Effect having the event handler * this.effectData: * the data store associated with the above Effect. This is a plain Object * and you can use it to store data for later event handlers. * this.effectData.target: * the Pokemon, Side, or Battle that the event handler's effect was * attached to. * this.event.id: * the event ID * this.event.target, this.event.source, this.event.effect: * the target, source, and effect of the event. These are the same * variables that are passed as arguments to the event handler, but * they're useful for functions called by the event handler. */ Battle.prototype.runEvent = function (eventid, target, source, effect, relayVar, onEffect) { if (this.eventDepth >= 8) { // oh fuck this.add('message', 'STACK LIMIT EXCEEDED'); this.add('message', 'PLEASE REPORT IN BUG THREAD'); this.add('message', 'Event: ' + eventid); this.add('message', 'Parent event: ' + this.event.id); throw new Error("Stack overflow"); } if (!target) target = this; var statuses = this.getRelevantEffects(target, 'on' + eventid, 'onSource' + eventid, source); var hasRelayVar = true; effect = this.getEffect(effect); var args = [target, source, effect]; //console.log('Event: ' + eventid + ' (depth ' + this.eventDepth + ') t:' + target.id + ' s:' + (!source || source.id) + ' e:' + effect.id); if (relayVar === undefined || relayVar === null) { relayVar = true; hasRelayVar = false; } else { args.unshift(relayVar); } var parentEvent = this.event; this.event = {id: eventid, target: target, source: source, effect: effect, modifier: 1}; this.eventDepth++; if (onEffect && 'on' + eventid in effect) { statuses.unshift({status: effect, callback: effect['on' + eventid], statusData: {}, end: null, thing: target}); } for (var i = 0; i < statuses.length; i++) { var status = statuses[i].status; var thing = statuses[i].thing; //this.debug('match ' + eventid + ': ' + status.id + ' ' + status.effectType); if (status.effectType === 'Status' && thing.status !== status.id) { // it's changed; call it off continue; } if (thing.ignore && thing.ignore[status.effectType] === 'A') { // ignore attacking events var AttackingEvents = { BeforeMove: 1, BasePower: 1, Immunity: 1, Accuracy: 1, RedirectTarget: 1, Damage: 1, SubDamage: 1, Heal: 1, TakeItem: 1, UseItem: 1, EatItem: 1, SetStatus: 1, CriticalHit: 1, ModifyPokemon: 1, ModifyAtk: 1, ModifyDef: 1, ModifySpA: 1, ModifySpD: 1, ModifySpe: 1, ModifyBoost: 1, ModifyDamage: 1, TryHit: 1, TryHitSide: 1, TrySecondaryHit: 1, Hit: 1, Boost: 1, DragOut: 1 }; if (eventid in AttackingEvents) { if (eventid !== 'ModifyPokemon') { this.debug(eventid + ' handler suppressed by Mold Breaker'); } continue; } } else if (thing.ignore && thing.ignore[status.effectType]) { if (eventid !== 'ModifyPokemon' && eventid !== 'Update') { this.debug(eventid + ' handler suppressed by Gastro Acid, Klutz or Magic Room'); } continue; } if (target.ignore && (target.ignore[status.effectType + 'Target'] || target.ignore[eventid + 'Target'])) { this.debug(eventid + ' handler suppressed by Air Lock'); continue; } var returnVal; if (typeof statuses[i].callback === 'function') { var parentEffect = this.effect; var parentEffectData = this.effectData; this.effect = statuses[i].status; this.effectData = statuses[i].statusData; this.effectData.target = thing; returnVal = statuses[i].callback.apply(this, args); this.effect = parentEffect; this.effectData = parentEffectData; } else { returnVal = statuses[i].callback; } if (returnVal !== undefined) { relayVar = returnVal; if (!relayVar) break; if (hasRelayVar) { args[0] = relayVar; } } } this.eventDepth--; if (this.event.modifier !== 1 && typeof relayVar === 'number') { // this.debug(eventid + ' modifier: 0x' + ('0000' + (this.event.modifier * 4096).toString(16)).slice(-4).toUpperCase()); relayVar = this.modify(relayVar, this.event.modifier); } this.event = parentEvent; return relayVar; }; Battle.prototype.resolveLastPriority = function (statuses, callbackType) { var order = false; var priority = 0; var subOrder = 0; var status = statuses[statuses.length - 1]; if (status.status[callbackType + 'Order']) { order = status.status[callbackType + 'Order']; } if (status.status[callbackType + 'Priority']) { priority = status.status[callbackType + 'Priority']; } else if (status.status[callbackType + 'SubOrder']) { subOrder = status.status[callbackType + 'SubOrder']; } status.order = order; status.priority = priority; status.subOrder = subOrder; if (status.thing && status.thing.getStat) status.speed = status.thing.speed; }; // bubbles up to parents Battle.prototype.getRelevantEffects = function (thing, callbackType, foeCallbackType, foeThing) { var statuses = this.getRelevantEffectsInner(thing, callbackType, foeCallbackType, foeThing, true, false); statuses.sort(Battle.comparePriority); //if (statuses[0]) this.debug('match ' + callbackType + ': ' + statuses[0].status.id); return statuses; }; Battle.prototype.getRelevantEffectsInner = function (thing, callbackType, foeCallbackType, foeThing, bubbleUp, bubbleDown, getAll) { if (!callbackType || !thing) return []; var statuses = []; var status; if (thing.sides) { for (var i in this.pseudoWeather) { status = this.getPseudoWeather(i); if (status[callbackType] !== undefined || (getAll && thing.pseudoWeather[i][getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: this.pseudoWeather[i], end: this.removePseudoWeather, thing: thing}); this.resolveLastPriority(statuses, callbackType); } } status = this.getWeather(); if (status[callbackType] !== undefined || (getAll && thing.weatherData[getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: this.weatherData, end: this.clearWeather, thing: thing, priority: status[callbackType + 'Priority'] || 0}); this.resolveLastPriority(statuses, callbackType); } status = this.getTerrain(); if (status[callbackType] !== undefined || (getAll && thing.terrainData[getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: this.terrainData, end: this.clearTerrain, thing: thing, priority: status[callbackType + 'Priority'] || 0}); this.resolveLastPriority(statuses, callbackType); } status = this.getFormat(); if (status[callbackType] !== undefined || (getAll && thing.formatData[getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: this.formatData, end: function (){}, thing: thing, priority: status[callbackType + 'Priority'] || 0}); this.resolveLastPriority(statuses, callbackType); } if (bubbleDown) { statuses = statuses.concat(this.getRelevantEffectsInner(this.p1, callbackType, null, null, false, true, getAll)); statuses = statuses.concat(this.getRelevantEffectsInner(this.p2, callbackType, null, null, false, true, getAll)); } return statuses; } if (thing.pokemon) { for (var i in thing.sideConditions) { status = thing.getSideCondition(i); if (status[callbackType] !== undefined || (getAll && thing.sideConditions[i][getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: thing.sideConditions[i], end: thing.removeSideCondition, thing: thing}); this.resolveLastPriority(statuses, callbackType); } } if (foeCallbackType) { statuses = statuses.concat(this.getRelevantEffectsInner(thing.foe, foeCallbackType, null, null, false, false, getAll)); } if (bubbleUp) { statuses = statuses.concat(this.getRelevantEffectsInner(this, callbackType, null, null, true, false, getAll)); } if (bubbleDown) { for (var i = 0;i < thing.active.length;i++) { statuses = statuses.concat(this.getRelevantEffectsInner(thing.active[i], callbackType, null, null, false, true, getAll)); } } return statuses; } if (!thing.getStatus) { this.debug(JSON.stringify(thing)); return statuses; } var status = thing.getStatus(); if (status[callbackType] !== undefined || (getAll && thing.statusData[getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: thing.statusData, end: thing.clearStatus, thing: thing}); this.resolveLastPriority(statuses, callbackType); } for (var i in thing.volatiles) { status = thing.getVolatile(i); if (status[callbackType] !== undefined || (getAll && thing.volatiles[i][getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: thing.volatiles[i], end: thing.removeVolatile, thing: thing}); this.resolveLastPriority(statuses, callbackType); } } status = thing.getAbility(); if (status[callbackType] !== undefined || (getAll && thing.abilityData[getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: thing.abilityData, end: thing.clearAbility, thing: thing}); this.resolveLastPriority(statuses, callbackType); } status = thing.getItem(); if (status[callbackType] !== undefined || (getAll && thing.itemData[getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: thing.itemData, end: thing.clearItem, thing: thing}); this.resolveLastPriority(statuses, callbackType); } status = this.getEffect(thing.template.baseSpecies); if (status[callbackType] !== undefined) { statuses.push({status: status, callback: status[callbackType], statusData: thing.speciesData, end: function (){}, thing: thing}); this.resolveLastPriority(statuses, callbackType); } if (foeThing && foeCallbackType && foeCallbackType.substr(0, 8) !== 'onSource') { statuses = statuses.concat(this.getRelevantEffectsInner(foeThing, foeCallbackType, null, null, false, false, getAll)); } else if (foeCallbackType) { var foeActive = thing.side.foe.active; var allyActive = thing.side.active; var eventName = ''; if (foeCallbackType.substr(0, 8) === 'onSource') { eventName = foeCallbackType.substr(8); if (foeThing) { statuses = statuses.concat(this.getRelevantEffectsInner(foeThing, foeCallbackType, null, null, false, false, getAll)); } foeCallbackType = 'onFoe' + eventName; foeThing = null; } if (foeCallbackType.substr(0, 5) === 'onFoe') { eventName = foeCallbackType.substr(5); for (var i = 0; i < allyActive.length; i++) { if (!allyActive[i] || allyActive[i].fainted) continue; statuses = statuses.concat(this.getRelevantEffectsInner(allyActive[i], 'onAlly' + eventName, null, null, false, false, getAll)); statuses = statuses.concat(this.getRelevantEffectsInner(allyActive[i], 'onAny' + eventName, null, null, false, false, getAll)); } for (var i = 0; i < foeActive.length; i++) { if (!foeActive[i] || foeActive[i].fainted) continue; statuses = statuses.concat(this.getRelevantEffectsInner(foeActive[i], 'onAny' + eventName, null, null, false, false, getAll)); } } for (var i = 0; i < foeActive.length; i++) { if (!foeActive[i] || foeActive[i].fainted) continue; statuses = statuses.concat(this.getRelevantEffectsInner(foeActive[i], foeCallbackType, null, null, false, false, getAll)); } } if (bubbleUp) { statuses = statuses.concat(this.getRelevantEffectsInner(thing.side, callbackType, foeCallbackType, null, true, false, getAll)); } return statuses; }; Battle.prototype.getPokemon = function (id) { if (typeof id !== 'string') id = id.id; for (var i = 0; i < this.p1.pokemon.length; i++) { var pokemon = this.p1.pokemon[i]; if (pokemon.id === id) return pokemon; } for (var i = 0; i < this.p2.pokemon.length; i++) { var pokemon = this.p2.pokemon[i]; if (pokemon.id === id) return pokemon; } return null; }; Battle.prototype.makeRequest = function (type, requestDetails) { if (type) { this.currentRequest = type; this.currentRequestDetails = requestDetails || ''; this.rqid++; this.p1.decision = null; this.p2.decision = null; } else { type = this.currentRequest; requestDetails = this.currentRequestDetails; } this.update(); // default to no request var p1request = null; var p2request = null; this.p1.currentRequest = ''; this.p2.currentRequest = ''; switch (type) { case 'switch': var switchTable = []; var active; for (var i=0, l=this.p1.active.length; i<l; i++) { active = this.p1.active[i]; switchTable.push(!!(active && active.switchFlag)); } if (switchTable.any(true)) { this.p1.currentRequest = 'switch'; p1request = {forceSwitch: switchTable, side: this.p1.getData(), rqid: this.rqid}; } switchTable = []; for (var i=0, l=this.p2.active.length; i<l; i++) { active = this.p2.active[i]; switchTable.push(!!(active && active.switchFlag)); } if (switchTable.any(true)) { this.p2.currentRequest = 'switch'; p2request = {forceSwitch: switchTable, side: this.p2.getData(), rqid: this.rqid}; } break; case 'teampreview': this.add('teampreview' + (requestDetails ? '|' + requestDetails : '')); this.p1.currentRequest = 'teampreview'; p1request = {teamPreview: true, side: this.p1.getData(), rqid: this.rqid}; this.p2.currentRequest = 'teampreview'; p2request = {teamPreview: true, side: this.p2.getData(), rqid: this.rqid}; break; default: var activeData; this.p1.currentRequest = 'move'; activeData = this.p1.active.map(function (pokemon) { if (pokemon) return pokemon.getRequestData(); }); p1request = {active: activeData, side: this.p1.getData(), rqid: this.rqid}; this.p2.currentRequest = 'move'; activeData = this.p2.active.map(function (pokemon) { if (pokemon) return pokemon.getRequestData(); }); p2request = {active: activeData, side: this.p2.getData(), rqid: this.rqid}; break; } if (this.p1 && this.p2) { var inactiveSide = -1; if (p1request && !p2request) { inactiveSide = 0; } else if (!p1request && p2request) { inactiveSide = 1; } if (inactiveSide !== this.inactiveSide) { this.send('inactiveside', inactiveSide); this.inactiveSide = inactiveSide; } } if (p1request) { this.p1.emitRequest(p1request); } else { this.p1.decision = true; this.p1.emitRequest({wait: true, side: this.p1.getData()}); } if (p2request) { this.p2.emitRequest(p2request); } else { this.p2.decision = true; this.p2.emitRequest({wait: true, side: this.p2.getData()}); } if (this.p2.decision && this.p1.decision) { if (this.p2.decision === true && this.p1.decision === true) { if (type !== 'move') { // TODO: investigate this race condition; should be fixed // properly later return this.makeRequest('move'); } this.add('html', '<div class="broadcast-red"><b>The battle crashed</b></div>'); this.win(); } else { // some kind of weird race condition? this.commitDecisions(); } return; } }; Battle.prototype.tie = function () { this.win(); }; Battle.prototype.win = function (side) { if (this.ended) { return false; } if (side === 'p1' || side === 'p2') { side = this[side]; } else if (side !== this.p1 && side !== this.p2) { side = null; } this.winner = side ? side.name : ''; this.add(''); if (side) { this.add('win', side.name); } else { this.add('tie'); } this.ended = true; this.active = false; this.currentRequest = ''; this.currentRequestDetails = ''; return true; }; Battle.prototype.switchIn = function (pokemon, pos) { if (!pokemon || pokemon.isActive) return false; if (!pos) pos = 0; var side = pokemon.side; if (pos >= side.active.length) { throw new Error("Invalid switch position"); } if (side.active[pos]) { var oldActive = side.active[pos]; var lastMove = null; lastMove = this.getMove(oldActive.lastMove); if (oldActive.switchCopyFlag === 'copyvolatile') { delete oldActive.switchCopyFlag; pokemon.copyVolatileFrom(oldActive); } } this.runEvent('BeforeSwitchIn', pokemon); if (side.active[pos]) { var oldActive = side.active[pos]; oldActive.isActive = false; oldActive.isStarted = false; oldActive.position = pokemon.position; pokemon.position = pos; side.pokemon[pokemon.position] = pokemon; side.pokemon[oldActive.position] = oldActive; this.cancelMove(oldActive); oldActive.clearVolatile(); } side.active[pos] = pokemon; pokemon.isActive = true; pokemon.activeTurns = 0; for (var m in pokemon.moveset) { pokemon.moveset[m].used = false; } this.add('switch', pokemon, pokemon.getDetails); pokemon.update(); this.runEvent('SwitchIn', pokemon); this.addQueue({pokemon: pokemon, choice: 'runSwitch'}); }; Battle.prototype.canSwitch = function (side) { var canSwitchIn = []; for (var i = side.active.length; i < side.pokemon.length; i++) { var pokemon = side.pokemon[i]; if (!pokemon.fainted) { canSwitchIn.push(pokemon); } } return canSwitchIn.length; }; Battle.prototype.getRandomSwitchable = function (side) { var canSwitchIn = []; for (var i = side.active.length; i < side.pokemon.length; i++) { var pokemon = side.pokemon[i]; if (!pokemon.fainted) { canSwitchIn.push(pokemon); } } if (!canSwitchIn.length) { return null; } return canSwitchIn[this.random(canSwitchIn.length)]; }; Battle.prototype.dragIn = function (side, pos) { if (pos >= side.active.length) return false; var pokemon = this.getRandomSwitchable(side); if (!pos) pos = 0; if (!pokemon || pokemon.isActive) return false; this.runEvent('BeforeSwitchIn', pokemon); if (side.active[pos]) { var oldActive = side.active[pos]; if (!oldActive.hp) { return false; } if (!this.runEvent('DragOut', oldActive)) { return false; } this.runEvent('SwitchOut', oldActive); oldActive.isActive = false; oldActive.isStarted = false; oldActive.position = pokemon.position; pokemon.position = pos; side.pokemon[pokemon.position] = pokemon; side.pokemon[oldActive.position] = oldActive; this.cancelMove(oldActive); oldActive.clearVolatile(); } side.active[pos] = pokemon; pokemon.isActive = true; pokemon.activeTurns = 0; for (var m in pokemon.moveset) { pokemon.moveset[m].used = false; } this.add('drag', pokemon, pokemon.getDetails); pokemon.update(); this.runEvent('SwitchIn', pokemon); this.addQueue({pokemon: pokemon, choice: 'runSwitch'}); return true; }; Battle.prototype.swapPosition = function (pokemon, slot, attributes) { if (slot >= pokemon.side.active.length) { throw new Error("Invalid swap position"); } var target = pokemon.side.active[slot]; if (slot !== 1 && (!target || target.fainted)) return false; this.add('swap', pokemon, slot, attributes || ''); var side = pokemon.side; side.pokemon[pokemon.position] = target; side.pokemon[slot] = pokemon; side.active[pokemon.position] = side.pokemon[pokemon.position]; side.active[slot] = side.pokemon[slot]; if (target) target.position = pokemon.position; pokemon.position = slot; return true; }; Battle.prototype.faint = function (pokemon, source, effect) { pokemon.faint(source, effect); }; Battle.prototype.nextTurn = function () { this.turn++; for (var i = 0; i < this.sides.length; i++) { for (var j = 0; j < this.sides[i].active.length; j++) { var pokemon = this.sides[i].active[j]; if (!pokemon) continue; pokemon.moveThisTurn = ''; pokemon.usedItemThisTurn = false; pokemon.newlySwitched = false; if (pokemon.lastAttackedBy) { pokemon.lastAttackedBy.thisTurn = false; } pokemon.activeTurns++; } this.sides[i].faintedLastTurn = this.sides[i].faintedThisTurn; this.sides[i].faintedThisTurn = false; } this.add('turn', this.turn); if (this.gameType === 'triples' && this.sides.map('pokemonLeft').count(1) === this.sides.length) { // If only 2 pokemon are left in triples, they must touch each other. var center = false; for (var i = 0; i < this.sides.length; i++) { for (var j = 0; j < this.sides[i].active.length; j++) { if (!this.sides[i].active[j] || this.sides[i].active[j].fainted) continue; if (this.sides[i].active[j].position === 1) break; this.swapPosition(this.sides[i].active[j], 1, '[silent]'); center = true; break; } } if (center) this.add('-message', 'Automatic center!'); } this.makeRequest('move'); }; Battle.prototype.start = function () { if (this.active) return; if (!this.p1 || !this.p1.isActive || !this.p2 || !this.p2.isActive) { // need two players to start return; } this.p2.emitRequest({side: this.p2.getData()}); this.p1.emitRequest({side: this.p1.getData()}); if (this.started) { this.makeRequest(); this.isActive = true; this.activeTurns = 0; return; } this.isActive = true; this.activeTurns = 0; this.started = true; this.p2.foe = this.p1; this.p1.foe = this.p2; this.add('gametype', this.gameType); this.add('gen', this.gen); var format = this.getFormat(); Tools.mod(format.mod).getBanlistTable(format); // fill in format ruleset this.add('tier', format.name); if (this.rated) { this.add('rated'); } if (format && format.ruleset) { for (var i = 0; i < format.ruleset.length; i++) { this.addPseudoWeather(format.ruleset[i]); } } if (!this.p1.pokemon[0] || !this.p2.pokemon[0]) { this.add('message', 'Battle not started: One of you has an empty team.'); return; } this.residualEvent('TeamPreview'); this.addQueue({choice:'start'}); this.midTurn = true; if (!this.currentRequest) this.go(); }; Battle.prototype.boost = function (boost, target, source, effect) { if (this.event) { if (!target) target = this.event.target; if (!source) source = this.event.source; if (!effect) effect = this.effect; } if (!target || !target.hp) return 0; effect = this.getEffect(effect); boost = this.runEvent('Boost', target, source, effect, Object.clone(boost)); var success = false; for (var i in boost) { var currentBoost = {}; currentBoost[i] = boost[i]; if (boost[i] !== 0 && target.boostBy(currentBoost)) { success = true; var msg = '-boost'; if (boost[i] < 0) { msg = '-unboost'; boost[i] = -boost[i]; } switch (effect.id) { case 'intimidate': case 'gooey': this.add(msg, target, i, boost[i]); break; default: if (effect.effectType === 'Move') { this.add(msg, target, i, boost[i]); } else { this.add(msg, target, i, boost[i], '[from] ' + effect.fullname); } break; } this.runEvent('AfterEachBoost', target, source, effect, currentBoost); } } this.runEvent('AfterBoost', target, source, effect, boost); return success; }; Battle.prototype.damage = function (damage, target, source, effect, instafaint) { if (this.event) { if (!target) target = this.event.target; if (!source) source = this.event.source; if (!effect) effect = this.effect; } if (!target || !target.hp) return 0; effect = this.getEffect(effect); if (!(damage || damage === 0)) return damage; if (damage !== 0) damage = this.clampIntRange(damage, 1); if (effect.id !== 'struggle-recoil') { // Struggle recoil is not affected by effects if (effect.effectType === 'Weather' && !target.runImmunity(effect.id)) { this.debug('weather immunity'); return 0; } damage = this.runEvent('Damage', target, source, effect, damage); if (!(damage || damage === 0)) { this.debug('damage event failed'); return damage; } if (target.illusion && effect && effect.effectType === 'Move') { this.debug('illusion cleared'); target.illusion = null; this.add('replace', target, target.getDetails); } } if (damage !== 0) damage = this.clampIntRange(damage, 1); damage = target.damage(damage, source, effect); if (source) source.lastDamage = damage; var name = effect.fullname; if (name === 'tox') name = 'psn'; switch (effect.id) { case 'partiallytrapped': this.add('-damage', target, target.getHealth, '[from] ' + this.effectData.sourceEffect.fullname, '[partiallytrapped]'); break; default: if (effect.effectType === 'Move') { this.add('-damage', target, target.getHealth); } else if (source && source !== target) { this.add('-damage', target, target.getHealth, '[from] ' + effect.fullname, '[of] ' + source); } else { this.add('-damage', target, target.getHealth, '[from] ' + name); } break; } if (effect.drain && source) { this.heal(Math.ceil(damage * effect.drain[0] / effect.drain[1]), source, target, 'drain'); } if (instafaint && !target.hp) { this.debug('instafaint: '+this.faintQueue.map('target').map('name')); this.faintMessages(true); } else { damage = this.runEvent('AfterDamage', target, source, effect, damage); } return damage; }; Battle.prototype.directDamage = function (damage, target, source, effect) { if (this.event) { if (!target) target = this.event.target; if (!source) source = this.event.source; if (!effect) effect = this.effect; } if (!target || !target.hp) return 0; if (!damage) return 0; damage = this.clampIntRange(damage, 1); damage = target.damage(damage, source, effect); switch (effect.id) { case 'strugglerecoil': this.add('-damage', target, target.getHealth, '[from] recoil'); break; case 'confusion': this.add('-damage', target, target.getHealth, '[from] confusion'); break; default: this.add('-damage', target, target.getHealth); break; } if (target.fainted) this.faint(target); return damage; }; Battle.prototype.heal = function (damage, target, source, effect) { if (this.event) { if (!target) target = this.event.target; if (!source) source = this.event.source; if (!effect) effect = this.effect; } effect = this.getEffect(effect); if (damage && damage <= 1) damage = 1; damage = Math.floor(damage); // for things like Liquid Ooze, the Heal event still happens when nothing is healed. damage = this.runEvent('TryHeal', target, source, effect, damage); if (!damage) return 0; if (!target || !target.hp) return 0; if (target.hp >= target.maxhp) return 0; damage = target.heal(damage, source, effect); switch (effect.id) { case 'leechseed': case 'rest': this.add('-heal', target, target.getHealth, '[silent]'); break; case 'drain': this.add('-heal', target, target.getHealth, '[from] drain', '[of] ' + source); break; case 'wish': break; default: if (effect.effectType === 'Move') { this.add('-heal', target, target.getHealth); } else if (source && source !== target) { this.add('-heal', target, target.getHealth, '[from] ' + effect.fullname, '[of] ' + source); } else { this.add('-heal', target, target.getHealth, '[from] ' + effect.fullname); } break; } this.runEvent('Heal', target, source, effect, damage); return damage; }; Battle.prototype.chain = function (previousMod, nextMod) { // previousMod or nextMod can be either a number or an array [numerator, denominator] if (previousMod.length) previousMod = Math.floor(previousMod[0] * 4096 / previousMod[1]); else previousMod = Math.floor(previousMod * 4096); if (nextMod.length) nextMod = Math.floor(nextMod[0] * 4096 / nextMod[1]); else nextMod = Math.floor(nextMod * 4096); return ((previousMod * nextMod + 2048) >> 12) / 4096; // M'' = ((M * M') + 0x800) >> 12 }; Battle.prototype.chainModify = function (numerator, denominator) { var previousMod = Math.floor(this.event.modifier * 4096); if (numerator.length) { denominator = numerator[1]; numerator = numerator[0]; } var nextMod = 0; if (this.event.ceilModifier) { nextMod = Math.ceil(numerator * 4096 / (denominator || 1)); } else { nextMod = Math.floor(numerator * 4096 / (denominator || 1)); } this.event.modifier = ((previousMod * nextMod + 2048) >> 12) / 4096; }; Battle.prototype.modify = function (value, numerator, denominator) { // You can also use: // modify(value, [numerator, denominator]) // modify(value, fraction) - assuming you trust JavaScript's floating-point handler if (!denominator) denominator = 1; if (numerator && numerator.length) { denominator = numerator[1]; numerator = numerator[0]; } var modifier = Math.floor(numerator * 4096 / denominator); return Math.floor((value * modifier + 2048 - 1) / 4096); }; Battle.prototype.getCategory = function (move) { move = this.getMove(move); return move.category || 'Physical'; }; Battle.prototype.getDamage = function (pokemon, target, move, suppressMessages) { if (typeof move === 'string') move = this.getMove(move); if (typeof move === 'number') move = { basePower: move, type: '???', category: 'Physical' }; if (move.affectedByImmunities) { if (!target.runImmunity(move.type, true)) { return false; } } if (move.isSoundBased && (pokemon !== target || this.gen <= 4)) { if (!target.runImmunity('sound', true)) { return false; } } if (move.ohko) { if (target.level > pokemon.level) { return false; } return target.maxhp; } if (move.damageCallback) { return move.damageCallback.call(this, pokemon, target); } if (move.damage === 'level') { return pokemon.level; } if (move.damage) { return move.damage; } if (!move) { move = {}; } if (!move.type) move.type = '???'; var type = move.type; // '???' is typeless damage: used for Struggle and Confusion etc var category = this.getCategory(move); var defensiveCategory = move.defensiveCategory || category; var basePower = move.basePower; if (move.basePowerCallback) { basePower = move.basePowerCallback.call(this, pokemon, target, move); } if (!basePower) { if (basePower === 0) return; // returning undefined means not dealing damage return basePower; } basePower = this.clampIntRange(basePower, 1); var critMult; if (this.gen <= 5) { move.critRatio = this.clampIntRange(move.critRatio, 0, 5); critMult = [0, 16, 8, 4, 3, 2]; } else { move.critRatio = this.clampIntRange(move.critRatio, 0, 4); critMult = [0, 16, 8, 2, 1]; } move.crit = move.willCrit || false; if (move.willCrit === undefined) { if (move.critRatio) { move.crit = (this.random(critMult[move.critRatio]) === 0); } } if (move.crit) { move.crit = this.runEvent('CriticalHit', target, null, move); } // happens after crit calculation basePower = this.runEvent('BasePower', pokemon, target, move, basePower, true); if (!basePower) return 0; basePower = this.clampIntRange(basePower, 1); var level = pokemon.level; var attacker = pokemon; var defender = target; var attackStat = category === 'Physical' ? 'atk' : 'spa'; var defenseStat = defensiveCategory === 'Physical' ? 'def' : 'spd'; var statTable = {atk:'Atk', def:'Def', spa:'SpA', spd:'SpD', spe:'Spe'}; var attack; var defense; var atkBoosts = move.useTargetOffensive ? defender.boosts[attackStat] : attacker.boosts[attackStat]; var defBoosts = move.useSourceDefensive ? attacker.boosts[defenseStat] : defender.boosts[defenseStat]; var ignoreNegativeOffensive = !!move.ignoreNegativeOffensive; var ignorePositiveDefensive = !!move.ignorePositiveDefensive; if (move.crit) { ignoreNegativeOffensive = true; ignorePositiveDefensive = true; } var ignoreOffensive = !!(move.ignoreOffensive || (ignoreNegativeOffensive && atkBoosts < 0)); var ignoreDefensive = !!(move.ignoreDefensive || (ignorePositiveDefensive && defBoosts > 0)); if (ignoreOffensive) { this.debug('Negating (sp)atk boost/penalty.'); atkBoosts = 0; } if (ignoreDefensive) { this.debug('Negating (sp)def boost/penalty.'); defBoosts = 0; } if (move.useTargetOffensive) attack = defender.calculateStat(attackStat, atkBoosts); else attack = attacker.calculateStat(attackStat, atkBoosts); if (move.useSourceDefensive) defense = attacker.calculateStat(defenseStat, defBoosts); else defense = defender.calculateStat(defenseStat, defBoosts); // Apply Stat Modifiers attack = this.runEvent('Modify' + statTable[attackStat], attacker, defender, move, attack); defense = this.runEvent('Modify' + statTable[defenseStat], defender, attacker, move, defense); //int(int(int(2 * L / 5 + 2) * A * P / D) / 50); var baseDamage = Math.floor(Math.floor(Math.floor(2 * level / 5 + 2) * basePower * attack / defense) / 50) + 2; // multi-target modifier (doubles only) if (move.spreadHit) { var spreadModifier = move.spreadModifier || 0.75; this.debug('Spread modifier: ' + spreadModifier); baseDamage = this.modify(baseDamage, spreadModifier); } // weather modifier (TODO: relocate here) // crit if (move.crit) { if (!suppressMessages) this.add('-crit', target); baseDamage = this.modify(baseDamage, move.critModifier || (this.gen >= 6 ? 1.5 : 2)); } // randomizer // this is not a modifier // gen 1-2 //var randFactor = Math.floor(Math.random() * 39) + 217; //baseDamage *= Math.floor(randFactor * 100 / 255) / 100; baseDamage = Math.floor(baseDamage * (100 - this.random(16)) / 100); // STAB if (move.hasSTAB || type !== '???' && pokemon.hasType(type)) { // The "???" type never gets STAB // Not even if you Roost in Gen 4 and somehow manage to use // Struggle in the same turn. // (On second thought, it might be easier to get a Missingno.) baseDamage = this.modify(baseDamage, move.stab || 1.5); } // types var totalTypeMod = 0; if (target.negateImmunity[move.type] !== 'IgnoreEffectiveness' || this.getImmunity(move.type, target)) { totalTypeMod = this.getEffectiveness(move, target, pokemon); } totalTypeMod = this.clampIntRange(totalTypeMod, -6, 6); if (totalTypeMod > 0) { if (!suppressMessages) this.add('-supereffective', target); for (var i = 0; i < totalTypeMod; i++) { baseDamage *= 2; } } if (totalTypeMod < 0) { if (!suppressMessages) this.add('-resisted', target); for (var i = 0; i > totalTypeMod; i--) { baseDamage = Math.floor(baseDamage / 2); } } if (basePower && !Math.floor(baseDamage)) { return 1; } // Final modifier. Modifiers that modify damage after min damage check, such as Life Orb. baseDamage = this.runEvent('ModifyDamage', pokemon, target, move, baseDamage); return Math.floor(baseDamage); }; /** * Returns whether a proposed target for a move is valid. */ Battle.prototype.validTargetLoc = function (targetLoc, source, targetType) { var numSlots = source.side.active.length; if (!Math.abs(targetLoc) && Math.abs(targetLoc) > numSlots) return false; var sourceLoc = -(source.position + 1); var isFoe = (targetLoc > 0); var isAdjacent = (isFoe ? Math.abs(-(numSlots + 1 - targetLoc) - sourceLoc) <= 1 : Math.abs(targetLoc - sourceLoc) === 1); var isSelf = (sourceLoc === targetLoc); switch (targetType) { case 'randomNormal': case 'normal': return isAdjacent; case 'adjacentAlly': return isAdjacent && !isFoe; case 'adjacentAllyOrSelf': return isAdjacent && !isFoe || isSelf; case 'adjacentFoe': return isAdjacent && isFoe; case 'any': return !isSelf; } return false; }; Battle.prototype.getTargetLoc = function (target, source) { if (target.side === source.side) { return -(target.position + 1); } else { return target.position + 1; } }; Battle.prototype.validTarget = function (target, source, targetType) { return this.validTargetLoc(this.getTargetLoc(target, source), source, targetType); }; Battle.prototype.getTarget = function (decision) { var move = this.getMove(decision.move); var target; if ((move.target !== 'randomNormal') && this.validTargetLoc(decision.targetLoc, decision.pokemon, move.target)) { if (decision.targetLoc > 0) { target = decision.pokemon.side.foe.active[decision.targetLoc - 1]; } else { target = decision.pokemon.side.active[-decision.targetLoc - 1]; } if (target) { if (!target.fainted) { // target exists and is not fainted return target; } else if (target.side === decision.pokemon.side) { // fainted allied targets don't retarget return false; } } // chosen target not valid, retarget randomly with resolveTarget } if (!decision.targetPosition || !decision.targetSide) { target = this.resolveTarget(decision.pokemon, decision.move); decision.targetSide = target.side; decision.targetPosition = target.position; } return decision.targetSide.active[decision.targetPosition]; }; Battle.prototype.resolveTarget = function (pokemon, move) { // A move was used without a chosen target // For instance: Metronome chooses Ice Beam. Since the user didn't // choose a target when choosing Metronome, Ice Beam's target must // be chosen randomly. // The target is chosen randomly from possible targets, EXCEPT that // moves that can target either allies or foes will only target foes // when used without an explicit target. move = this.getMove(move); if (move.target === 'adjacentAlly') { var adjacentAllies = [pokemon.side.active[pokemon.position - 1], pokemon.side.active[pokemon.position + 1]].filter(function (active) { return active && !active.fainted; }); if (adjacentAllies.length) return adjacentAllies[Math.floor(Math.random() * adjacentAllies.length)]; return pokemon; } if (move.target === 'self' || move.target === 'all' || move.target === 'allySide' || move.target === 'allyTeam' || move.target === 'adjacentAllyOrSelf') { return pokemon; } if (pokemon.side.active.length > 2) { if (move.target === 'adjacentFoe' || move.target === 'normal' || move.target === 'randomNormal') { var foeActives = pokemon.side.foe.active; var frontPosition = foeActives.length - 1 - pokemon.position; var adjacentFoes = foeActives.slice(frontPosition < 1 ? 0 : frontPosition - 1, frontPosition + 2).filter(function (active) { return active && !active.fainted; }); if (adjacentFoes.length) return adjacentFoes[Math.floor(Math.random() * adjacentFoes.length)]; // no valid target at all, return a foe for any possible redirection } } return pokemon.side.foe.randomActive() || pokemon.side.foe.active[0]; }; Battle.prototype.checkFainted = function () { function check(a) { if (!a) return; if (a.fainted) { a.switchFlag = true; } } this.p1.active.forEach(check); this.p2.active.forEach(check); }; Battle.prototype.faintMessages = function (lastFirst) { if (this.ended) return; if (lastFirst && this.faintQueue.length) { this.faintQueue.unshift(this.faintQueue.pop()); } var faintData; while (this.faintQueue.length) { faintData = this.faintQueue.shift(); if (!faintData.target.fainted) { this.add('faint', faintData.target); this.runEvent('Faint', faintData.target, faintData.source, faintData.effect); faintData.target.fainted = true; faintData.target.isActive = false; faintData.target.isStarted = false; faintData.target.side.pokemonLeft--; faintData.target.side.faintedThisTurn = true; } } if (!this.p1.pokemonLeft && !this.p2.pokemonLeft) { this.win(faintData && faintData.target.side); return true; } if (!this.p1.pokemonLeft) { this.win(this.p2); return true; } if (!this.p2.pokemonLeft) { this.win(this.p1); return true; } return false; }; Battle.prototype.addQueue = function (decision, noSort, side) { if (decision) { if (Array.isArray(decision)) { for (var i = 0; i < decision.length; i++) { this.addQueue(decision[i], noSort); } return; } if (!decision.side && side) decision.side = side; if (!decision.side && decision.pokemon) decision.side = decision.pokemon.side; if (!decision.choice && decision.move) decision.choice = 'move'; if (!decision.priority) { var priorities = { 'beforeTurn': 100, 'beforeTurnMove': 99, 'switch': 6, 'runSwitch': 6.1, 'megaEvo': 5.9, 'residual': -100, 'team': 102, 'start': 101 }; if (priorities[decision.choice]) { decision.priority = priorities[decision.choice]; } } if (decision.choice === 'move') { if (this.getMove(decision.move).beforeTurnCallback) { this.addQueue({choice: 'beforeTurnMove', pokemon: decision.pokemon, move: decision.move, targetLoc: decision.targetLoc}, true); } } else if (decision.choice === 'switch') { if (decision.pokemon.switchFlag && decision.pokemon.switchFlag !== true) { decision.pokemon.switchCopyFlag = decision.pokemon.switchFlag; } decision.pokemon.switchFlag = false; if (!decision.speed && decision.pokemon && decision.pokemon.isActive) decision.speed = decision.pokemon.speed; } if (decision.move) { var target; if (!decision.targetPosition) { target = this.resolveTarget(decision.pokemon, decision.move); decision.targetSide = target.side; decision.targetPosition = target.position; } decision.move = this.getMoveCopy(decision.move); if (!decision.priority) { var priority = decision.move.priority; priority = this.runEvent('ModifyPriority', decision.pokemon, target, decision.move, priority); decision.priority = priority; // In Gen 6, Quick Guard blocks moves with artificially enhanced priority. if (this.gen > 5) decision.move.priority = priority; } } if (!decision.pokemon && !decision.speed) decision.speed = 1; if (!decision.speed && decision.choice === 'switch' && decision.target) decision.speed = decision.target.speed; if (!decision.speed) decision.speed = decision.pokemon.speed; if (decision.choice === 'switch' && !decision.side.pokemon[0].isActive) { // if there's no actives, switches happen before activations decision.priority = 6.2; } this.queue.push(decision); } if (!noSort) { this.queue.sort(Battle.comparePriority); } }; Battle.prototype.prioritizeQueue = function (decision, source, sourceEffect) { if (this.event) { if (!source) source = this.event.source; if (!sourceEffect) sourceEffect = this.effect; } for (var i = 0; i < this.queue.length; i++) { if (this.queue[i] === decision) { this.queue.splice(i, 1); break; } } decision.sourceEffect = sourceEffect; this.queue.unshift(decision); }; Battle.prototype.willAct = function () { for (var i = 0; i < this.queue.length; i++) { if (this.queue[i].choice === 'move' || this.queue[i].choice === 'switch' || this.queue[i].choice === 'shift') { return this.queue[i]; } } return null; }; Battle.prototype.willMove = function (pokemon) { for (var i = 0; i < this.queue.length; i++) { if (this.queue[i].choice === 'move' && this.queue[i].pokemon === pokemon) { return this.queue[i]; } } return null; }; Battle.prototype.cancelDecision = function (pokemon) { var success = false; for (var i = 0; i < this.queue.length; i++) { if (this.queue[i].pokemon === pokemon) { this.queue.splice(i, 1); i--; success = true; } } return success; }; Battle.prototype.cancelMove = function (pokemon) { for (var i = 0; i < this.queue.length; i++) { if (this.queue[i].choice === 'move' && this.queue[i].pokemon === pokemon) { this.queue.splice(i, 1); return true; } } return false; }; Battle.prototype.willSwitch = function (pokemon) { for (var i = 0; i < this.queue.length; i++) { if (this.queue[i].choice === 'switch' && this.queue[i].pokemon === pokemon) { return true; } } return false; }; Battle.prototype.runDecision = function (decision) { var pokemon; // returns whether or not we ended in a callback switch (decision.choice) { case 'start': // I GIVE UP, WILL WRESTLE WITH EVENT SYSTEM LATER var beginCallback = this.getFormat().onBegin; if (beginCallback) beginCallback.call(this); this.add('start'); for (var pos = 0; pos < this.p1.active.length; pos++) { this.switchIn(this.p1.pokemon[pos], pos); } for (var pos = 0; pos < this.p2.active.length; pos++) { this.switchIn(this.p2.pokemon[pos], pos); } for (var pos = 0; pos < this.p1.pokemon.length; pos++) { pokemon = this.p1.pokemon[pos]; this.singleEvent('Start', this.getEffect(pokemon.species), pokemon.speciesData, pokemon); } for (var pos = 0; pos < this.p2.pokemon.length; pos++) { pokemon = this.p2.pokemon[pos]; this.singleEvent('Start', this.getEffect(pokemon.species), pokemon.speciesData, pokemon); } this.midTurn = true; break; case 'move': if (!decision.pokemon.isActive) return false; if (decision.pokemon.fainted) return false; this.runMove(decision.move, decision.pokemon, this.getTarget(decision), decision.sourceEffect); break; case 'megaEvo': if (this.runMegaEvo) this.runMegaEvo(decision.pokemon); break; case 'beforeTurnMove': if (!decision.pokemon.isActive) return false; if (decision.pokemon.fainted) return false; this.debug('before turn callback: ' + decision.move.id); var target = this.getTarget(decision); if (!target) return false; decision.move.beforeTurnCallback.call(this, decision.pokemon, target); break; case 'event': this.runEvent(decision.event, decision.pokemon); break; case 'team': var i = parseInt(decision.team[0], 10) - 1; if (i >= 6 || i < 0) return; if (decision.team[1]) { // validate the choice var len = decision.side.pokemon.length; var newPokemon = [null, null, null, null, null, null].slice(0, len); for (var j = 0; j < len; j++) { var i = parseInt(decision.team[j], 10) - 1; newPokemon[j] = decision.side.pokemon[i]; } var reject = false; for (var j = 0; j < len; j++) { if (!newPokemon[j]) reject = true; } if (!reject) { for (var j = 0; j < len; j++) { newPokemon[j].position = j; } decision.side.pokemon = newPokemon; return; } } if (i === 0) return; pokemon = decision.side.pokemon[i]; if (!pokemon) return; decision.side.pokemon[i] = decision.side.pokemon[0]; decision.side.pokemon[0] = pokemon; decision.side.pokemon[i].position = i; decision.side.pokemon[0].position = 0; // we return here because the update event would crash since there are no active pokemon yet return; case 'pass': if (!decision.priority || decision.priority <= 101) return; if (decision.pokemon) { decision.pokemon.switchFlag = false; } break; case 'switch': if (decision.pokemon) { decision.pokemon.beingCalledBack = true; var lastMove = this.getMove(decision.pokemon.lastMove); if (lastMove.selfSwitch !== 'copyvolatile') { this.runEvent('BeforeSwitchOut', decision.pokemon); } if (!this.runEvent('SwitchOut', decision.pokemon)) { // Warning: DO NOT interrupt a switch-out // if you just want to trap a pokemon. // To trap a pokemon and prevent it from switching out, // (e.g. Mean Look, Magnet Pull) use the 'trapped' flag // instead. // Note: Nothing in BW or earlier interrupts // a switch-out. break; } } if (decision.pokemon && !decision.pokemon.hp && !decision.pokemon.fainted) { // a pokemon fainted from Pursuit before it could switch if (this.gen <= 4) { // in gen 2-4, the switch still happens decision.priority = -101; this.queue.unshift(decision); this.debug('Pursuit target fainted'); break; } // in gen 5+, the switch is cancelled this.debug('A Pokemon can\'t switch between when it runs out of HP and when it faints'); break; } if (decision.target.isActive) { this.debug('Switch target is already active'); break; } this.switchIn(decision.target, decision.pokemon.position); //decision.target.runSwitchIn(); break; case 'runSwitch': decision.pokemon.isStarted = true; if (!decision.pokemon.fainted) { this.singleEvent('Start', decision.pokemon.getAbility(), decision.pokemon.abilityData, decision.pokemon); this.singleEvent('Start', decision.pokemon.getItem(), decision.pokemon.itemData, decision.pokemon); } break; case 'shift': if (!decision.pokemon.isActive) return false; if (decision.pokemon.fainted) return false; this.swapPosition(decision.pokemon, 1); break; case 'beforeTurn': this.eachEvent('BeforeTurn'); break; case 'residual': this.add(''); this.clearActiveMove(true); this.residualEvent('Residual'); break; } // phazing (Roar, etc) var self = this; function checkForceSwitchFlag(a) { if (!a) return false; if (a.hp && a.forceSwitchFlag) { self.dragIn(a.side, a.position); } delete a.forceSwitchFlag; } this.p1.active.forEach(checkForceSwitchFlag); this.p2.active.forEach(checkForceSwitchFlag); this.clearActiveMove(); // fainting this.faintMessages(); if (this.ended) return true; // switching (fainted pokemon, U-turn, Baton Pass, etc) if (!this.queue.length || (this.gen <= 3 && this.queue[0].choice in {move:1,residual:1})) { // in gen 3 or earlier, switching in fainted pokemon is done after // every move, rather than only at the end of the turn. this.checkFainted(); } else if (decision.choice === 'pass') { this.eachEvent('Update'); return false; } function hasSwitchFlag(a) { return a ? a.switchFlag : false; } function removeSwitchFlag(a) { if (a) a.switchFlag = false; } var p1switch = this.p1.active.any(hasSwitchFlag); var p2switch = this.p2.active.any(hasSwitchFlag); if (p1switch && !this.canSwitch(this.p1)) { this.p1.active.forEach(removeSwitchFlag); p1switch = false; } if (p2switch && !this.canSwitch(this.p2)) { this.p2.active.forEach(removeSwitchFlag); p2switch = false; } if (p1switch || p2switch) { if (this.gen <= 1) { // in gen 1, fainting ends the turn; residuals do not happen this.queue = []; } this.makeRequest('switch'); return true; } this.eachEvent('Update'); return false; }; Battle.prototype.go = function () { this.add(''); if (this.currentRequest) { this.currentRequest = ''; this.currentRequestDetails = ''; } if (!this.midTurn) { this.queue.push({choice:'residual', priority: -100}); this.queue.push({choice:'beforeTurn', priority: 100}); this.midTurn = true; } this.addQueue(null); while (this.queue.length) { var decision = this.queue.shift(); this.runDecision(decision); if (this.currentRequest) { return; } if (this.ended) return; } this.nextTurn(); this.midTurn = false; this.queue = []; }; /** * Changes a pokemon's decision. * * The un-modded game should not use this function for anything, * since it rerolls speed ties (which messes up RNG state). * * You probably want the OverrideDecision event (which doesn't * change priority order). */ Battle.prototype.changeDecision = function (pokemon, decision) { this.cancelDecision(pokemon); if (!decision.pokemon) decision.pokemon = pokemon; this.addQueue(decision); }; /** * Takes a choice string passed from the client. Starts the next * turn if all required choices have been made. */ Battle.prototype.choose = function (sideid, choice, rqid) { var side = null; if (sideid === 'p1' || sideid === 'p2') side = this[sideid]; // This condition should be impossible because the sideid comes // from our forked process and if the player id were invalid, we would // not have even got to this function. if (!side) return; // wtf // This condition can occur if the client sends a decision at the // wrong time. if (!side.currentRequest) return; // Make sure the decision is for the right request. if ((rqid !== undefined) && (parseInt(rqid, 10) !== this.rqid)) { return; } // It should be impossible for choice not to be a string. Choice comes // from splitting the string sent by our forked process, not from the // client. However, just in case, we maintain this check for now. if (typeof choice === 'string') choice = choice.split(','); side.decision = this.parseChoice(choice, side); if (this.p1.decision && this.p2.decision) { this.commitDecisions(); } }; Battle.prototype.commitDecisions = function () { if (this.p1.decision !== true) { this.addQueue(this.p1.decision, true, this.p1); } if (this.p2.decision !== true) { this.addQueue(this.p2.decision, true, this.p2); } this.currentRequest = ''; this.currentRequestDetails = ''; this.p1.currentRequest = ''; this.p2.currentRequest = ''; this.p1.decision = true; this.p2.decision = true; this.go(); }; Battle.prototype.undoChoice = function (sideid) { var side = null; if (sideid === 'p1' || sideid === 'p2') side = this[sideid]; // The following condition can never occur for the reasons given in // the choose() function above. if (!side) return; // wtf // This condition can occur. if (!side.currentRequest) return; if (side.decision && side.decision.finalDecision) { this.debug("Can't cancel decision: the last pokemon could have been trapped"); return; } side.decision = false; }; /** * Parses a choice string passed from a client into a decision object * usable by PS's engine. * * Choice validation is also done here. */ Battle.prototype.parseChoice = function (choices, side) { var prevSwitches = {}; if (!side.currentRequest) return true; if (typeof choices === 'string') choices = choices.split(','); var decisions = []; var len = choices.length; if (side.currentRequest === 'move') len = side.active.length; var freeSwitchCount = {'switch':0, 'pass':0}; if (side.currentRequest === 'switch') { var canSwitch = side.active.filter(function (mon) {return mon && mon.switchFlag;}).length; freeSwitchCount['switch'] = Math.min(canSwitch, side.pokemon.slice(side.active.length).filter(function (mon) {return !mon.fainted;}).length); freeSwitchCount['pass'] = canSwitch - freeSwitchCount['switch']; } for (var i = 0; i < len; i++) { var choice = (choices[i] || '').trim(); var data = ''; var firstSpaceIndex = choice.indexOf(' '); if (firstSpaceIndex >= 0) { data = choice.substr(firstSpaceIndex + 1).trim(); choice = choice.substr(0, firstSpaceIndex).trim(); } switch (side.currentRequest) { case 'teampreview': if (choice !== 'team' || i > 0) return false; break; case 'move': if (i >= side.active.length) return false; if (!side.pokemon[i] || side.pokemon[i].fainted) { decisions.push({ choice: 'pass' }); continue; } if (choice !== 'move' && choice !== 'switch' && choice !== 'shift') { if (i === 0) return false; // fallback choice = 'move'; data = '1'; } break; case 'switch': if (i >= side.active.length) return false; if (!side.active[i] || !side.active[i].switchFlag) { if (choice !== 'pass') choices.splice(i, 0, 'pass'); decisions.push({ choice: 'pass', pokemon: side.active[i], priority: 102 }); continue; } if (choice !== 'switch' && choice !== 'pass') return false; freeSwitchCount[choice]--; break; default: return false; } switch (choice) { case 'team': decisions.push({ choice: 'team', side: side, team: data }); break; case 'switch': if (i > side.active.length || i > side.pokemon.length) continue; if (side.currentRequest === 'move') { if (side.pokemon[i].trapped) { //this.debug("Can't switch: The active pokemon is trapped"); side.emitCallback('trapped', i); return false; } else if (side.pokemon[i].maybeTrapped) { var finalDecision = true; for (var j = i + 1; j < side.active.length; ++j) { if (side.active[j] && !side.active[j].fainted) { finalDecision = false; } } decisions.finalDecision = decisions.finalDecision || finalDecision; } } data = parseInt(data, 10) - 1; if (data < 0) data = 0; if (data > side.pokemon.length - 1) data = side.pokemon.length - 1; if (!side.pokemon[data]) { this.debug("Can't switch: You can't switch to a pokemon that doesn't exist"); return false; } if (data === i) { this.debug("Can't switch: You can't switch to yourself"); return false; } if (data < side.active.length) { this.debug("Can't switch: You can't switch to an active pokemon"); return false; } if (side.pokemon[data].fainted) { this.debug("Can't switch: You can't switch to a fainted pokemon"); return false; } if (prevSwitches[data]) { this.debug("Can't switch: You can't switch to pokemon already queued to be switched"); return false; } prevSwitches[data] = true; decisions.push({ choice: 'switch', priority: (side.currentRequest === 'switch' ? 101 : undefined), pokemon: side.pokemon[i], target: side.pokemon[data] }); break; case 'shift': if (i > side.active.length || i > side.pokemon.length) continue; if (this.gameType !== 'triples') { this.debug("Can't shift: You can't shift a pokemon to the center except in a triple battle"); return false; } if (i === 1) { this.debug("Can't shift: You can't shift a pokemon to its own position"); return false; } decisions.push({ choice: 'shift', pokemon: side.pokemon[i] }); break; case 'move': var targetLoc = 0; var pokemon = side.pokemon[i]; var lockedMove = pokemon.getLockedMove(); var validMoves = pokemon.getValidMoves(lockedMove); var moveid = ''; if (data.substr(data.length - 2) === ' 1') targetLoc = 1; if (data.substr(data.length - 2) === ' 2') targetLoc = 2; if (data.substr(data.length - 2) === ' 3') targetLoc = 3; if (data.substr(data.length - 3) === ' -1') targetLoc = -1; if (data.substr(data.length - 3) === ' -2') targetLoc = -2; if (data.substr(data.length - 3) === ' -3') targetLoc = -3; if (targetLoc) data = data.substr(0, data.lastIndexOf(' ')); if (lockedMove) targetLoc = (this.runEvent('LockMoveTarget', pokemon) || 0); if (data.substr(data.length - 5) === ' mega') { if (!lockedMove) { decisions.push({ choice: 'megaEvo', pokemon: pokemon }); } data = data.substr(0, data.length - 5); } if (data.search(/^[0-9]+$/) >= 0) { moveid = validMoves[parseInt(data, 10) - 1]; } else { moveid = toId(data); if (moveid.substr(0, 11) === 'hiddenpower') { moveid = 'hiddenpower'; } if (validMoves.indexOf(moveid) < 0) { moveid = ''; } } if (!moveid) { moveid = validMoves[0]; } decisions.push({ choice: 'move', pokemon: pokemon, targetLoc: targetLoc, move: moveid }); break; case 'pass': if (i > side.active.length || i > side.pokemon.length) continue; if (side.currentRequest !== 'switch') { this.debug("No se pudo pasar el turno."); return false; } decisions.push({ choice: 'pass', priority: 102, pokemon: side.active[i] }); } } if (freeSwitchCount['switch'] !== 0 || freeSwitchCount['pass'] !== 0) return false; return decisions; }; Battle.prototype.add = function () { var parts = Array.prototype.slice.call(arguments); var functions = parts.map(function (part) { return typeof part === 'function'; }); if (functions.indexOf(true) < 0) { this.log.push('|' + parts.join('|')); } else { this.log.push('|split'); var sides = [null, this.sides[0], this.sides[1], true]; for (var i = 0; i < sides.length; ++i) { var line = ''; for (var j = 0; j < parts.length; ++j) { line += '|'; if (functions[j]) { line += parts[j](sides[i]); } else { line += parts[j]; } } this.log.push(line); } } }; Battle.prototype.addMove = function () { this.lastMoveLine = this.log.length; this.log.push('|' + Array.prototype.slice.call(arguments).join('|')); }; Battle.prototype.attrLastMove = function () { this.log[this.lastMoveLine] += '|' + Array.prototype.slice.call(arguments).join('|'); }; Battle.prototype.debug = function (activity) { if (this.getFormat().debug) { this.add('debug', activity); } }; Battle.prototype.debugError = function (activity) { this.add('debug', activity); }; // players Battle.prototype.join = function (slot, name, avatar, team) { if (this.p1 && this.p1.isActive && this.p2 && this.p2.isActive) return false; if ((this.p1 && this.p1.isActive && this.p1.name === name) || (this.p2 && this.p2.isActive && this.p2.name === name)) return false; if (this.p1 && this.p1.isActive || slot === 'p2') { if (this.started) { this.p2.name = name; } else { //console.log("NEW SIDE: " + name); this.p2 = new BattleSide(name, this, 1, team); this.sides[1] = this.p2; } if (avatar) this.p2.avatar = avatar; this.p2.isActive = true; this.add('player', 'p2', this.p2.name, avatar); } else { if (this.started) { this.p1.name = name; } else { //console.log("NEW SIDE: " + name); this.p1 = new BattleSide(name, this, 0, team); this.sides[0] = this.p1; } if (avatar) this.p1.avatar = avatar; this.p1.isActive = true; this.add('player', 'p1', this.p1.name, avatar); } this.start(); return true; }; Battle.prototype.rename = function (slot, name, avatar) { if (slot === 'p1' || slot === 'p2') { var side = this[slot]; side.name = name; if (avatar) side.avatar = avatar; this.add('player', slot, name, side.avatar); } }; Battle.prototype.leave = function (slot) { if (slot === 'p1' || slot === 'p2') { var side = this[slot]; if (!side) { console.log('**** ' + slot + ' tried to leave before it was possible in ' + this.id); require('./crashlogger.js')({stack: '**** ' + slot + ' tried to leave before it was possible in ' + this.id}, 'A simulator process'); return; } side.emitRequest(null); side.isActive = false; this.add('player', slot); this.active = false; } return true; }; // IPC // Messages sent by this function are received and handled in // Simulator.prototype.receive in simulator.js (in another process). Battle.prototype.send = function (type, data) { if (Array.isArray(data)) data = data.join("\n"); battleEngineFakeProcess.client.send(this.id + "\n" + type + "\n" + data); }; // This function is called by this process's 'message' event. Battle.prototype.receive = function (data, more) { this.messageLog.push(data.join(' ')); var logPos = this.log.length; var alreadyEnded = this.ended; switch (data[1]) { case 'join': var team = null; try { if (more) team = Tools.fastUnpackTeam(more); } catch (e) { console.log('TEAM PARSE ERROR: ' + more); team = null; } this.join(data[2], data[3], data[4], team); break; case 'rename': this.rename(data[2], data[3], data[4]); break; case 'leave': this.leave(data[2]); break; case 'chat': this.add('chat', data[2], more); break; case 'win': case 'tie': this.win(data[2]); break; case 'choose': this.choose(data[2], data[3], data[4]); break; case 'undo': this.undoChoice(data[2]); break; case 'eval': var battle = this; var p1 = this.p1; var p2 = this.p2; var p1active = p1 ? p1.active[0] : null; var p2active = p2 ? p2.active[0] : null; var target = data.slice(2).join('|').replace(/\f/g, '\n'); this.add('', '>>> ' + target); try { this.add('', '<<< ' + eval(target)); } catch (e) { this.add('', '<<< error: ' + e.message); } break; } this.sendUpdates(logPos, alreadyEnded); }; Battle.prototype.sendUpdates = function (logPos, alreadyEnded) { if (this.p1 && this.p2) { var inactiveSide = -1; if (!this.p1.isActive && this.p2.isActive) { inactiveSide = 0; } else if (this.p1.isActive && !this.p2.isActive) { inactiveSide = 1; } else if (!this.p1.decision && this.p2.decision) { inactiveSide = 0; } else if (this.p1.decision && !this.p2.decision) { inactiveSide = 1; } if (inactiveSide !== this.inactiveSide) { this.send('inactiveside', inactiveSide); this.inactiveSide = inactiveSide; } } if (this.log.length > logPos) { if (alreadyEnded !== undefined && this.ended && !alreadyEnded) { if (this.rated) { var log = { turns: this.turn, p1: this.p1.name, p2: this.p2.name, p1team: this.p1.team, p2team: this.p2.team, log: this.log }; this.send('log', JSON.stringify(log)); } this.send('score', [this.p1.pokemonLeft, this.p2.pokemonLeft]); this.send('winupdate', [this.winner].concat(this.log.slice(logPos))); } else { this.send('update', this.log.slice(logPos)); } } }; Battle.prototype.destroy = function () { // deallocate ourself // deallocate children and get rid of references to them for (var i = 0; i < this.sides.length; i++) { if (this.sides[i]) this.sides[i].destroy(); this.sides[i] = null; } this.p1 = null; this.p2 = null; for (var i = 0; i < this.queue.length; i++) { delete this.queue[i].pokemon; delete this.queue[i].side; this.queue[i] = null; } this.queue = null; // in case the garbage collector really sucks, at least deallocate the log this.log = null; // remove from battle list Battles[this.id] = null; }; return Battle; })(); exports.BattlePokemon = BattlePokemon; exports.BattleSide = BattleSide; exports.Battle = Battle;
import * as EditorChanges from '../change/editor'; const EditorController = { [EditorChanges.SELECT_ENTITY]: (event, store) => { store.state.globals.editor.selectedEntity = event.data.entity; } }; export default EditorController;
// @flow import SimpleChanMsgPlugin from 'plugins/SimpleChanMsgPlugin'; import Norbert from 'lib/Norbert'; import template from 'lib/template'; export function stripTimestamps(input:string) { return input.replace(/.*?([^\w\s]?[+%@&~]?[a-z])/i, '$1').trim(); } export default class QuotePlugin extends SimpleChanMsgPlugin { getName() { return "Quote"; } getHelp() { return template.getObject('Quote.help'); } getCommands() { return { addQuote: this.addQuote.bind(this), quote: this.quote.bind(this) }; } init(norbert:Norbert) { super.init(norbert); this.log.trace({ tableInit: { table: 'quotes' } }); norbert.db.run("" + "CREATE TABLE IF NOT EXISTS quotes (" + "ID INTEGER PRIMARY KEY," + "added_by TEXT, " + "channel TEXT, " + "quote TEXT, " + "created INTEGER" + ")"); } reset(norbert:Norbert) { norbert.db.run("TRUNCATE TABLE quotes"); } quote(channel:string, sender:string, message:string, norbert:Norbert) { const stmt = norbert.db.prepare('SELECT ID, added_by, quote FROM quotes WHERE channel=? LIMIT 1'); this.log.trace({ quote: { channel: channel, "requested by": sender, message: message } }); stmt.all([channel.toLowerCase()], (err, rows) => { for(const row of rows) { let msg = template('Quote.fetched', {ID: row.ID, addedBy: row.added_by, quote: row.quote}); this.log.trace("Fetched quote: " + msg); norbert.client.say(channel, msg); } }); } addQuote(channel:string, sender:string, message:string, norbert:Norbert) { const stmt = norbert.db.prepare('INSERT INTO quotes (added_by, channel, quote, created) ' + 'VALUES (?, ?, ?, ?)'); channel = channel.toLowerCase(); const stripped = stripTimestamps(message); const created = new Date().getTime(); this.log.trace({ addQuote: { sender: sender, channel: channel, created: created, message: stripped } }, "Preparing to insert quote"); stmt.run([sender, channel, stripped, created], err => { if(err) { norbert.client.say(channel, template('error')); this.log.error(err, "Error inserting quote."); } else { norbert.client.say(channel, template('Quote.inserted', {sender})); } }); } }
var conversationController = require(global.__main_root + 'controllers/api/v1/ConversationController.js'); var conversationRouteValidator = require(global.__main_root + 'validators/api/v1/ConversationRouteValidator.js'); var createNewConversation = { path: '/api/v1/conversations', method: 'POST', config: { id: 'create_new_conversation', description: 'Creates new conversation', handler: conversationController.createNewConversation, validate: conversationRouteValidator.createNewConversation() } }; module.exports = [createNewConversation];
(function() { var isBrowser = (typeof window !== 'undefined'); //TODO: performance optimization -- merge geometries. http://learningthreejs.com/blog/2011/10/05/performance-merging-geometry/ function _ObstacleBoxFactory(THREE) { var textureLoader = new THREE.TextureLoader(); var obstacleBoxTexture1 = (isBrowser) ? textureLoader.load("textures/crate1.png") : null; var obstacleBoxTexture2 = (isBrowser) ? textureLoader.load("textures/crate2.png") : null; var obstacleBoxTexture3 = (isBrowser) ? textureLoader.load("textures/crate3.png") : null; var obstacleBoxTexture4 = (isBrowser) ? textureLoader.load("textures/crate4.png") : null; var obstacleBoxTexture5 = (isBrowser) ? textureLoader.load("textures/crate5.png") : null; function getTexture(type) { if (type == 1) return obstacleBoxTexture1; else if (type == 2) return obstacleBoxTexture2; else if (type == 3) return obstacleBoxTexture3; else if (type == 4) return obstacleBoxTexture4; else return obstacleBoxTexture5; } const size = 10; var boxGeometry = new THREE.BoxGeometry(size, size, size); function ObstacleBox(type, originX, originY) { var boxMaterial = new THREE.MeshLambertMaterial({ map: getTexture(type), }); THREE.Mesh.call(this, boxGeometry, boxMaterial); this.position.set(originX + 5, originY + 5, 5); this.castShadow = true; this.receiveShadow = true; this.collisionWidth = size; this.collisionHeight = size; } ObstacleBox.prototype = Object.create(THREE.Mesh.prototype); return ObstacleBox; } if (isBrowser) { window.ObstacleBox = _ObstacleBoxFactory(THREE); } else { module.exports = _ObstacleBoxFactory; } })();
var aCenters = []; function generateCenters(iLvl, mostleft, center) { aCenters.push(center); if (iLvl !== 9) { if (mostleft) { //gen up center if (center.y % 2) { //odd generateCenters(iLvl+1, true, { x: center.x, y: center.y - 3 }); } else { generateCenters(iLvl+1, true, { x: center.x - 1, y: center.y - 3 }); } } //gen right center generateCenters(iLvl+1, false, { x: center.x + 2, y: center.y - 2 }); } } generateCenters(0, true, { x: 6, y: 28 }); console.log("Count: ", aCenters.length); console.log(JSON.stringify(aCenters));
(function () { 'use strict'; angular .module('money.login') .run(webRun); webRun.$inject = ['routerHelper']; /* @ngInject */ function webRun(routerHelper) { routerHelper.configureStates(getStates()); } function getStates() { return [{ state: 'login', config: { url: '/login', templateUrl: 'login/login.view.html', controller: 'LoginController', controllerAs: 'vm' } }]; } })();
var CryptoJS = require('crypto-js'); var secretKey = 'bgvyzdsv'; var mine = function(secretKey) { var num = 0; var hash = CryptoJS.MD5(secretKey + num).toString(CryptoJS.enc.hex); while (hash.slice(0,6) !== '000000') { num++; hash = CryptoJS.MD5(secretKey + num).toString(CryptoJS.enc.hex); } console.log('Found hash ' + hash); console.log('Number added: ' + num); } mine(secretKey);
const altForEachImplReplacement = require('./common-replacements').altForEachImplReplacement , altForEachUseReplacement = require('./common-replacements').altForEachUseReplacement , altIndexOfImplReplacement = require('./common-replacements').altIndexOfImplReplacement , altIndexOfUseReplacement = require('./common-replacements').altIndexOfUseReplacement module.exports.all = [ [ /require\(['"]stream['"]\)/g , 'require(\'../../\')' ] // some tests need stream.Stream but readable.js doesn't offer that // and we've undone it with the previous replacement , [ /stream\.Stream|require\('\.\.\/\.\.\/'\)\.Stream/g , 'require(\'stream\').Stream' ] , [ /require\(['"](_stream_\w+)['"]\)/g , 'require(\'../../lib/$1\')' ] , [ /Stream.(Readable|Writable|Duplex|Transform|PassThrough)/g , 'require(\'../../\').$1' ] ] module.exports['test-stream2-basic.js'] = [ altForEachImplReplacement , altForEachUseReplacement ] module.exports['test-stream2-objects.js'] = [ altForEachImplReplacement , altForEachUseReplacement ] module.exports['test-stream2-transform.js'] = [ altForEachImplReplacement , altForEachUseReplacement ] module.exports['test-stream2-writable.js'] = [ altForEachImplReplacement , altForEachUseReplacement ] module.exports['test-stream-big-packet.js'] = [ altIndexOfImplReplacement , altIndexOfUseReplacement ] module.exports['common.js'] = [ altForEachImplReplacement , altForEachUseReplacement , [ /(exports.mustCall[\s\S]*)/m , '$1\n' + 'if (!util._errnoException) {\n' + ' var uv;\n' + ' util._errnoException = function(err, syscall) {\n' + ' if (util.isUndefined(uv)) try { uv = process.binding(\'uv\'); } catch (e) {}\n' + ' var errname = uv ? uv.errname(err) : \'\';\n' + ' var e = new Error(syscall + \' \' + errname);\n' + ' e.code = errname;\n' + ' e.errno = errname;\n' + ' e.syscall = syscall;\n' + ' return e;\n' + ' };\n' + '}\n' ] // for streams2 on node 0.11 // and dtrace in 0.10 , [ /^( for \(var x in global\) \{|function leakedGlobals\(\) \{)$/m , ' /*<replacement>*/\n' + ' if (typeof constructor == \'function\')\n' + ' knownGlobals.push(constructor);\n' + ' if (typeof DTRACE_NET_SOCKET_READ == \'function\')\n' + ' knownGlobals.push(DTRACE_NET_SOCKET_READ);\n' + ' if (typeof DTRACE_NET_SOCKET_WRITE == \'function\')\n' + ' knownGlobals.push(DTRACE_NET_SOCKET_WRITE);\n' + ' /*</replacement>*/\n\n$1' ] // for node 0.8 , [ /^/ , '/*<replacement>*/' + '\nif (!global.setImmediate) {\n' + ' global.setImmediate = function setImmediate(fn) {\n' + ' return setTimeout(fn.bind.apply(fn, arguments), 0);\n' + ' };\n' + '}\n' + 'if (!global.clearImmediate) {\n' + ' global.clearImmediate = function clearImmediate(i) {\n' + ' return clearTimeout(i);\n' + ' };\n' + '}\n' + '/*</replacement>*/\n' ] ] // this test has some trouble with the nextTick depth when run // to stdout, it's also very noisy so we'll quiet it module.exports['test-stream-pipe-multi.js'] = [ altForEachImplReplacement , altForEachUseReplacement , [ /console\.error/g , '//console.error' ] , [ /process\.nextTick/g , 'setImmediate' ] ] // just noisy module.exports['test-stream2-large-read-stall.js'] = [ [ /console\.error/g , ';false && console.error' ] ] module.exports['test-stream-pipe-cleanup.js'] = [ [ /(function Writable\(\) \{)/ , 'if (/^v0\\.8\\./.test(process.version))\n return\n\n$1' ] ] module.exports['test-stream2-stderr-sync.js'] = [ altForEachImplReplacement , altForEachUseReplacement , [ // 'tty_wrap' is too different across node versions. // this bypasses it and replicates a console.error() test /(function child0\(\) \{)/ , '$1\n' + ' return console.error(\'child 0\\nfoo\\nbar\\nbaz\');\n' ] ] module.exports['test-stream-unshift-read-race.js'] = [ [ /data\.slice\(pos, pos \+ n\)/g, 'data.slice(pos, Math.min(pos + n, data.length))' ] ]
import React from 'react' import { Route } from 'react-router' import BaseLayout from 'layouts/BaseLayout' import App from 'containers' import { NotFound } from 'components/common' export default (<Route> <Route component={BaseLayout}> <Route path='/' component={App.Home} /> </Route> <Route path='*' component={NotFound} /> </Route>)
$(document).ready(function(){ try { var SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition || window.mozSpeechRecognition || window.oSpeechRecognition || window.msSpeechRecognition; var recognition = new SpeechRecognition(); } catch(e) { console.error(e); $('.no-browser-support').show(); $('.app').hide(); } var interimTextArea = $('#interim-textarea'); var interimContent = ''; var finalTextArea = $('#final-textarea'); var finalContent = ''; var instructions = $('#recording-instructions'); var notesList = $('ul#notes'); var final_transcript = ''; var currTranscript = ''; var w1; var w2; var w3; var times=0; var camNum=0; var buttonNum=0; recognition.lang = 'en-US'; recognition.continuous = true; recognition.interimResults = true; recognition.maxAlternatives = 1; // This block is called every time the Speech APi captures a line. recognition.onresult = function(event) { var interim_transcript = ''; for (var i = event.resultIndex; i < event.results.length; ++i) { if (event.results[i].isFinal) { currTranscript = event.results[i][0].transcript; final_transcript += times+'. '+currTranscript+'\n'; } else { interim_transcript += event.results[i][0].transcript; } } var len=0; len=currTranscript.split(" ").length; // two word command, 1st time if(times==0 && len==2){ w1 =currTranscript.split(" ")[0]; w2=currTranscript.split(" ")[1]; // two word command, 2nd time }else if(times>0 && len==3){ w1 =currTranscript.split(" ")[1]; w2=currTranscript.split(" ")[2]; }// three word command, 1st time else if(times==0 && len==3){ w1 =currTranscript.split(" ")[0]; w2=currTranscript.split(" ")[1]; w3=currTranscript.split(" ")[2]; }// three word command, 2nd time else if(times>0 && len==4){ w1 =currTranscript.split(" ")[1]; w2=currTranscript.split(" ")[2]; w3=currTranscript.split(" ")[3]; }else{ w1 ="undefined"; w2= "undefined"; w3= "undefined"; } // camera names switch(w1) { case "top": camNum=1; break; case "side": camNum=2; break; case "gripper": camNum=3; break; default: camNum=4; break; } // buttons names switch(w2) { case "up": buttonNum=1; break; case "right": buttonNum=2; break; case "down": buttonNum=3; break; case "left": buttonNum=4; break; case "rotate": if (w2=="left"){ buttonNum=5; }else{ buttonNum=6; } break; default: buttonNum=7; break; } var btnCom=currTranscript; var number=0; switch(btnCom) { case "up": number=1; break; case "down": number=2; break; case "right": number=3; break; case "left": number=4; break; } finalContent = 'camNum = '+ camNum +'\nbuttonNum = '+ buttonNum +'\nw1 = '+ w1 + '\nw2 ='+ w2 + '\nw3 ='+ w3;// currTranscript + '. len ='+ len; interimContent= interim_transcript; finalTextArea.val(finalContent); interimTextArea.val(interimContent); currTranscript = ''; times++; var up1BTN = document.getElementById("up"); var up2BTN = document.getElementById("up2"); var right1BTN = document.getElementById("right"); var right2BTN = document.getElementById("right2"); var down1BTN = document.getElementById("down"); var down2BTN = document.getElementById("down2"); var left1BTN = document.getElementById("left"); var left2BTN = document.getElementById("left2"); var rotateLeft1BTN = document.getElementById("rotateLeft"); var rotateLeft2BTN = document.getElementById("rotateLeft2"); var rotateRight1BTN = document.getElementById("rotateRight"); var rotateRight2BTN = document.getElementById("rotateRight2"); if(camNum==1 && buttonNum ==1){ up1BTN.click(); }else if(camNum==1 && buttonNum ==2){ right1BTN.click(); }else if(camNum==1 && buttonNum ==3){ down1BTN.click(); }else if(camNum==1 && buttonNum ==4){ left1BTN.click(); }else if(camNum==1 && buttonNum ==5){ rotateLeft1BTN.click(); }else if(camNum==1 && buttonNum ==6){ rotateRight1BTN.click(); }else if(camNum==2 && buttonNum ==1){ up2BTN.click(); }else if(camNum==2 && buttonNum ==2){ right2BTN.click(); }else if(camNum==2 && buttonNum ==3){ down2BTN.click(); }else if(camNum==2 && buttonNum ==4){ left2BTN.click(); }else if(camNum==2 && buttonNum ==5){ rotateLeft2BTN.click(); }else if(camNum==2 && buttonNum ==6){ rotateRight2BTN.click(); } w1 ="undefined"; w2= "undefined"; w3= "undefined"; }; recognition.onstart = function() { instructions.text('Voice recognition is on.'); } recognition.onspeechend = function() { instructions.text('Voice recognition is off.'); } recognition.onerror = function(event) { if(event.error == 'no-speech') { instructions.text('No speech was detected. Try again.'); }; } /*----------------------------- App buttons and input ------------------------------*/ $('#start-record-btn').on('click', function(e) { var element = document.getElementById("start-record-btn"); $(element).toggleClass('stopStyle'); if ($(element).hasClass("stopStyle")) { element.innerHTML="Stop Recognition"; recognition.start(); } else { element.innerHTML="Start Recognition"; recognition.stop(); instructions.text('Voice recognition paused.'); } }); // Sync the text inside the text area with the interimContent variable. interimTextArea.on('input', function() { interimContent = $(this).val(); }) // Sync the text inside the text area with the finalContent variable. finalTextArea.on('input', function() { finalContent = $(this).val(); }) });
// Generated by CoffeeScript 1.10.0 (function() { var median; median = function() {}; }).call(this); //# sourceMappingURL=median.js.map
import _reduce from 'fast.js/array/reduce'; import invariant from 'invariant'; export const reduce = { method: function(reduceFn, initial) { invariant( typeof reduceFn === 'function', 'reduce(...): reducer argument must be a function' ); this._addPipeline('reduce', reduceFn, initial); return this; }, process: function(docs, pipeObj) { return _reduce(docs, pipeObj.value, pipeObj.args[0]); }, };
module.exports = require('lodash/array/first');
/* The MIT License Copyright (c) 2012 Olaf Horstmann, indiegamr.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. */ /** * A Pixel Perfect Collision Detection for EaselJS Bitmap-Objects * @author olsn, indiegamr.com **/ this.cutie = this.cutie || {}; this.cutie.Collisions = this.cutie.Collisions || {}; (function(module) { var collisionCanvas = document.createElement('canvas'); var collisionCtx = collisionCanvas.getContext('2d'); //collisionCtx.globalCompositeOperation = 'source-in'; collisionCtx.save(); var collisionCanvas2 = document.createElement('canvas'); var collisionCtx2 = collisionCanvas2.getContext('2d'); collisionCtx2.save(); var cachedBAFrames = []; var checkCircleCollision = function(bitmap1, bitmap2) { var c1, c2; c1 = getCircle(bitmap1); c2 = getCircle(bitmap2); return calculateCircleIntersection(c1, c2); } module.Collisions.checkCircleCollision = checkCircleCollision; var checkCircleRectCollision = function(bitmap1, bitmap2) { var b, c; c = getCircle(bitmap1); b = getBounds(bitmap2); return calculateCircleRectIntersection(c, b); } module.Collisions.checkCircleRectCollision = checkCircleRectCollision; var checkRectCollision = function(bitmap1,bitmap2) { var b1, b2; b1 = getBounds(bitmap1); b2 = getBounds(bitmap2) return calculateIntersection(b1,b2); } module.Collisions.checkRectCollision = checkRectCollision; var checkPixelCollision = function(bitmap1, bitmap2, alphaThreshold, getRect) { //display the intersecting canvases for debugging if ( module.Log.level <= module.Log.VERBOSE) { //document.body.appendChild(collisionCanvas); //document.body.appendChild(collisionCanvas2); } getRect = getRect || false; var areObjectsCloseEnough, intersetion, imageData1, imageData2, pixelIntersection; areObjectsCloseEnough = _collisionDistancePrecheck(bitmap1,bitmap2); if ( !areObjectsCloseEnough ) { return false; } intersection = checkRectCollision(bitmap1,bitmap2); if ( !intersection ) { return false; } alphaThreshold = alphaThreshold || 0; alphaThreshold = Math.min(0.99999,alphaThreshold); //setting the canvas size collisionCanvas.width = intersection.width; collisionCanvas.height = intersection.height; collisionCanvas2.width = intersection.width; collisionCanvas2.height = intersection.height; imageData1 = _intersectingImagePart(intersection,bitmap1,collisionCtx,1); imageData2 = _intersectingImagePart(intersection,bitmap2,collisionCtx2,2); //compare the alpha values to the threshold and return the result // = true if pixels are both > alphaThreshold at one coordinate pixelIntersection = _compareAlphaValues(imageData1,imageData2,intersection.width,intersection.height,alphaThreshold, getRect); if ( pixelIntersection ) { pixelIntersection.x += intersection.x; pixelIntersection.x2 += intersection.x; pixelIntersection.y += intersection.y; pixelIntersection.y2 += intersection.y; } else { return false; } return pixelIntersection; } module.Collisions.checkPixelCollision = checkPixelCollision; var _collisionDistancePrecheck = function(bitmap1,bitmap2) { var ir1,ir2,b1,b2; b1 = bitmap1.localToGlobal(0,0); b2 = bitmap2.localToGlobal(0,0); ir1 = bitmap1 instanceof createjs.Bitmap ? {width:bitmap1.image.width, height:bitmap1.image.height} : bitmap1.spriteSheet.getFrame(bitmap1.currentFrame).rect; ir2 = bitmap2 instanceof createjs.Bitmap ? {width:bitmap2.image.width, height:bitmap2.image.height} : bitmap2.spriteSheet.getFrame(bitmap2.currentFrame).rect; //precheck if objects are even close enough return ( Math.abs(b2.x-b1.x) < ir2.width *bitmap2.scaleX+ir1.width *bitmap1.scaleX && Math.abs(b2.y-b1.y) < ir2.height*bitmap2.scaleY+ir1.height*bitmap2.scaleY ) } var _intersectingImagePart = function(intersetion,bitmap,ctx,i) { var bl, image, frameName, sr; if ( bitmap instanceof createjs.Bitmap ) { image = bitmap.image; } else if ( bitmap instanceof createjs.Sprite ) { frame = bitmap.spriteSheet.getFrame( bitmap.currentFrame ) frameName = frame.image.src + ':' + frame.rect.x + ':' + frame.rect.y + ':' + frame.rect.width + ':' + frame.rect.height;// + ':' + frame.rect.regX + ':' + frame.rect.regY if ( cachedBAFrames[frameName] ) { image = cachedBAFrames[frameName]; } else { cachedBAFrames[frameName] = image = createjs.SpriteSheetUtils.extractFrame(bitmap.spriteSheet,bitmap.currentFrame); } } bl = bitmap.globalToLocal(intersetion.x,intersetion.y); ctx.restore(); ctx.save(); //ctx.clearRect(0,0,intersetion.width,intersetion.height); ctx.rotate(_getParentalCumulatedProperty(bitmap,'rotation')*(Math.PI/180)); ctx.scale(_getParentalCumulatedProperty(bitmap,'scaleX','*'),_getParentalCumulatedProperty(bitmap,'scaleY','*')); ctx.translate(-bl.x-intersetion['rect'+i].regX,-bl.y-intersetion['rect'+i].regY); if ( (sr = bitmap.sourceRect) != undefined ) { ctx.drawImage(image,sr.x,sr.y,sr.width,sr.height,0,0,sr.width,sr.height); } else { ctx.drawImage(image,0,0,image.width,image.height); } return ctx.getImageData(0, 0, intersetion.width, intersetion.height).data; } var _compareAlphaValues = function(imageData1,imageData2,width,height,alphaThreshold,getRect) { var alpha1, alpha2, x, y, offset = 3, pixelRect = {x:Infinity,y:Infinity,x2:-Infinity,y2:-Infinity}; // parsing through the pixels checking for an alpha match // TODO: intelligent parsing, not just from 0 to end! for ( y = 0; y < height; ++y) { for ( x = 0; x < width; ++x) { alpha1 = imageData1.length > offset+1 ? imageData1[offset] / 255 : 0; alpha2 = imageData2.length > offset+1 ? imageData2[offset] / 255 : 0; if ( alpha1 > alphaThreshold && alpha2 > alphaThreshold ) { if ( getRect ) { if ( x < pixelRect.x ) pixelRect.x = x; if ( x > pixelRect.x2 ) pixelRect.x2 = x; if ( y < pixelRect.y ) pixelRect.y = y; if ( y > pixelRect.y2 ) pixelRect.y2 = y; } else { return {x:x,y:y,width:1,height:1}; } } offset += 4; } } if ( pixelRect.x != Infinity ) { pixelRect.width = pixelRect.x2 - pixelRect.x + 1; pixelRect.height = pixelRect.y2 - pixelRect.y + 1; return pixelRect; } return null; } // this is needed to paint the intersection part correctly, // if the tested bitmap is a child to a rotated/scaled parent // this was not painted correctly before var _getParentalCumulatedProperty = function(child,propName,operation) { operation = operation || '+'; if ( child.parent && child.parent[propName] ) { var cp = child[propName]; var pp = _getParentalCumulatedProperty(child.parent,propName,operation); if ( operation == '*' ) { return cp * pp; } else { return cp + pp; } } return child[propName]; } var calculateCircleRectIntersection = function(circ, rect) { var dist; var cY = circ.center.y, cX = circ.center.x; var rY = rect.y + rect.height/2, rX = rect.x + rect.width/2; var rD = Math.sqrt(rect.width/2*rect.width/2+rect.height/2*rect.height/2); var min = rD + circ.radius; dist = Math.sqrt((cX-rX)*(cX-rX)+(cY-rY)*(cY-rY)); if(dist > (rD+circ.radius)) return null; else { var dist1, dist2, dist3, dist4; dist1 = Math.sqrt((cX-rect.x)*(cX-rect.x)+(cY-rect.y)*(cY-rect.y)); dist2 = Math.sqrt((cX-rect.x-rect.width)*(cX-rect.x-rect.width)+(cY-rect.y)*(cY-rect.y)); dist3 = Math.sqrt((cX-rect.x)*(cX-rect.x)+(cY-rect.y-rect.height)*(cY-rect.y-rect.height)); dist4 = Math.sqrt((cX-rect.x-rect.width)*(cX-rect.x-rect.width)+(cY-rect.y-rect.height)*(cY-rect.y-rect.height)); //circlue is touching a corner if(dist1 < circ.radius|| dist2 < circ.radius|| dist3 < circ.radius|| dist4 < circ.radius) { return {hit: true}; } else if(cX >= rect.x && cX <= (rect.x + rect.width) && Math.abs(rY - cY) < (circ.radius + rect.height/2)) { return {hit: true}; } else if(cY >= rect.y && cY <= (rect.y + rect.height) && Math.abs(rX - cX) < (circ.radius + rect.width/2)) { return {hit: true}; } else { return null; } } //dist2 = Math.sqrt((cX-rect.x-rect.width)*(cX-rect.x-rect.width)+(cY-rect.y)*(cY-rect.y)); //dist3 = Math.sqrt((cX-rect.x)*(cX-rect.x)+(cY-rect.y-rect.height)*(cY-rect.y-rect.height)); //dist4 = Math.sqrt((cX-rect.x-rect.width)*(cX-rect.x-rect.width)+(cY-rect.y-rect.height)*(cY-rect.y-rect.height)); } module.Collisions.calculateCircleRectIntersection = calculateCircleRectIntersection; var calculateCircleIntersection = function(circ1, circ2) { var dist = Math.sqrt((circ1.center.x-circ2.center.x)*(circ1.center.x-circ2.center.x) + (circ1.center.y-circ2.center.y)*(circ1.center.y-circ2.center.y)); if(dist < (circ1.radius + circ2.radius)) { var centerX = (circ1.center.x + circ2.center.x)/2 var centerY = (circ1.center.y + circ2.center.y)/2 return { x:centerX, y:centerY } } return null; } module.Collisions.calculateCircleIntersection = calculateCircleIntersection; var getCircle = function(obj) { var circle = {center: {x:0, y:0}, radius: 0}; if(obj instanceof module.Container) { //calculate center and maximum radius of all children var children = obj.children, len = children.length; } else { var gp, img = {}; if(obj instanceof module.Sprite) { if(obj.spriteSheet._frames && obj.spriteSheet._frames[obj.currentFrame] && obj.spriteSheet._frames[obj.currentFrame].image) { var frame = obj.spriteSheet.getFrame(obj.currentFrame); img.width = frame.rect.width; img.height = frame.rect.height; img.regX = frame.regX; img.regY = frame.regY; img.x = frame.x; } } else if(obj instanceof module.Bitmap) { var sr = obj.sourceRect || obj.image; img.width = sr.width; img.height = sr.height; img.regX = sr.regX; img.regY = sr.regY; } circle.radius = (img.width > img.height)? sr.width/2:sr.height/2; img.regX = img.regX || 0; img.regY = img.regY || 0; gp = obj.localToGlobal(img.width/2 - img.regX, img.height/2 - img.regY); circle.center.x = gp.x; circle.center.y = gp.y; } return circle; } module.Collisions.getCircle = getCircle; var calculateIntersection = function(rect1, rect2) { // first we have to calculate the // center of each rectangle and half of // width and height var dx, dy, r1={}, r2={}; r1.cx = rect1.x + (r1.hw = (rect1.width /2)); r1.cy = rect1.y + (r1.hh = (rect1.height/2)); r2.cx = rect2.x + (r2.hw = (rect2.width /2)); r2.cy = rect2.y + (r2.hh = (rect2.height/2)); dx = Math.abs(r1.cx-r2.cx) - (r1.hw + r2.hw); dy = Math.abs(r1.cy-r2.cy) - (r1.hh + r2.hh); if (dx < 0 && dy < 0) { dx = Math.min(Math.min(rect1.width,rect2.width),-dx); dy = Math.min(Math.min(rect1.height,rect2.height),-dy); return {x:Math.max(rect1.x,rect2.x), y:Math.max(rect1.y,rect2.y), width:dx, height:dy, rect1: rect1, rect2: rect2}; } else { return null; } } module.Collisions.calculateIntersection = calculateIntersection; var getBounds = function(obj) { var bounds={x:Infinity,y:Infinity,width:0,height:0}; if ( obj instanceof createjs.Container ) { bounds.x2 = -Infinity; bounds.y2 = -Infinity; var children = obj.children, l=children.length, cbounds, c; for ( c = 0; c < l; c++ ) { cbounds = getBounds(children[c]); if ( cbounds.x < bounds.x ) bounds.x = cbounds.x; if ( cbounds.y < bounds.y ) bounds.y = cbounds.y; if ( cbounds.x + cbounds.width > bounds.x2 ) bounds.x2 = cbounds.x + cbounds.width; if ( cbounds.y + cbounds.height > bounds.y2 ) bounds.y2 = cbounds.y + cbounds.height; //if ( cbounds.x - bounds.x + cbounds.width > bounds.width ) bounds.width = cbounds.x - bounds.x + cbounds.width; //if ( cbounds.y - bounds.y + cbounds.height > bounds.height ) bounds.height = cbounds.y - bounds.y + cbounds.height; } if ( bounds.x == Infinity ) bounds.x = 0; if ( bounds.y == Infinity ) bounds.y = 0; if ( bounds.x2 == Infinity ) bounds.x2 = 0; if ( bounds.y2 == Infinity ) bounds.y2 = 0; bounds.width = bounds.x2 - bounds.x; bounds.height = bounds.y2 - bounds.y; delete bounds.x2; delete bounds.y2; } else { var gp,gp2,gp3,gp4,imgr={},sr; if ( obj instanceof createjs.Bitmap ) { sr = obj.sourceRect || obj.image; imgr.width = sr.width; imgr.height = sr.height; } else if ( obj instanceof createjs.Sprite ) { if ( obj.spriteSheet._frames && obj.spriteSheet._frames[obj.currentFrame] && obj.spriteSheet._frames[obj.currentFrame].image ) { var cframe = obj.spriteSheet.getFrame(obj.currentFrame); imgr.width = cframe.rect.width; imgr.height = cframe.rect.height; imgr.regX = cframe.regX; imgr.regY = cframe.regY; } else { bounds.x = obj.x || 0; bounds.y = obj.y || 0; } } else { bounds.x = obj.x || 0; bounds.y = obj.y || 0; } imgr.regX = imgr.regX || 0; imgr.width = imgr.width || 0; imgr.regY = imgr.regY || 0; imgr.height = imgr.height || 0; bounds.regX = imgr.regX; bounds.regY = imgr.regY; gp = obj.localToGlobal(0 -imgr.regX,0 -imgr.regY); gp2 = obj.localToGlobal(imgr.width-imgr.regX,imgr.height-imgr.regY); gp3 = obj.localToGlobal(imgr.width-imgr.regX,0 -imgr.regY); gp4 = obj.localToGlobal(0 -imgr.regX,imgr.height-imgr.regY); bounds.x = Math.min(Math.min(Math.min(gp.x,gp2.x),gp3.x),gp4.x); bounds.y = Math.min(Math.min(Math.min(gp.y,gp2.y),gp3.y),gp4.y); bounds.width = Math.max(Math.max(Math.max(gp.x,gp2.x),gp3.x),gp4.x) - bounds.x; bounds.height = Math.max(Math.max(Math.max(gp.y,gp2.y),gp3.y),gp4.y) - bounds.y; } return bounds; } module.Collisions.getBounds = getBounds; }(this.cutie));
/** * Watches for changes to the quantity of items in the shopping cart, to update * cart count indicators on the storefront. */ define(['modules/jquery-mozu', 'modules/api'], function ($, api) { $(document).ready(function () { var $cartCount = $('[data-mz-role="cartmonitor"]'), timeout; function waitAndGetCart() { return setTimeout(function() { api.get('cartsummary').then(function (summary) { updateCartCount(summary.count()); }); }, 500); } function checkForCartUpdates(apiObject) { if (!apiObject || !apiObject.type) return; switch (apiObject.type) { case "cart": case "cart-summary": clearTimeout(timeout); updateCartCount(apiObject.count() || 0); break; case "cartitem": if (!apiObject.unsynced) timeout = waitAndGetCart(); break; } } function updateCartCount(count) { $cartCount.text(count); $.cookie('mozucartcount', count, { path: '/' }); } api.on('sync', checkForCartUpdates); api.on('spawn', checkForCartUpdates); var savedCount = $.cookie('mozucartcount'); if (savedCount === null) waitAndGetCart(); $cartCount.text(savedCount || 0); }); });
var app = angular.module('yellowpages', ['ngRoute', 'ngCookies']).config(config); config.$inject = ['$routeProvider', '$locationProvider']; function config($routeProvider, $locationProvider){ $routeProvider.when('/', { controller: 'UpdateCtrl', templateUrl:'/login' }); }
import React from 'react'; const Hello = (props) => <div>Hello, {props.name}</div>; Hello.propTypes = { name: React.PropTypes.string } Hello.defaultProps = { name: 'John Doe' } export default Hello;
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. /** * Interface to wrap the native File interface. * * This interface is necessary for creating zero-length (empty) files, * something the Filesystem API allows you to do. Unfortunately, File's * constructor cannot be called directly, making it impossible to instantiate * an empty File in JS. * * @param {Object} opts Initial values. * @constructor */ function MyFile(opts) { var blob_ = new Blob(); this.size = opts.size || 0; this.name = opts.name || ''; this.type = opts.type || ''; this.lastModifiedDate = opts.lastModifiedDate || null; this.storagePath = opts.storagePath || ''; // Need some black magic to correct the object's size/name/type based on the // blob that is saved. Object.defineProperty(this, 'blob_', { enumerable: true, get: function() { return blob_; }, set: function(val) { blob_ = val; this.size = blob_.size; this.name = blob_.name; this.type = blob_.type; this.lastModifiedDate = blob_.lastModifiedDate; }.bind(this) }); } MyFile.prototype.constructor = MyFile; module.exports = MyFile;
const { GraphQLInputObjectType, GraphQLNonNull, GraphQLString } = require('graphql'); const ProfileEnum = require('../enums/ProfileEnum'); const AddProfileType = new GraphQLInputObjectType({ name: 'AddProfile', fields: () => ({ id: { type: GraphQLString }, type: { type: new GraphQLNonNull(ProfileEnum) }, name: { type: new GraphQLNonNull(GraphQLString) }, passkey: { type: new GraphQLNonNull(GraphQLString) }, }), }); module.exports = AddProfileType;
window.uploadFile = (function() { var busy = false; return function(file) { var defer = jQuery.Deferred(); if(busy) { defer.reject(); return defer.promise(); } busy = true; $("#progress-bar").removeClass("hidden"); var formData = new FormData(); formData.append('file', file); var xhr = new XMLHttpRequest(); xhr.open('POST', '/files'); xhr.onload = function(data) { busy = false; $("#progress-bar").addClass("hidden"); $("#progress-bar").width(0); var json = {}; try { json = JSON.parse(this.response); }catch(err) {}; defer.resolve(json); }; xhr.upload.onprogress = function (event) { if (event.lengthComputable) { var progress = (event.loaded / event.total * 100 | 0); defer.notify(progress); $("#progress-bar").width(progress.toFixed(0) + "%"); } }; xhr.send(formData); return defer.promise(); }; })();
$ = $.noConflict(); $(document).ready(function() { $("#signupForm").submit(function(event) { event.preventDefault(); }); // hide the span elements which show errors (initially) $("#invEmail").hide(); $("#existEmail").hide(); $("#succSignUp").hide(); $("#btnSignUp").click(function() { if ((document.getElementById("inputEmail").value).length < 256) { $.ajax({ url: '/signUp', data: $('form').serialize(), type: 'POST', success: function(response) { console.log("Got a valid email address."); console.log(response); $("#succSignUp").show(); // one way to show a successful signUp? // window.location.href = '/'; }, error: function(error) { // Entered email id already exists $("#existEmail").show().fadeOut(4000); console.log("Email Id already exists.") console.log(error); } }); } // Unusually long email entered else { $("#invEmail").show().fadeOut(4000); console.log("Email Id is too long!") } }); });
var searchData= [ ['faq_640',['FAQ',['../md_docs_md_faq.html',1,'']]] ];
#!/usr/bin/env node require('../lib/d2.stat');
describe('Angular-Validation Full Tests:', function () { // global variables var requiredErrorMessages = { 'en': 'Field is required.', 'es': 'El campo es requerido.', 'fr': 'Le champ est requis.', 'no': 'Feltet er påkrevd.', 'ru': 'Поле обязательно для заполнения.' }; var languages = ['en', 'es', 'fr', 'no', 'ru']; var types = ['Directive', 'Service']; var btnGoTo = ['btn_goto_directive', 'btn_goto_service']; var validations = explodeAndFlattenValidatorArray(loadData()); for(var k = 0, kln = types.length; k < kln; k++) { // because we are dealing with promises, we better use closures to pass certain variables (function(types, k) { describe('When clicking on top menu Angular-Validation >> ' + types[k], function () { it('Should navigate to Angular-Validation home page', function () { browser.get('http://localhost/Github/angular-validation/full-tests'); // Find the title element var titleElement = element(by.css('h1')); // Assert that the text element has the expected value. // Protractor patches 'expect' to understand promises. expect(titleElement.getText()).toEqual('Angular-Validation Directive|Service (ghiscoding)'); }); it('Should navigate to TestingForm' + types[k] + ' page', function () { browser.get('http://localhost/Github/angular-validation/full-tests'); var anchorLink = $('[name=btn_goto_' + types[k] +']'); anchorLink.click(); browser.waitForAngular(); // Find the sub-title element var titleElement = element(by.css('h3')); expect(titleElement.getText()).toEqual(types[k]); }); it('Should be loading locale: en', function () { var elmBtnEnglish = $('button[name=btn_english]'); elmBtnEnglish.click(); browser.waitForAngular(); }); it('Should click and blur on each form elements and error message should display on each of them', function () { for (var i = 0, ln = validations.length; i < ln; i++) { var elmInput = $('[name=input' + i + ']'); elmInput.click(); element(by.css('body')).click(); elmInput.sendKeys(protractor.Key.TAB); //$('[for=input' + i + ']').click(); var elmError = $('.validation-input' + i); var errorMsg = (validations[i].validator === 'maxLen' || validations[i].validator === 'max_len') ? requiredErrorMessages[languages[0]] : requiredErrorMessages[languages[0]] + ' ' + validations[i].error_message[languages[0]] expect(elmError.getText()).toEqual(errorMsg); } }); // -- // It seems that Protractor doesn't let us run indefinetely into a describe call (even with higher timeout) // So we have no choice but to run only a max of 2 valid/invalid checks it('Should enter valid text and make error go away', function () { for (var i = 0, ln = validations.length; i < ln; i++) { var elmInput = $('[name=input' + i + ']'); elmInput.click(); for(var j = 0, jln = validations[i].valid_data.length; j < jln; j++) { var data = validations[i].valid_data[j]; (function(elmInput, data, i) { elmInput.clear().then(function() { elmInput.sendKeys(data); element(by.css('body')).click(); elmInput.sendKeys(protractor.Key.TAB); //$('[for=input' + i + ']').click(); var elmError = $('.validation-input' + i); expect(elmError.getText()).toEqual(''); }); })(elmInput, data, i); } } }, 620000); it('Should check that ngDisabled button is now enabled', function() { var elmSubmit1 = $('[name=btn_ngDisabled]'); expect(elmSubmit1.isEnabled()).toBe(true); }); it('Should enter invalid text and make error appear', function () { for (var i = 0, ln = validations.length; i < ln; i++) { var elmInput = $('[name=input' + i + ']'); elmInput.click(); for(var j = 0, jln = 2; j < jln; j++) { if(jln > validations[i].length) { break; } var data = validations[i].invalid_data[j]; (function(elmInput, data, i) { elmInput.clear().then(function() { elmInput.sendKeys(data); element(by.css('body')).click(); elmInput.sendKeys(protractor.Key.TAB); //$('[for=input' + i + ']').click(); var elmError = $('.validation-input' + i); expect(elmError.getText()).toEqual(validations[i].error_message[languages[0]]); }); })(elmInput, data, i); } } }, 620000); }); // describe: When clicking on top menu ... })(types, k); // closure } // for() }); // explode the validators data, a validator might have aliases and if that is the case then exploded them into multiple validators function explodeAndFlattenValidatorArray(data) { var tempArray = []; var obj = {}; for(var i=0, ln = data.length; i < ln; i++) { obj = { validation: data[i].validator + (typeof data[i].params !== "undefined" ? ':' + data[i].params : ''), validator: data[i].validator, invalid_data: data[i].invalid_data, valid_data: data[i].valid_data, error_message: data[i].error_message }; tempArray.push(obj); if(typeof data[i].aliases !== "undefined") { for(var j = 0, jln = data[i].aliases.length; j < jln; j++) { var validator = data[i].validator; if(!!data[i].params) { validator += data[i].params; } obj = { validation: data[i].aliases[j] + (typeof data[i].params !== "undefined" ? ':' + data[i].params : ''), validator: data[i].aliases[j], invalid_data: data[i].invalid_data, valid_data: data[i].valid_data, error_message: data[i].error_message }; tempArray.push(obj); } } } return tempArray; } function loadData() { return [ { 'validator': 'alpha', 'invalid_data': ['abc-def', 'abc def', '@', '#', '123', '{|\\}'], 'valid_data': ['abcdefghijklmnopqrstuvwxyz', 'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝ', 'ążźćśłńęàáâãäåçèéêëìíîïðòóôõöùúûüýÿ'], 'error_message': { 'en': 'May only contain letters.', 'es': 'Unicamente puede contener letras.', 'fr': 'Ne doit contenir que des lettres.', 'no': 'Kan bare inneholde bokstaver.', 'ru': 'Может содержать только буквы.' } }, { 'validator': 'alphaSpaces', 'aliases': ['alpha_spaces'], 'invalid_data': ['abc-def', 'abc(def)', '@', '#', '123', '{|\\}'], 'valid_data': ['abcdefghijklmnopqrstuvwxyz', 'ÀÁÂÃÄÅ ÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝ', 'ążźćśłńęàáâãäå çèéêëìíîïðòóôõöùúûüýÿ'], 'error_message': { 'en': 'May only contain letters and spaces.', 'es': 'Unicamente puede contener letras y espacios.', 'fr': 'Ne doit contenir que des lettres et espaces.', 'no': 'Kan bare inneholde bokstaver og mellomrom.', 'ru': 'Может содержать только буквы и пробелы.' } }, { 'validator': 'alphaNum', 'aliases': ['alpha_num'], 'invalid_data': ['abc-def', 'abc(def)', '@', '#', '{|\\}'], 'valid_data': ['1234567890', 'abcdefghijklmnopqrstuvwxyz', 'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝ', 'ążźćśłńęàáâãäåçèéêëìíîïðòóôõöùúûüýÿ'], 'error_message': { 'en': 'May only contain letters and numbers.', 'es': 'Unicamente puede contener letras y números.', 'fr': 'Ne doit contenir que des lettres et nombres.', 'no': 'Kan bare inneholde bokstaver og tall.', 'ru': 'Может содержать только буквы и цифры.' } }, { 'validator': 'alphaNumSpaces', 'aliases': ['alpha_num_spaces'], 'invalid_data': ['abc-def', 'abc(def)', '@', '#'], 'valid_data': ['1234567890', 'abcdefghijkl mnopqrstuvwxyz', 'ÀÁÂÃÄÅ ÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝ', 'ążźćśłńęàáâãäå çèéêëìíîïðòóôõöùúûüýÿ'], 'error_message': { 'en': 'May only contain letters, numbers and spaces.', 'es': 'Unicamente puede contener letras, números y espacios.', 'fr': 'Ne doit contenir que des lettres, nombres et espaces.', 'no': 'Kan bare inneholde bokstaver, tall og mellomrom.', 'ru': 'Может содержать только буквы, цифры и пробелы.' } }, { 'validator': 'alphaDash', 'aliases': ['alpha_dash'], 'invalid_data': ['abc(def)', '@', '#', '{|\\}'], 'valid_data': ['1234567890', 'abcdefg-hijklmnopqrstuvwxyz', 'ÀÁÂÃÄÅ--ÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝ', 'ążźćśłńęàáâãäåçèéêëìíîïðòóôõöùúûüýÿ'], 'error_message': { 'en': "May only contain letters, numbers and dashes.", 'es': "Unicamente puede contener letras, números y guiones.", 'fr': "Ne doit contenir que des lettres, nombres et des tirets.", 'no': "Kan bare inneholde bokstaver, tall og bindestrek.", 'ru': "Может содержать только буквы, цифры и дефисы." } }, { 'validator': 'alphaDashSpaces', 'aliases': ['alpha_dash_spaces'], 'invalid_data': ['abc(def)', '@', '#', '{|\\}'], 'valid_data': ['123456-7890', 'abcdefg-hijklmn opqrstuvwxyz', 'ÀÁÂÃÄÅ--ÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝ', 'ążźćśłńęàáâãäå çèéêëìíîïðòóôõöùúûüýÿ'], 'error_message': { 'en': "May only contain letters, numbers, dashes and spaces.", 'es': "Unicamente puede contener letras, números, guiones y espacios.", 'fr': "Ne doit contenir que des lettres, nombres, tirets et espaces.", 'no': "Kan bare inneholde bokstaver, tall, bindestrek og mellomrom.", 'ru': "Может содержать только буквы, цифры, дефисы и пробелы." } }, { 'validator': 'betweenLen', 'aliases': ['between_len'], 'params': '1,5', 'invalid_data': ['123456', 'abcdefg', '1234567890'], 'valid_data': ['12345', 'abcde', '!@#$%', '1\r234'], 'error_message': { 'en': "Text must be between 1 and 5 characters in length.", 'es': "El número de caracteres debe de estar entre 1 y 5.", 'fr': "Le texte doit être entre 1 et 5 caractères de longueur.", 'no': "Teksten må være mellom 1 og 5 tegn lang.", 'ru': "Текст должен быть длиной от 1 до 5 символов." } }, { 'validator': 'betweenNum', 'aliases': ['between_num'], 'params': '5,15', 'invalid_data': ['1', '4', '100', 'a', '$'], 'valid_data': ['5', '15'], 'error_message': { 'en': "Needs to be a numeric value, between 5 and 15.", 'es': "El valor debe ser númerico y estar entre 5 y 15.", 'fr': "Doit être une valeur numérique, entre 5 et 15.", 'no': "Det må være en numerisk verdi, mellom 5 og 15.", 'ru': "Должно быть числом между 5 и 15.", } }, { 'validator': 'boolean', 'invalid_data': ['abc', '2', 'falsy'], 'valid_data': ['true', 'false', 'True', 'False', '0', '1'], 'error_message': { 'en': "May only contain a true or false value.", 'es': "Unicamente puede contener el texto verdadero ó falso.", 'fr': "Doit contenir qu'une valeur vraie ou fausse.", 'no': "Kan bare inneholde en sann eller usann verdi.", 'ru': "Может содержать только значение права или ложь." } }, { 'validator': 'creditCard', 'aliases': ['credit_card'], 'invalid_data': ['30-5693-0902-5904', '31169309025904'], 'valid_data': ['4538 1212 2020 3030', '5431-1111-1111-1111', '30569309025904', '4538123456789012'], 'error_message': { 'en': "Must be a valid credit card number.", 'es': "Debe contener un número de tarjeta de crédito valido.", 'fr': "Doit être un numéro de carte de crédit valide.", 'no': "Må være et gyldig kredittkortnummer.", 'ru': "Должно быть действительным номером кредитной карты." } }, { 'validator': 'dateEuro', 'aliases': ['date_euro'], 'invalid_data': ['abc', '32-12-2000', '00-01-2001', '29-02-2012'], 'valid_data': ['30-12-2001', '29-02-2000', '05.05.2005'], 'error_message': { 'en': "Must be a valid date format (dd-mm-yyyy) OR (dd/mm/yyyy).", 'es': "Debe contener una fecha valida con formato (dd-mm-yyyy) ó (dd/mm/yyyy).", 'fr': "Doit être un format de date valide (dd-mm-yyyy) OU (dd/mm/yyyy).", 'no': "Må være et gyldig datoformat (dd-mm-yyyy) eller (dd/mm/yyyy).", 'ru': "Должно быть допустимым форматом даты (dd-mm-yyyy) или (dd/mm/yyyy)." } }, { 'validator': 'dateEuroBetween', 'aliases': ['date_euro_between', 'betweenDateEuro', 'between_date_euro'], 'params': '01-01-2000,28-02-2001', 'invalid_data': ['abc', '32-12-2000', '00-01-2001', '30-13-2012', '31-12-2000', '01-03-2001'], 'valid_data': ['01-02-2001', '29-02-2000', '05.02.2001'], 'error_message': { 'en': "Needs to be a valid date format (dd-mm-yyyy) OR (dd/mm/yyyy) between 01-01-2000 and 28-02-2001.", 'es': "Debe contener una fecha valida entre 01-01-2000 y 28-02-2001 con formato (dd-mm-yyyy) ó (dd/mm/yyyy).", 'fr': "Doit être un format de date valide (dd-mm-yyyy) OU (dd/mm/yyyy) entre 01-01-2000 et 28-02-2001.", 'no': "Må være et gyldig datoformat (dd-mm-yyyy) eller (dd/mm/yyyy) mellom 01-01-2000 and 28-02-2001. ", 'ru': "Должно быть допустимым форматом даты (dd-mm-yyyy) или (dd/mm/yyyy) между 01-01-2000 и 28-02-2001. " } }, { 'validator': 'dateEuroMax', 'aliases': ['date_euro_max', 'maxDateEuro', 'max_date_euro'], 'params': '30-05-2012', 'invalid_data': ['abc', '32-12-2000', '00-01-2001', '30-13-2012', '01-06-2012'], 'valid_data': ['01/01/2001', '30-05-2012', '05.05.2005'], 'error_message': { 'en': "Needs to be a valid date format (dd-mm-yyyy) OR (dd/mm/yyyy), equal to, or lower than 30-05-2012.", 'es': "Debe contener una fecha valida igual ó menor que 30-05-2012 con formato (dd-mm-yyyy) ó (dd/mm/yyyy).", 'fr': "Doit être une date valide (dd-mm-yyyy) OU (dd/mm/yyyy), égale ou inférieure à 30-05-2012.", 'no': "Må være et gyldig datoformat (dd-mm-yyyy) eller (dd/mm/yyyy), lik eller før 30-05-2012.", 'ru': "Должно быть допустимым форматом даты (dd-mm-yyyy) или (dd/mm/yyyy), равное или меньше чем 30-05-2012." } }, { 'validator': 'dateEuroMin', 'aliases': ['date_euro_min', 'minDateEuro', 'min_date_euro'], 'params': '25-05-2012', 'invalid_data': ['abc', '24-05-2012', '32-12-2000', '00-01-2001', '30-13-2012'], 'valid_data': ['25/05/2012', '30-05-2012', '05.05.2015'], 'error_message': { 'en': "Needs to be a valid date format (dd-mm-yyyy) OR (dd/mm/yyyy), equal to, or higher than 25-05-2012.", 'es': "Debe contener una fecha valida igual ó mayor que 25-05-2012 con formato (dd-mm-yyyy) ó (dd/mm/yyyy).", 'fr': "Doit être une date valide (dd-mm-yyyy) OU (dd/mm/yyyy), égale ou supérieure à 25-05-2012.", 'no': "Må være et gyldig datoformat (dd-mm-yyyy) eller (dd/mm/yyyy), lik eller etter 25-05-2012.", 'ru': "Должно быть допустимым форматом даты (dd-mm-yyyy) или (dd/mm/yyyy), равное или больше чем 25-05-2012." } }, { 'validator': 'dateEuroShort', 'aliases': ['date_euro_short'], 'params': '25-05-12', 'invalid_data': ['32-12-00', '00-01-01', '30-13-12', '01-06-2012'], 'valid_data': ['25/05/12', '30-05-12', '05.05.05'], 'error_message': { 'en': "Must be a valid date format (dd-mm-yy) OR (dd/mm/yy).", 'es': "Debe contener una fecha valida con formato (dd-mm-yy) o (dd/mm/yy).", 'fr': "Doit être un format de date valide (dd-mm-yy) OU (dd/mm/yy).", 'no': "Må være et gyldig datoformat (dd-mm-yy) eller (dd/mm/yy).", 'ru': "Должно быть допустимым форматом даты (dd-mm-yy) или (dd/mm/yy)." } }, { 'validator': 'dateEuroShortBetween', 'aliases': ['date_euro_short_between', 'betweenDateEuroShort', 'between_date_euro_short'], 'params': '25-05-12,04-06-12', 'invalid_data': ['24-05-12', '32-12-00', '00-01-01', '30-13-12', '24-05-12', '05-06-12', '01-06-2012'], 'valid_data': ['25/05/12', '30.05.12', '04-06-12'], 'error_message': { 'en': "Needs to be a valid date format (dd-mm-yy) OR (dd/mm/yy) between 25-05-12 and 04-06-12.", 'es': "Debe contener una fecha valida entre 25-05-12 y 04-06-12 con formato (dd-mm-yy) o (dd/mm/yy).", 'fr': "Doit être un format de date valide (dd-mm-yy) OU (dd/mm/yy) entre 25-05-12 et 04-06-12.", 'no': "Må være et gyldig datoformat (dd-mm-yy) eller (dd/mm/yy) mellom 25-05-12 and 04-06-12.", 'ru': "Должно быть допустимым форматом даты (dd-mm-yy) или (dd/mm/yy) между 25-05-12 и 04-06-12." } }, { 'validator': 'dateEuroShortMax', 'aliases': ['date_euro_short_max', 'maxDateEuroShort', 'max_date_euro_short'], 'params': '04-06-12', 'invalid_data': ['32-12-00', '00-01-01', '30-13-12', '05-06-12', '01-06-2012'], 'valid_data': ['25/05/12', '04-06-12', '05.05.05'], 'error_message': { 'en': "Needs to be a valid date format (dd-mm-yy) OR (dd/mm/yy), equal to, or lower than 04-06-12.", 'es': "Debe contener una fecha valida igual ó menor que 04-06-12 con formato (dd-mm-yy) ó (dd/mm/yy).", 'fr': "Doit être une date valide (dd-mm-yy) OU (dd/mm/yy), égale ou inférieure à 04-06-12.", 'no': "Må være et gyldig datoformat (dd-mm-yy) eller (dd/mm/yy), lik eller før 04-06-12.", 'ru': "Должно быть допустимым форматом даты (dd-mm-yy) или (dd/mm/yy), равное или меньше чем 04-06-12." } }, { 'validator': 'dateEuroShortMin', 'aliases': ['date_euro_short_min', 'minDateEuroShort', 'min_date_euro_short'], 'params': '04-06-12', 'invalid_data': ['32-12-00', '00-01-01', '30-13-12', '03-06-12', '01-06-2012'], 'valid_data': ['25/07/12', '04-06-12', '05.05.15'], 'error_message': { 'en': "Needs to be a valid date format (dd-mm-yy) OR (dd/mm/yy), equal to, or higher than 04-06-12.", 'es': "Debe contener una fecha valida igual ó mayor que 04-06-12 con formato (dd-mm-yy) ó (dd/mm/yy).", 'fr': "Doit être une date valide (dd-mm-yy) OU (dd/mm/yy), égale ou supérieure à 04-06-12.", 'no': "Må være et gyldig datoformat (dd-mm-yy) eller (dd/mm/yy), lik eller etter 04-06-12.", 'ru': "Должно быть допустимым форматом даты (dd-mm-yy) или (dd/mm/yy), равное или больше чем 04-06-12." } }, { 'validator': 'dateIso', 'aliases': ['date_iso'], 'invalid_data': ['20001230', '2000-12-32', '2000-13-01', '2012/07/25'], 'valid_data': ['2012-12-31', '1954-01-01'], 'error_message': { 'en': "Must be a valid date format (yyyy-mm-dd).", 'es': "Debe contener una fecha valida con formato (yyyy-mm-dd).", 'fr': "Doit être un format de date valide (yyyy-mm-dd).", 'no': "Må være et gyldig datoformat (yyyy-mm-dd).", 'ru': "Должно быть допустимым форматом даты (yyyy-mm-dd)." } }, { 'validator': 'dateIsoBetween', 'aliases': ['date_iso_between', 'betweenDateIso', 'between_date_iso'], 'params': '2012-05-25,2012-06-04', 'invalid_data': ['2012-24-05', '2032-12-00', '2000-01-00', '2012-05-24', '2012-06-05'], 'valid_data': ['2012-05-25', '2012-06-04'], 'error_message': { 'en': "Needs to be a valid date format (yyyy-mm-dd) between 2012-05-25 and 2012-06-04.", 'es': "Debe contener una fecha valida entre 2012-05-25 y 2012-06-04 con formato (yyyy-mm-dd).", 'fr': "Doit être un format de date valide (yyyy-mm-dd) entre 2012-05-25 et 2012-06-04.", 'no': "Må være et gyldig datoformat (yyyy-mm-dd) mellom 2012-05-25 and 2012-06-04.", 'ru': "Должно быть допустимым форматом даты (yyyy-mm-dd) между 2012-05-25 and 2012-06-04." } }, { 'validator': 'dateIsoMax', 'aliases': ['date_iso_max', 'maxDateIso', 'max_date_iso'], 'params': '2012-05-25', 'invalid_data': ['2012-24-05', '2032-12-00', '2000-01-00', '2012-05-26'], 'valid_data': ['2012-05-25', '2000-06-04'], 'error_message': { 'en': "Needs to be a valid date format (yyyy-mm-dd), equal to, or lower than 2012-05-25.", 'es': "Debe contener una fecha valida igual ó menor que 2012-05-25 con formato (yyyy-mm-dd).", 'fr': "Doit être une date valide (yyyy-mm-dd), égale ou inférieure à 2012-05-25.", 'no': "Må være et gyldig datoformat (yyyy-mm-dd), lik eller før 2012-05-25.", 'ru': "Должно быть допустимым форматом даты (yyyy-mm-dd), равное или меньше чем 2012-05-25." } }, { 'validator': 'dateIsoMin', 'aliases': ['date_iso_min', 'minDateIso', 'min_date_iso'], 'params': '2012-05-25', 'invalid_data': ['2012-24-05', '2032-12-00', '2000-01-00', '2012-05-24'], 'valid_data': ['2012-05-25', '2012-06-04'], 'error_message': { 'en': "Needs to be a valid date format (yyyy-mm-dd), equal to, or higher than 2012-05-25.", 'es': "Debe contener una fecha valida igual ó mayor que 2012-05-25 con formato (yyyy-mm-dd).", 'fr': "Doit être une date valide (yyyy-mm-dd), égale ou supérieure à 2012-05-25.", 'no': "Må være et gyldig datoformat (yyyy-mm-dd), lik eller etter 2012-05-25.", 'ru': "Должно быть допустимым форматом даты (yyyy-mm-dd), равное или больше чем 2012-05-25." } }, { 'validator': 'dateUs', 'aliases': ['date_us'], 'invalid_data': ['02-29-2001', '00-01-2001', '13-30-2012'], 'valid_data': ['01-01-2001', '02/29/2000', '05.15.2005'], 'error_message': { 'en': "Must be a valid date format (mm/dd/yyyy) OR (mm-dd-yyyy).", 'es': "Debe contener una fecha valida con formato (mm/dd/yyyy) ó (mm-dd-yyyy).", 'fr': "Doit être un format de date valide (mm/dd/yyyy) OU (mm-dd-yyyy).", 'no': "Må være et gyldig datoformat (mm/dd/yyyy) eller (mm-dd-yyyy).", 'ru': "Должно быть допустимым форматом даты (mm/dd/yyyy) или (mm-dd-yyyy)." } }, { 'validator': 'dateUsBetween', 'aliases': ['date_us_between', 'betweenDateUs', 'between_date_us'], 'params': '01/01/1990,12/31/2015', 'invalid_data': ['00/02/1990', '01/01/2016', '12/31/15'], 'valid_data': ['01-01-1990', '02/29/2000', '05.15.2015'], 'error_message': { 'en': "Needs to be a valid date format (mm/dd/yyyy) OR (mm-dd-yyyy) between 01/01/1990 and 12/31/2015.", 'es': "Debe contener una fecha valida entre 01/01/1990 y 12/31/2015 con formato (mm/dd/yyyy) ó (mm/dd/yyyy).", 'fr': "Doit être un format de date valide (mm/dd/yyyy) OU (mm-dd-yyyy) entre 01/01/1990 et 12/31/2015.", 'no': "Må være et gyldig datoformat (mm/dd/yyyy) eller (mm-dd-yyyy) mellom 01/01/1990 and 12/31/2015.", 'ru': "Должно быть допустимым форматом даты (mm/dd/yyyy) или (mm-dd-yyyy) между 01/01/1990 и 12/31/2015.", } }, { 'validator': 'dateUsMax', 'aliases': ['date_us_max', 'maxDateUs', 'max_date_us'], 'params': '01/01/1990', 'invalid_data': ['00/02/1990', '02/01/1990', '12/31/15'], 'valid_data': ['01-01-1990', '12/31/1989', '01.12.1900'], 'error_message': { 'en': "Needs to be a valid date format (mm/dd/yyyy) OR (mm-dd-yyyy), equal to, or lower than 01/01/1990.", 'es': "Debe contener una fecha valida igual ó menor que 01/01/1990 con formato (mm/dd/yyyy) ó (mm/dd/yyyy).", 'fr': "Doit être une date valide (mm/dd/yyyy) OU (mm-dd-yyyy), égale ou inférieure à 01/01/1990.", 'no': "Må være et gyldig datoformat (mm/dd/yyyy) eller (mm-dd-yyyy), lik eller før 01/01/1990.", 'ru': "Должно быть допустимым форматом даты (mm/dd/yyyy) или (mm-dd-yyyy), равное или меньше чем 01/01/1990." } }, { 'validator': 'dateUsMin', 'aliases': ['date_us_min', 'minDateUs', 'min_date_us'], 'params': '01/01/1990', 'invalid_data': ['00/02/1990', '12/31/1989', '12/31/15'], 'valid_data': ['01-01-1990', '02/29/2000', '12.31.1999'], 'error_message': { 'en': "Needs to be a valid date format (mm/dd/yyyy) OR (mm-dd-yyyy), equal to, or higher than 01/01/1990.", 'es': "Debe contener una fecha valida igual ó mayor que 01/01/1990 con formato (mm/dd/yyyy) ó (mm/dd/yyyy).", 'fr': "Doit être une date valide (mm/dd/yyyy) OU (mm-dd-yyyy), égale ou supérieure à 01/01/1990.", 'no': "Må være et gyldig datoformat (mm/dd/yyyy) eller (mm-dd-yyyy), lik eller etter 01/01/1990.", 'ru': "Должно быть допустимым форматом даты (mm/dd/yyyy) или (mm-dd-yyyy), равное или больше чем 01/01/1990." } }, { 'validator': 'dateUsShort', 'aliases': ['date_us_short'], 'invalid_data': ['32-12-00', '00-01-01', '13-30-12'], 'valid_data': ['01-01-01', '12/30/01', '05.15.05'], 'error_message': { 'en': "Must be a valid date format (mm/dd/yy) OR (mm-dd-yy).", 'es': "Debe contener una fecha valida con formato (mm/dd/yy) ó (mm-dd-yy).", 'fr': "Doit être un format de date valide (mm/dd/yy) OU (mm-dd-yy).", 'no': "Må være et gyldig datoformat (mm/dd/yy) eller (mm-dd-yy).", 'ru': "Должно быть допустимым форматом даты (mm/dd/yy) или (mm-dd-yy)." } }, { 'validator': 'dateUsShortBetween', 'aliases': ['date_us_short_between', 'betweenDateUsShort', 'between_date_us_short'], 'params': '01/01/90,12/31/15', 'invalid_data': ['00/02/90', '01/01/16', '12/31/15', '12/31/2015'], 'valid_data': ['01-01-90', '12/31/15', '05.15.15'], 'error_message': { 'en': "Needs to be a valid date format (mm/dd/yy) OR (mm-dd-yy) between 01/01/90 and 12/31/15.", 'es': "Debe contener una fecha valida entre 01/01/90 y 12/31/15 con formato (mm/dd/yy) ó (mm/dd/yy).", 'fr': "Doit être un format de date valide (mm/dd/yy) OU (mm-dd-yy) entre 01/01/90 et 12/31/15.", 'no': "Må være et gyldig datoformat (mm/dd/yy) eller (mm-dd-yy) between 01/01/90 and 12/31/15.", 'ru': "Должно быть допустимым форматом даты (mm/dd/yy) или (mm-dd-yy) между 01/01/90 и 12/31/15." } }, { 'validator': 'dateUsShortMax', 'aliases': ['date_us_short_max', 'maxDateUsShort', 'max_date_us_short'], 'params': '01/01/90', 'invalid_data': ['00/02/90', '02/01/90', '12/31/15', '12/31/2015'], 'valid_data': ['01-01-90', '12/31/89', '01.12.89'], 'error_message': { 'en': "Needs to be a valid date format (mm/dd/yy) OR (mm-dd-yy), equal to, or lower than 01/01/90.", 'es': "Debe contener una fecha valida igual ó menor que 01/01/90 con formato (mm/dd/yy) ó (mm/dd/yy).", 'fr': "Doit être une date valide (mm/dd/yy) OU (mm-dd-yy), égale ou inférieure à 01/01/90.", 'no': "Må være et gyldig datoformat (mm/dd/yy) eller (mm-dd-yy), lik eller før 01/01/90.", 'ru': "Должно быть допустимым форматом даты (mm/dd/yy) или (mm-dd-yy), равное или меньше чем 01/01/90." } }, { 'validator': 'dateUsShortMin', 'aliases': ['date_us_short_min', 'minDateUsShort', 'min_date_us_short'], 'params': '01/01/90', 'invalid_data': ['00/02/90', '12/31/89', '31/12/15', '12/31/2015'], 'valid_data': ['01-01-90', '02/28/90', '05.15.05'], 'error_message': { 'en': "Needs to be a valid date format (mm/dd/yy) OR (mm-dd-yy), equal to, or higher than 01/01/90.", 'es': "Debe contener una fecha valida igual ó mayor que 01/01/90 con formato (mm/dd/yy) ó (mm/dd/yy).", 'fr': "Doit être une date valide (mm/dd/yy) OU (mm-dd-yy), égale ou supérieure à 01/01/90.", 'no': "Må være et gyldig datoformat (mm/dd/yy) eller (mm-dd-yy), lik eller etter 01/01/90.", 'ru': "Должно быть допустимым форматом даты (mm/dd/yy) или (mm-dd-yy), равное или больше чем 01/01/90." } }, { 'validator': 'digits', 'params': '3', 'invalid_data': ['12a', '12.2', '12', '12,3'], 'valid_data': ['123'], 'error_message': { 'en': "Must be 3 digits.", 'es': "Debe ser 3 dígitos.", 'fr': "Doit être 3 chiffres.", 'no': "Må være 3 sifre.", 'ru': "Должно быть 3 цифры." } }, { 'validator': 'digitsBetween', 'aliases': ['digits_between'], 'params': '1,5', 'invalid_data': ['123456', 'abc', '12.5', '-2'], 'valid_data': ['12345', '9'], 'error_message': { 'en': "Must be between 1 and 5 digits.", 'es': "Debe ser entre 1 y 5 dígitos.", 'fr': "Doit être entre 1 et 5 chiffres.", 'no': "Må være mellom 1 og 5 siffer.", 'ru': "Должно быть между 1 и 5 цифр." } }, { 'validator': 'email', 'invalid_data': ['g$g.com', 'g@g,com', '.my@email.com.', 'some space@hotmail.com'], 'valid_data': ['nickname@domain', 'other.email-with-dash@some-company.com', 'кокер@спаниель.рф', 'hola.ążźćśłńęàáâãäåæçèéêëœìíïîðòóôõöøùúûñüýÿ@español.com'], 'error_message': { 'en': "Must be a valid email address.", 'es': "Debe contener una dirección de correo electronico valida.", 'fr': "Doit être une adresse courriel valide.", 'no': "Må være en gyldig epostadresse.", 'ru': "Должно быть допустимым адресом электронной почты." } }, { 'validator': 'exactLen', 'aliases': ['exact_len'], 'params': '11', 'invalid_data': ['1234567890', 'abcdefghijkl'], 'valid_data': ['12345678901', 'abcdefghijk'], 'error_message': { 'en': "Must have a length of exactly 11 characters.", 'es': "Debe contener exactamente 11 caracteres.", 'fr': "Doit être d'une longueur fixe de 11 caractères.", 'no': "Må være nøyaktig 11 tegn lang.", 'ru': "Должно быть длиной в размере точно 11 символов." } }, { 'validator': 'float', 'invalid_data': ['12', '12.', 'abc', '12,3', '-12.3', '+12.3'], 'valid_data': ['.5', '0.5', '12.3'], 'error_message': { 'en': "May only contain a positive float value (integer excluded).", 'es': "Debe contener un número decimal positivo (Los números enteros no son validos).", 'fr': "Doit être obligatoirement un nombre flottant positif (nombre entier exclu).", 'no': "Kan bare inneholde en positiv flyttalsverdi (heltall ekskludert).", 'ru': "Может содержать только положительное дробное или целое число." } }, { 'validator': 'floatSigned', 'aliases': ['float_signed'], 'invalid_data': ['12', '12.', 'abc', '12,3'], 'valid_data': ['.5', '0.5', '12.3', '-12.3', '+12.3'], 'error_message': { 'en': "May only contain a positive or negative float value (integer excluded).", 'es': "Debe contener un número decimal positivo ó negativo (Los números enteros no son validos).", 'fr': "Doit être obligatoirement un nombre flottant positif ou négatif (nombre entier exclu).", 'no': "Kan bare inneholde en positiv eller negativ flyttalsverdi (heltall ekskludert).", 'ru': "Может содержать только положительное или отрицательное дробное или целое число." } }, { 'validator': 'iban', 'invalid_data': ['ABC1234567890', 'DEABCD12500105170648489890'], 'valid_data': ['DE12500105170648489890', 'AB12500105170648489890'], 'error_message': { 'en': "Must be a valid IBAN.", 'es': "Debe contener un IBAN valido.", 'fr': "Doit être un IBAN valide.", 'no': "Må være en gyldig IBAN.", 'ru': "Должно быть действительным международным номером банковского счёта (IBAN)." } }, { 'validator': 'in', 'aliases': ['inList', 'in_list'], 'params': 'chocolate,apple pie,ice cream,sweet & sour,A+B', 'invalid_data': ['choco', 'carrot', 'apple'], 'valid_data': ['chocolate', 'ice cream','sweet & sour','A+B'], 'error_message': { 'en': "Must be a choice inside this list: (chocolate,apple pie,ice cream,sweet & sour,A+B).", 'es': "Debe ser una opción dentro de esta lista: (chocolate,apple pie,ice cream,sweet & sour,A+B).", 'fr': "Doit être un choix dans cette liste: (chocolate,apple pie,ice cream,sweet & sour,A+B).", 'no': "Må være et valg inne i denne listen: (chocolate,apple pie,ice cream,sweet & sour,A+B).", 'ru': "Должно бытьвыбор в этом списке: (chocolate,apple pie,ice cream,sweet & sour,A+B)." } }, { 'validator': 'int', 'aliases': ['integer'], 'invalid_data': ['12.5', '.5', 'abc', '12,4', '-12.3', '+12.3'], 'valid_data': ['12', '100'], 'error_message': { 'en': "Must be a positive integer.", 'es': "Debe contener un número entero positivo.", 'fr': "Doit être un nombre entier positif.", 'no': "Må være et positivt heltall.", 'ru': "Должно быть положительным целым числом." } }, { 'validator': 'intSigned', 'aliases': ['integerSigned', 'int_signed', 'integer_signed'], 'invalid_data': ['12.5', '.5', 'abc', '12,4'], 'valid_data': ['12', '100', '-12', '+12'], 'error_message': { 'en': "Must be a positive or negative integer.", 'es': "Debe contener un número entero positivo ó negativo.", 'fr': "Doit être un nombre entier positif ou négatif.", 'no': "Må være et positivt eller negativt heltall.", 'ru': "Должно быть положительным или отрицательным целым числом." } }, { 'validator': 'ipv4', 'aliases': ['ip'], 'invalid_data': ['192.0.0.256', '256.0.0.256', '192.0.0'], 'valid_data': ['192.0.0.1', '127.0.0.1', '255.255.255.0'], 'error_message': { 'en': "Must be a valid IP (IPV4).", 'es': "Debe contener una dirección IP valida (IPV4).", 'fr': "Doit être un IP valide (IPV4).", 'no': "Må være en gyldig IP-adresse (IPV4).", 'ru': "Должно быть действительным ip адресом (IPV4)." } }, { 'validator': 'ipv6', 'invalid_data': ['127.0.0.1', '255.255.255.0', '1762:0:0:0:0:B03:1'], 'valid_data': ['2002:4559:1FE2::4559:1FE2', '2002:4559:1FE2:0:0:0:4559:1FE2', '2002:4559:1FE2:0000:0000:0000:4559:1FE2'], 'error_message': { 'en': "Must be a valid IP (IPV6).", 'es': "Debe contener una dirección IP valida (IPV6).", 'fr': "Doit être un IP valide (IPV6).", 'no': "Må være en gyldig IP-adresse (IPV6).", 'ru': "Должно быть действительным ip адресом (IPV6)." } }, { 'validator': 'maxLen', 'aliases': ['max_len'], 'params': '11', 'invalid_data': ['abcdefghijkl', 'abcdefghijklmnopqrstuvwxyz'], 'valid_data': ['abcdefghij$', 'abcdef!@#$', 'abcdefghijk', '12345\r67890'], 'error_message': { 'en': "May not be greater than 11 characters.", 'es': "No puede contener mas de 11 caracteres.", 'fr': "Doit être plus petit que 11 caractères.", 'no': "Kan ikke være større enn 11 characters.", 'ru': "Должно быть размером не большим, чем 11 символов." } }, { 'validator': 'maxNum', 'aliases': ['max_num'], 'params': '99', 'invalid_data': ['100', '255'], 'valid_data': ['99', '1', '-1'], 'error_message': { 'en': "Needs to be a numeric value, equal to, or lower than 99.", 'es': "Debe contener un valor númerico igual o menor que 99.", 'fr': "Doit être une valeur numérique, égale ou inférieure à 99.", 'no': "Må være en numerisk verdi, lik, eller mindre enn 99.", 'ru': "Должно быть числовым значением, равное или меньшее чем 99." } }, { 'validator': 'minLen', 'aliases': ['min_len'], 'params': '3', 'invalid_data': ['@@', 'ab'], 'valid_data': ['!#$', 'abc', 'word', '1\r23'], 'error_message': { 'en': "Must be at least 3 characters.", 'es': "Debe contener almenos 3 caracteres.", 'fr': "Doit avoir au moins 3 caractères.", 'no': "Må være minst 3 tegn.", 'ru': "Должно быть размером не меньшим, чем 3 символов." } }, { 'validator': 'minNum', 'aliases': ['min_num'], 'params': '1', 'invalid_data': ['0', '-1'], 'valid_data': ['1', '+1', '120'], 'error_message': { 'en': "Needs to be a numeric value, equal to, or higher than 1.", 'es': "Debe contener un valor númerico igual o mayor que 1.", 'fr': "Doit être une valeur numérique, égale ou supérieure à 1.", 'no': "Må være en numerisk verdi, lik, eller større enn 1.", 'ru': "Должно быть числовым значением, равное или большее чем 1." } }, { 'validator': 'notIn', 'aliases': ['not_in', 'notInList', 'not_in_list'], 'params': 'chocolate,apple pie,ice cream,sweet & sour,A+B', 'invalid_data': ['chocolate', 'apple pie', 'sweet & sour', 'A+B'], 'valid_data': ['apple', 'sweet & sou', 'A+', 'B+A'], 'error_message': { 'en': "Must be a choice outside this list: (chocolate,apple pie,ice cream,sweet & sour,A+B).", 'es': "Debe ser una elección fuera de esta lista: (chocolate,apple pie,ice cream,sweet & sour,A+B).", 'fr': "Doit être un choix en dehors de cette liste: (chocolate,apple pie,ice cream,sweet & sour,A+B).", 'no': "Må være et valg utenfor denne listen: (chocolate,apple pie,ice cream,sweet & sour,A+B).", 'ru': "Должно бытьвыбор за этот список: (chocolate,apple pie,ice cream,sweet & sour,A+B)." } }, { 'validator': 'numeric', 'invalid_data': ['abc', '+2', '-2', '12,5'], 'valid_data': ['0', '12.5'], 'error_message': { 'en': "Must be a positive number.", 'es': "Debe contener un valor númerico positivo.", 'fr': "Doit être un nombre positif.", 'no': "Må være et positivt tall.", 'ru': "Должно быть положительным числом." } }, { 'validator': 'numericSigned', 'aliases': ['numeric_signed'], 'invalid_data': ['abc', '12,5'], 'valid_data': ['0', '12.5', '+2.2', '-2'], 'error_message': { 'en': "Must be a positive or negative number.", 'es': "Debe contener un valor númerico positivo ó negativo.", 'fr': "Doit être un nombre positif ou négatif.", 'no': "Må være et positivt eller negativt tall.", 'ru': "Должно быть положительным или отрицательным числом." } }, { 'validator': 'phone', 'invalid_data': ['1-800-123-456', '123-456-789', '1234567890'], 'valid_data': ['1-800-123-4567', '123-456-7890', '(123) 456-7890'], 'error_message': { 'en': "Must be a valid phone number and must include area code.", 'es': "Debe ser un número de teléfono válido y debe incluir el código de área.", 'fr': "Doit être un numéro de téléphone valide et doit inclure le code régional.", 'no': "Må være et gyldig telefonnummer og inkluderer retningsnummer.", 'ru': "Должен быть действительный телефонный номер и включают в себя код города." } }, { 'validator': 'url', 'invalid_data': ['htp://www.future.com', 'fp://www.future.com', 'http:www.future.com'], 'valid_data': ['http://www.future.com', 'https://future.com', 'ftp://www.future.com'], 'error_message': { 'en': "Must be a valid URL.", 'es': "Debe contener una dirección URL valida.", 'fr': "Doit être un URL valide.", 'no': "Må være en gyldig URL.", 'ru': "Должно быть действительным URL адресом." } }, { 'validator': 'time', 'invalid_data': ['1010', '61:61', '00:00', '59:59:59'], 'valid_data': ['10:10', '00:01', '23:59:59'], 'error_message': { 'en': "Must be a valid time format (hh:mm) OR (hh:mm:ss).", 'es': "Debe contener un formato de tiempo valido (hh:mm) ó (hh:mm:ss).", 'fr': "Doit être un format de temps valide (hh:mm) OU (hh:mm:ss).", 'no': "Må være et gyldig tidsformat (tt:mm) OR (tt:mm:ss).", 'ru': "Должно быть допустимым форматом времени (hh:mm) или (hh:mm:ss)." } } ]; }
// All symbols in the `Armenian` script as per Unicode v4.1.0: [ '\u0531', '\u0532', '\u0533', '\u0534', '\u0535', '\u0536', '\u0537', '\u0538', '\u0539', '\u053A', '\u053B', '\u053C', '\u053D', '\u053E', '\u053F', '\u0540', '\u0541', '\u0542', '\u0543', '\u0544', '\u0545', '\u0546', '\u0547', '\u0548', '\u0549', '\u054A', '\u054B', '\u054C', '\u054D', '\u054E', '\u054F', '\u0550', '\u0551', '\u0552', '\u0553', '\u0554', '\u0555', '\u0556', '\u0559', '\u055A', '\u055B', '\u055C', '\u055D', '\u055E', '\u055F', '\u0561', '\u0562', '\u0563', '\u0564', '\u0565', '\u0566', '\u0567', '\u0568', '\u0569', '\u056A', '\u056B', '\u056C', '\u056D', '\u056E', '\u056F', '\u0570', '\u0571', '\u0572', '\u0573', '\u0574', '\u0575', '\u0576', '\u0577', '\u0578', '\u0579', '\u057A', '\u057B', '\u057C', '\u057D', '\u057E', '\u057F', '\u0580', '\u0581', '\u0582', '\u0583', '\u0584', '\u0585', '\u0586', '\u0587', '\u058A', '\uFB13', '\uFB14', '\uFB15', '\uFB16', '\uFB17' ];
import { typeOf } from '@ember/utils'; import { toInternal, isInternal, isInternalObject, isInternalArray } from 'documents/util/internal'; import { empty } from './-base'; const createDeserializeMixin = Class => class DeserializeMixin extends Class { _createInternalObject(parent, type) { return this.store._createInternalObject(parent, type); } _createInternalArray(parent, type) { return this.store._createInternalArray(parent, type); } _deserializeObjectValue(value, current, type) { let internal; let update; if(isInternalObject(current)) { internal = current; internal.withPropertyChanges(changed => internal.deserialize(value, type, changed), true); update = false; } else { this._detachInternal(current); internal = this._createInternalObject(this); internal.withPropertyChanges(changed => internal.deserialize(value, type, changed), false); update = true; } return { update, internal }; } _deserializeArrayValue(value, current, type) { let internal; let update; if(isInternalArray(current)) { internal = current; internal.withPropertyChanges(changed => internal.deserialize(value, type, changed), true); update = false; } else { this._detachInternal(current); internal = this._createInternalArray(this); internal.withPropertyChanges(changed => internal.deserialize(value, type, changed), false); update = true; } return { update, internal }; } _deserializeInternalArrayValue(value, current) { this._detachInternal(current); this._attachInternal(value); return { update: true, internal: value }; } _deserializeInternalObjectValue(value, current) { this._detachInternal(current); this._attachInternal(value); return { update: true, internal: value }; } _deserializePrimitiveValue(value, current) { this._detachInternal(current); return { update: true, internal: value }; } _deserializeValue(value, current, type) { value = toInternal(value); if(current === value) { return { update: false, internal: value }; } if(current === empty) { current = undefined; } if(isInternal(value)) { if(value.isDetached()) { if(isInternalObject(value)) { return this._deserializeInternalObjectValue(value, current); } else if(isInternalArray(value)) { return this._deserializeInternalArrayValue(value, current); } } value = value.serialize('model'); } let valueType = typeOf(value); if(valueType === 'object') { return this._deserializeObjectValue(value, current, type); } else if(valueType === 'array') { return this._deserializeArrayValue(value, current, type); } return this._deserializePrimitiveValue(value, current, type); } } const createSerializeMixin = Class => class SerializeMixin extends Class { _serializeValue(value, type) { if(isInternal(value)) { value = value.serialize(type); } return value; } } export default Class => createSerializeMixin(createDeserializeMixin(Class));
import _ from "lodash"; import AvroElement from "../avro-objects/avro-element"; import AvroNode from "../avro-objects/avro-node"; import avroTypes from "../constants/avro-types"; import {isArray, isDefined, isObject} from "../utilities"; export default class Avroizer { constructor(avroSchema, visitors) { this._avroElements = Avroizer.getAvroElement(avroSchema, [], []); this._visitors = visitors; } get avroElements() { return this._avroElements; } get visitors() { return this._visitors; } avroize(data) { return this.avroizeElements(data, this.avroElements); } avroizeElements(data, avroElements) { const cleanAvroElements = _.cloneDeep(avroElements); let avroizedData = {}; cleanAvroElements.forEach((avroElement) => { if (this.visitors !== null) { this.visitors.forEach((visitor) => { avroElement.accept(visitor, data); }); } const parentNodeLength = avroElement.parentNodes.length; if (parentNodeLength === 0) { avroizedData = avroElement.value; } else if (parentNodeLength === 1) { if (isDefined(avroElement.arrayElements)) { avroizedData[avroElement.name] = this.getArrayRecords(avroElement, data); } else { avroizedData[avroElement.name] = avroElement.value; } } else { let latestNode = avroizedData; let latestData = data; avroElement.parentNodes.forEach((parentNode) => { // looking to get the right node object and data object if (parentNode.dataNodeName !== null && latestData !== null) { // get the right data first if (isObject(latestData)) { if (isObject(latestData[parentNode.name])) { if (parentNode.isNullable) { latestData = latestData[parentNode.name][parentNode.dataNodeName]; } else { latestData = latestData[parentNode.name]; } } else { latestData = undefined; } } // initialize the node here if not created yet if (!isDefined(latestNode[parentNode.name])) { if (parentNode.isNullable) { if (isObject(latestData)) { latestNode[parentNode.name] = {}; latestNode[parentNode.name][parentNode.dataNodeName] = {}; } else { latestNode[parentNode.name] = null; latestData = null; } } else { latestNode[parentNode.name] = {}; } } // descend into the node if it exists if (isObject(latestNode[parentNode.name])) { if (parentNode.isNullable) { latestNode = latestNode[parentNode.name][parentNode.dataNodeName]; } else { latestNode = latestNode[parentNode.name]; } } else { latestData = null; } } }); if (latestData !== null) { if (isDefined(avroElement.arrayElements)) { latestNode[avroElement.name] = this.getArrayRecords(avroElement, latestData); } else { latestNode[avroElement.name] = avroElement.value; } } } }); return avroizedData; } getArrayRecords(avroElement, data) { let arrayElement, avroizedRecords, result; if (isObject(data)) { if (avroElement.isNullable) { if (isObject(data[avroElement.name])) { arrayElement = data[avroElement.name][avroTypes.ARRAY]; } } else { arrayElement = data[avroElement.name]; } } if (isArray(arrayElement)) { avroizedRecords = arrayElement.filter((record) => { return isObject(record); }).map((record) => { return this.avroizeElements(record, avroElement.arrayElements); }); } if (avroElement.isNullable) { if (isArray(avroizedRecords)) { result = {}; result[avroTypes.ARRAY] = avroizedRecords; } else { result = null; } } else { if (isArray(avroizedRecords)) { result = avroizedRecords; } else { result = []; } } return result; } static addAvroElementToAccumulator(accumulator, name, dataType, isNullable, isArray, defaultValue, parentNodes, arrayElements) { const avroElement = new AvroElement(name, dataType, isNullable, isArray, defaultValue, parentNodes, arrayElements); accumulator.push(avroElement); } static getAvroElement(avroJSON, parentNodes, accumulator, nodeName, namespace) { if (isObject(avroJSON.type)) { if (avroJSON.type.type === avroTypes.ARRAY) { if (isObject(avroJSON.type.items)) { const arrayElements = Avroizer.getAvroElement(avroJSON.type.items, [], [], undefined, namespace); Avroizer.addAvroElementToAccumulator(accumulator, avroJSON.name, avroJSON.type.type, false, true, avroJSON.default, parentNodes, arrayElements); } else { Avroizer.addAvroElementToAccumulator(accumulator, avroJSON.name, avroJSON.type.items, false, true, avroJSON.default, parentNodes); } } else { return Avroizer.getAvroElement(avroJSON.type, parentNodes, accumulator, avroJSON.name, namespace); } } else if (avroJSON.type === avroTypes.RECORD) { let parentNode; if (isDefined(nodeName)) { const dataNodeName = namespace + "." + avroJSON.name; parentNode = new AvroNode(nodeName, dataNodeName, false); } else { if (!isDefined(namespace)) { namespace = avroJSON.namespace; } parentNode = new AvroNode(avroJSON.name, null, false); } const newParentNodes = parentNodes.concat([parentNode]); avroJSON.fields.forEach((field) => { Avroizer.getAvroElement(field, newParentNodes, accumulator, undefined, namespace); }); return accumulator; } else { if (isArray(avroJSON.type)) { const unionType = avroJSON.type[1]; if (isObject(unionType)) { if (unionType.type === avroTypes.ARRAY) { if (isObject(unionType.items)) { const arrayElements = Avroizer.getAvroElement(unionType.items, [], [], undefined, namespace); Avroizer.addAvroElementToAccumulator(accumulator, avroJSON.name, unionType.type, true, true, avroJSON.default, parentNodes, arrayElements); } else { Avroizer.addAvroElementToAccumulator(accumulator, avroJSON.name, unionType.items, true, true, avroJSON.default, parentNodes); } } else { const dataNodeName = namespace + "." + avroJSON.type[1].name; const parentNode = new AvroNode(avroJSON.name, dataNodeName, true); const newParentNodes = parentNodes.concat([parentNode]); avroJSON.type[1].fields.forEach((field) => { Avroizer.getAvroElement(field, newParentNodes, accumulator, undefined, namespace); }); return accumulator; } } else { Avroizer.addAvroElementToAccumulator(accumulator, avroJSON.name, unionType, true, false, avroJSON.default, parentNodes); } } else { Avroizer.addAvroElementToAccumulator(accumulator, avroJSON.name, avroJSON.type, false, false, avroJSON.default, parentNodes); } return accumulator; } } }
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var React = require("react"); var Utilities_1 = require("../Utilities"); var StoreHost = (function (_super) { __extends(StoreHost, _super); function StoreHost() { return _super !== null && _super.apply(this, arguments) || this; } StoreHost.prototype.getChildContext = function () { var parentStores = this.context.stores; var currentStores = this.props.stores; return { stores: parentStores ? parentStores.merge(currentStores) : currentStores }; }; StoreHost.prototype.render = function () { return React.Children.only(this.props.children); }; return StoreHost; }(Utilities_1.BaseComponent)); StoreHost.contextTypes = { stores: React.PropTypes.object }; StoreHost.childContextTypes = { stores: React.PropTypes.object }; exports.StoreHost = StoreHost; //# sourceMappingURL=StoreHost.js.map
exports.catchErrors = (fn) => { return function(req, res, next) { return fn(req, res, next).catch(next) } } exports.notFound = (req, res, next) => { const err = new Error('Not Found') err.status = 404 next(err) } exports.flashValidationErrors = (err, req, res, next) => { if (!err.errors) return next(err) const errorKeys = Object.keys(err.errors) errorKeys.forEach(key => req.flash('error', err.errors[key].message)) res.redirect('back') } exports.developmentErrors = (err, req, res, next) => { err.stack = err.stack || '' const errorDetails = { message: err.message, status: err.status, stackHighlighted: err.stack.replace(/[a-z_-\d]+.js:\d+:\d+/gi, '<mark>$&</mark>') } res.status(err.status || 500) res.format({ 'text/html': () => { res.render('error', errorDetails) }, 'application/json': () => res.json(errorDetails) }) } exports.productionErrors = (err, req, res, next) => { res.status(err.status || 500) res.render('error', { message: err.message, error: {} }) }
'use strict'; var postsPolicy = require('../policies/posts.server.policy'), comments = require('../controllers/comments.server.controller'), ideas = require('../controllers/ideas.server.controller'), photos = require('../controllers/photos.server.controller'), posts = require('../controllers/posts.server.controller'), rates = require('../controllers/rates.server.controller'), videos = require('../controllers/videos.server.controller'); module.exports = function(app) { /************************************************ Ideas Route *************************************************/ app.route('/api/posts/idea').all(postsPolicy.isAllowed) // .get(ideas.list) .post(ideas.create); app.route('/api/posts/:postId/idea/:ideaId').all(postsPolicy.isAllowed) // .get(ideas.read) .put(ideas.update) .delete(ideas.delete); app.route('/api/posts/:postId/comment').all(postsPolicy.isAllowed) .post(comments.addIdeaComment); app.route('/api/posts/:postId/comment/:commentIdeaId').all(postsPolicy.isAllowed) .delete(comments.deleteIdeaComment); app.route('/api/posts/:postId/rate').all(postsPolicy.isAllowed) .get(rates.avgRating) .post(rates.addIdeaRate); // app.route('/posts/:postId/rate/:rateIdeaId') /************************************************* Photo's Route **************************************************/ app.route('/api/posts/photo').all(postsPolicy.isAllowed) // .get(photos.list) .post(photos.create); app.route('/api/posts/:postId/photo/:photoId').all(postsPolicy.isAllowed) // .get(photos.read) .put(photos.update) .delete(photos.delete); app.route('/api/posts/:postId/comment').all(postsPolicy.isAllowed) .post(comments.addPhotoComment); app.route('/api/posts/:postId/comment/:commentPhotoId').all(postsPolicy.isAllowed) .delete(comments.deletePhotoComment); app.route('/api/posts/:postId/rate').all(postsPolicy.isAllowed) .get(rates.avgRating) .post(rates.addPhotoRate); // app.route('/posts/:postId/rate/:ratePhotoId') /*********************************************** Video Route ***********************************************/ app.route('/api/posts/video').all(postsPolicy.isAllowed) // .get(videos.list) .post(videos.create); app.route('/api/posts/:postId/video/:videoId').all(postsPolicy.isAllowed) // .get(videos.read) .put(videos.update) .delete(videos.delete); app.route('/api/posts/:postId/comment').all(postsPolicy.isAllowed) .post(comments.addVideoComment); app.route('/api/posts/:postId/comment/:commentVideoId').all(postsPolicy.isAllowed) .delete(comments.deleteVideoComment); app.route('/api/posts/:postId/rate').all(postsPolicy.isAllowed) .get(rates.avgRating) .post(rates.addVideoRate); // app.route('/posts/:postId/rate/:rateVideoId'); /********************************************* List Posts Based on Passion and Intrests **********************************************/ app.route('/api/posts').all(postsPolicy.isAllowed) .get(posts.list); app.route('/api/posts/:passion') .get(posts.listPost); // app.route('/:skill/:areaOfSpecialization') // .get(posts.listSpecialities); /********************************************* List Posts Based on User **********************************************/ // app.route('/user') // .get(posts.userList); /******************************************** Finish By Binding Middleware *********************************************/ app.param('ideaId', ideas.ideaById); app.param('photoId', photos.photoById); app.param('videoId', videos.videoById); app.param('postId', posts.postById); app.param('rateIdeaId', rates.rateIdeaById); app.param('ratePhotoId', rates.ratePhotoById); app.param('rateVideoId', rates.rateVideoById); app.param('commentVideoId', comments.commentVideoById); app.param('commentPhotoId', comments.commentPhotoById); app.param('commentIdeaId', comments.commentIdeaById); };
// jquery, react and parrot2 const $ = require('jquery'); const React = require('react'); const ReactDOM = require('react-dom'); const {Parrot} = require('../../../../node_modules/nest-parrot2/dist/nest-parrot2'); const {Model, Layout, Envs, NForm, NComponent, NPanel, NTab} = Parrot; // electron related const electron = require('electron'); const {ipcRenderer} = electron; // commands constants const {Commands} = require('../../../common/commander'); // router for handle default webContents commands const router = require('../../common/router'); // require standard components from pre-define file const StandardComponents = require('../../components/standard-components'); // component categories class ComponentCategories extends NComponent { constructor(props) { super(props); this.onCategoryExpanded = this.onCategoryExpanded.bind(this); } postDidMount() { this.refs[StandardComponents.Categories[0].getId()].expand(); } renderCategory(category, categoryIndex) { return <NPanel model={this.getModel()} n-id={category.getId()} n-label={category.getLabel()} n-comp-style='borderless' n-comp-collapsible={true} n-comp-expanded={false} n-comp-children={this.getChildrenLayoutOfCategory(category)} n-styles-comp='owl-component-category' n-evt-expand={this.onCategoryExpanded} ref={category.getId()} key={categoryIndex} />; } renderInNormal() { return (<div className='owl-component-categories' ref='me'> {StandardComponents.Categories.map((category, categoryIndex) => { return this.renderCategory(category, categoryIndex); })} </div>); } getChildrenLayoutOfCategory(category) { return category.getComponents().reduce((layout, component, componentIndex) => { layout[component.getKey()] = { label: component.getLabel(), comp: { type: Envs.COMPONENT_TYPES.OWL_COMPONENT_DEF, define: component }, pos: {width: 6, row: 100, col: (componentIndex + 1) * 100} }; return layout; }, {}); } onCategoryExpanded(evt) { let target = evt.target; StandardComponents.Categories.map((category) => { return category.getId(); }).forEach((ref) => { let panel = this.refs[ref]; if (ReactDOM.findDOMNode(panel.refs.me) != target) { panel.collapse(); } }); } } Envs.COMPONENT_TYPES.OWL_COMPONENT_CATEGORIES = {type: 'owl-component-categories', label: false, error: false}; Envs.setRenderer(Envs.COMPONENT_TYPES.OWL_COMPONENT_CATEGORIES.type, function (options) { return <ComponentCategories {...options} />; }); // let it draggable and carry component definition class ComponentDef extends NComponent { constructor(props) { super(props); this.onDragStarted = this.onDragStarted.bind(this); } renderInNormal() { return (<div className='owl-component-def' draggable={true} onDragStart={this.onDragStarted} data-title={this.getLabel()}> {this.getLabel()} </div>); } getComponentKey() { return this.getLayoutOptionValue('define').getKey(); } onDragStarted(evt) { evt.dataTransfer.setData('componentKey', this.getComponentKey()); } } Envs.COMPONENT_TYPES.OWL_COMPONENT_DEF = {type: 'owl-component-def', label: false, error: false}; Envs.setRenderer(Envs.COMPONENT_TYPES.OWL_COMPONENT_DEF.type, function (options) { return <ComponentDef {...options} />; }); class SideBar extends React.Component { render() { return <NTab model={this.getModel()} layout={this.getLayout()} />; } getModel() { if (this.model == null) { this.model = new Model({}); } return this.model; } getLayout() { if (this.layout == null) { this.layout = this.createLayout(); } return this.layout; } createLayout() { return new Layout('sidebar', { comp: { style: 'primary', tabs: [{ label: 'Components', children: { categories: { comp: { type: Envs.COMPONENT_TYPES.OWL_COMPONENT_CATEGORIES }, pos: {width: 12, row: 100} } } }, { label: 'Folders', children: { name: {} } }] }, pos: {width: 12}, styles: { cell: 'side-bar-tab' } }); } toggleShown() { $('#side-bar').toggleClass('hide'); } } // work area, drag and drop component here class Content extends React.Component { constructor(props) { super(props); this.newComponentIndex = 1; this.onDropped = this.onDropped.bind(this); this.onDragOver = this.onDragOver.bind(this); this.onDragEnter = this.onDragEnter.bind(this); this.onDragLeave = this.onDragLeave.bind(this); } render() { return (<div className='page' onDrop={this.onDropped} onDragOver={this.onDragOver} onDragEnter={this.onDragEnter} onDragLeave={this.onDragLeave}> <NForm model={this.getFormModel()} layout={this.getFormLayout()} /> </div>); } getFormModel() { if (this.formModel == null) { this.formModel = new Model({}); } return this.formModel; } getFormLayout() { if (this.formLayout == null) { this.formLayout = new Layout('form', { comp: { children: {} } }); } return this.formLayout; } appendComponent(component) { let children = this.getFormLayout().getOptionValue('children'); let maxRow = Object.keys(children).reduce((maxRow, cellKey) => { let layout = children[cellKey]; let rowIndex = (layout && layout.pos) ? layout.pos.row : 0; if (rowIndex > maxRow) { maxRow = rowIndex; } return maxRow; }, 100); let maxCol = Object.keys(children).reduce((maxCol, cellKey) => { let layout = children[cellKey]; let rowIndex = (layout && layout.pos) ? layout.pos.row : 0; if (rowIndex === maxRow) { let columnIndex = (Layout && layout.pos) ? layout.pos.col : 0; if (columnIndex > maxCol) { maxCol = columnIndex; } } return maxCol + 100; }, 100); let cell = { label: component.getLabel(), comp: Envs.deepMergeTo({}, { type: component.getType(), enabled: false, // definition define: component }, component.getLayoutOptions()), styles: { cell: 'owl-component' }, pos: { width: component.getWidth(), row: maxRow, col: maxCol }, evt: { 'jq.click': this.onComponentClicked } }; children[`pseduo-${this.newComponentIndex++}`] = cell; // repaint this.forceUpdate(); } onDropped(evt) { evt.preventDefault(); evt.stopPropagation() let componentKey = evt.dataTransfer.getData('componentKey'); let component = StandardComponents.Components[componentKey]; this.appendComponent(component); } onDragOver(evt) { evt.preventDefault(); evt.stopPropagation() } onDragEnter(evt) { evt.preventDefault(); evt.stopPropagation() } onDragLeave(evt) { evt.preventDefault(); evt.stopPropagation() } onComponentClicked(evt) { bottombar.setEditComponent(this); } } class BottomBar extends React.Component { constructor(props) { super(props); this.state = {}; } render() { return <NTab model={this.getModel()} layout={this.getLayout()} />; } getModel() { if (this.state.model == null) { this.state.model = new Model({}); } return this.state.model; } getLayout() { if (this.state.layout == null) { this.state.layout = this.createLayout(); } return this.state.layout; } createLayout() { return new Layout('bottombar', { comp: { style: 'primary', tabs: [{ label: 'Property', children: this.getComponentAttributeLayout('property') }, { label: 'Position', children: this.getComponentAttributeLayout('position') }, { label: 'Styles', children: this.getComponentAttributeLayout('styles') }, { label: 'Event', children: this.getComponentAttributeLayout('event') }] }, pos: {width: 12}, styles: { cell: 'bottom-bar-tab' } }); } getNoAvailableAttributeLayout() { return { nothing: { label: 'No Available Attribute Designated.', comp: { type: Envs.COMPONENT_TYPES.LABEL, textFromModel: false }, pos: {width: 12, row: 100, col: 100} } }; } getNoComponentLayout() { return { nothing: { label: 'No Component Selected...', comp: { type: Envs.COMPONENT_TYPES.LABEL, textFromModel: false }, pos: {width: 12, row: 100, col: 100} } }; } toggleShown() { $('#bottom-bar').toggleClass('hide'); } setEditComponent(component) { this.setState({ layout: null, component: component }, () => { if (component) { $('#bottom-bar').removeClass('hide'); } }); } getEditComponent() { return this.state.component; } getComponentAttributeLayout(key) { let component = this.getEditComponent(); if (component) { let layout = component.getLayoutOptionValue('define').getAttributeLayout()[key]; return layout ? layout : this.getNoAvailableAttributeLayout(); } else { return this.getNoComponentLayout(); } } } class Working { renderSideBar() { return ReactDOM.render(<SideBar />, document.getElementById('side-bar')); } renderContent() { return ReactDOM.render(<Content />, document.getElementById('content')); } renderBottomBar() { return ReactDOM.render(<BottomBar />, document.getElementById('bottom-bar')); } } let working = new Working(); let sidebar = working.renderSideBar(); let content = working.renderContent(); let bottombar = working.renderBottomBar(); ipcRenderer.on(Commands.TOGGLE_SIDE_BAR, (evt, arg) => { sidebar.toggleShown(); }).on(Commands.TOGGLE_BOTTOM_BAR, (evt, arg) => { bottombar.toggleShown(); }); module.exports = working;
var config = {filters:[]}
const { readFile } = require('fs'); const xml2js = require('xml2js'); process.once('message', filename => { readFile(filename, (error, xmlString) => { if (error) { process.send({ error, result: null }); return; } const parser = new xml2js.Parser(); parser.parseString(xmlString, (error, result) => { if (error) { process.send({ error, result: null }); return; } process.send({ result }); }); }); });
//////////////////////////////////////////////////////////////////////////////// // Directory Selector Control // // Tree control designed specifically to display directories //////////////////////////////////////////////////////////////////////////////// /*global jQuery */ var app = app || {}; var alldirs = false; app.controls = function (controls, $, services) { // tells whether an object has any own propertes function hasOwnProperties(obj) { var prop; for (prop in obj) { if (obj.hasOwnProperty(prop)) { return true; } } return false; } // directory selection handler function onSelect($node, node) { var self = controls.lookup[$node.closest('.w_popup').attr('id')]; self.btnOk() .disabled({self: false}) .render(); } // directory expand / collapse handler // loads child directories on demand function onExpandCollapse($node, node) { var expanded = node.expanded(), empty = !hasOwnProperties(node.json()), $spinner; // acquiring sub-nodes when expanding an empty node if (expanded && empty) { $spinner = $node .closest('.w_popup') .find('.spinner') .show(); services.sys.dirlist(node.path().join('/'), function (json) { $spinner.hide(); empty = !hasOwnProperties(json.data); if (empty) { // no subdirs, removing expand button $node .removeClass('expanded') .addClass('dead'); } else { // has subdirs, creating child nodes node .json(json.data) .build() .render(); } }); } } controls.dirsel = function () { var self = controls.control.create(controls.popup('centered')), base_init = self.init, tree = controls.tree(onSelect, onExpandCollapse), btnCancel = controls.button("Cancel"), btnOk = controls.button("OK").disabled({self: true}); // initial service call for root dirs services.sys.dirlist(null, function (json) { // initial tree contents tree .json(json.data) .appendTo(self); // re-rendering full control self .render() .find('div.spinner') .hide(); }); ////////////////////////////// // Setters / getters self.onCancel = function (value) { btnCancel.onClick(value); return self; }; self.btnOk = function () { return btnOk; }; self.onOk = function (value) { btnOk.onClick(value); return self; }; self.selected = function () { return '/' + tree.selected().join('/'); }; ////////////////////////////// // Overrides self.build = function () { btnOk.appendTo(self); btnCancel.appendTo(self); return self; }; self.init = function (elem) { base_init.call(self, elem); elem .find('div.spinner') .show() .end() .find('table.status') .insertAfter(elem.find('ul.root')); }; self.contents = function () { return [ '<div class="spinner"></div>', '<span class="title">', "Add folder to library", '</span>', tree.html(), btnOk.html(), btnCancel.html() ].join(''); }; return self; }; return controls; }(app.controls, jQuery, app.services);
angular.module('myApp').controller('EditCtrl', ['$scope', '$stateParams', function($scope, $stateParams){ $scope.listRecieved.then(function(){ $scope.todo = _.findWhere( $scope.todos, { id: parseInt($stateParams.id) } ); }) }]);
'use strict'; const hasBlock = require('../../utils/hasBlock'); const isStandardSyntaxAtRule = require('../../utils/isStandardSyntaxAtRule'); const nextNonCommentNode = require('../../utils/nextNonCommentNode'); const rawNodeString = require('../../utils/rawNodeString'); const report = require('../../utils/report'); const ruleMessages = require('../../utils/ruleMessages'); const validateOptions = require('../../utils/validateOptions'); const whitespaceChecker = require('../../utils/whitespaceChecker'); const ruleName = 'at-rule-semicolon-newline-after'; const messages = ruleMessages(ruleName, { expectedAfter: () => 'Expected newline after ";"', }); const meta = { url: 'https://stylelint.io/user-guide/rules/list/at-rule-semicolon-newline-after', }; /** @type {import('stylelint').Rule} */ const rule = (primary, _secondary, context) => { const checker = whitespaceChecker('newline', primary, messages); return (root, result) => { const validOptions = validateOptions(result, ruleName, { actual: primary, possible: ['always'], }); if (!validOptions) { return; } root.walkAtRules((atRule) => { const nextNode = atRule.next(); if (!nextNode) { return; } if (hasBlock(atRule)) { return; } if (!isStandardSyntaxAtRule(atRule)) { return; } // Allow an end-of-line comment const nodeToCheck = nextNonCommentNode(nextNode); if (!nodeToCheck) { return; } checker.afterOneOnly({ source: rawNodeString(nodeToCheck), index: -1, err: (msg) => { if (context.fix) { nodeToCheck.raws.before = context.newline + nodeToCheck.raws.before; } else { report({ message: msg, node: atRule, index: atRule.toString().length + 1, result, ruleName, }); } }, }); }); }; }; rule.ruleName = ruleName; rule.messages = messages; rule.meta = meta; module.exports = rule;
"use strict"; var connect = require("connect"), logger = connect.logger(":method :url :status - :response-time ms"); var config = require("../../../shared/config"), paths = config.paths, env = require("../../../shared/env.js"); var Bundler = require("../../../core/bundle/Bundler.class.js"), parseURL = require("./middleware/parseURL.js"), serveInitPageShortcut = require("./middleware/serveInitPageShortcut.js"), serveInitPage = require("./middleware/serveInitPage.js"), notFoundAsset = require("./middleware/notFoundAsset.js"), staticFileHandler = require("./middleware/staticFileHandler.js"), defaultHeaders = require("./middleware/defaultHeaders.js"), checkContentType = require("./middleware/checkContentType.js"), httpAdapter = require("./middleware/httpAdapter.js"); function staticRequest() { var bundler; if (env.isDevelopment()) { staticRequestStack.unshift(logger); if (config.use.bundle) { bundler = Bundler.getInstance(); staticRequestStack.unshift(bundler.getDevMiddleware()); } } return staticRequestStack; } //ON REQUEST exports.request = [ parseURL, connect.json(), connect.urlencoded(), serveInitPageShortcut ]; //SERVICE REQUEST exports.serviceRequest = [ checkContentType(["application/json"]), defaultHeaders.setServiceHeader, httpAdapter ]; //VALIDATOR REQUEST exports.validatorRequest = [ checkContentType(["application/json"]), defaultHeaders.setValidatorHeader, httpAdapter ]; //STATIC REQUEST var staticRequestStack = [ staticFileHandler ]; //will be set on init //so you have to call init exports.staticRequest = null; //UNHANDLED REQUEST exports.unhandledRequest = [ notFoundAsset, serveInitPage ]; //ON REQUEST ERROR /** * Handler for errors within middleware-pipeline * ends the request and returns error-message depending on mode * @param err * @param req * @param res */ exports.requestError = function (err, req, res) { if (err) { if (env.isDevelopment()) { console.log(err.stack); res.end(err.toString(), "utf-8"); return; } res.statusCode = 500; res.end("(alamid) Internal Server Error."); } }; /** * helpers function to defined static file-server * @param staticFileHandler */ exports.setStaticFileHandler = function (staticFileHandler) { staticRequestStack = [ staticFileHandler ]; }; /** * don't forget to call init * before on server start */ exports.init = function () { //TODO find a better way to solve this problem //routes should not be initialized on require exports.staticRequest = staticRequest(); };
(function (app) { var helper = app('helper'); var pushToWatchedArray = helper('pushToWatchedArray'); var dom = app('dom'); var UiPopupClass = app('bb-co')('ui-popup-menu', 'ui-popup', { tpl: 'scripts/ui-controllers/components/ui-controls/menus/ui-popup-menu', overflow: false, init: function () { UiPopupClass._parent.init.apply(this, arguments); this.defineScope({ items: [] }); }, setItems: function (data) { var list = this.getScope().items; list.clear(); pushToWatchedArray(list, data); }, processContent: function (content) { var self = this; self.showPopup(); // bind to parent el for catch showing content.parent().on('jrclick', function (ev) { self.showPopup(); }); content.on('jrclick', function (ev) { var items = self.getScope().items; var item = self.getRepeatScopeItem(ev, '.ui-popup-menu-item', items); var ret; if (item) { ret = self.onItemClick(item); } else { if (self.canOutsideClick()) { if (dom.closest(ev.target, 'uia-overflow')) { ret = true; } else { ret = self.onContentClick(ev); } } else { ret = self.onContentClick(ev); } } if (ret !== false){ self.isShown() && self.hidePopup(); } }); UiPopupClass._parent.processContent.apply(this, arguments); }, onItemClick: function (item) { // cap }, onContentClick: function () { // cap } }); })(window.app);
"use strict"; var __assign = (this && this.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; /** * * * Created by Administrator on 2016/1/26. */ const React = require('react'); const react_redux_1 = require('react-redux'); const antd_1 = require('antd'); require('./style.scss'); const LoginForm_1 = require('./LoginForm'); const mapStateToProps = (state) => ({ login: state.login }); class Login extends React.Component { render() { return (React.createElement("div", null, React.createElement(antd_1.Row, {className: 'form', type: "flex", justify: "center"}, React.createElement(antd_1.Col, {span: 10}, React.createElement(LoginForm_1.default, __assign({}, this.props)))))); } } exports.Login = Login; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = react_redux_1.connect(mapStateToProps)(Login); //# sourceMappingURL=LoginIn.js.map
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Bubbles from '../../components/Bubbles/Bubbles.container'; import env from '../../.env'; import './Hub.css'; class Hub extends Component { componentDidMount() { this.props.listenData(); } render() { return ([ <div className="hub-container"> <Bubbles /> <a href={env.DEMO_URL}>{env.DEMO_URL}</a> </div>, ]); } } Hub.propTypes = { listenData: PropTypes.func.isRequired, }; export default Hub;
import React from 'react' import { View } from 'react-vr' import Asteroid01 from './Asteroid01'; import Asteroid02 from './Asteroid02'; import Asteroid03 from './Asteroid03'; import Earth from './Earth'; import Moon from './Moon'; export default class World extends React.Component { render() { return ( <View> <Asteroid01 style={{ transform: [ {scale: 0.5}, {translate: [20, -3, -330]}, ] }} /> <Asteroid01 style={{ transform: [ {scale: 1.7}, {translate: [-80, 33, -180]}, ] }} /> <Asteroid02 style={{ transform: [ {scale: 0.9}, {translate: [-30, 12, -120]}, ] }} /> <Asteroid03 style={{ transform: [ {scale: 1}, {translate: [50, -3, -50]}, ] }} /> <Earth style={{ transform: [ {scale: 3.2}, {translate: [-72, -10, -170]}, ] }} /> <Moon style={{ transform: [ {scale: 3}, {translate: [60, 10, -220]}, ] }} /> </View> ); } }
import {isIdentifierStart, isIdentifierChar} from "./identifier.js" import {Parser} from "./state.js" import UNICODE_PROPERTY_VALUES from "./unicode-property-data.js" import {has} from "./util.js" const pp = Parser.prototype export class RegExpValidationState { constructor(parser) { this.parser = parser this.validFlags = `gim${parser.options.ecmaVersion >= 6 ? "uy" : ""}${parser.options.ecmaVersion >= 9 ? "s" : ""}` this.unicodeProperties = UNICODE_PROPERTY_VALUES[parser.options.ecmaVersion >= 11 ? 11 : parser.options.ecmaVersion] this.source = "" this.flags = "" this.start = 0 this.switchU = false this.switchN = false this.pos = 0 this.lastIntValue = 0 this.lastStringValue = "" this.lastAssertionIsQuantifiable = false this.numCapturingParens = 0 this.maxBackReference = 0 this.groupNames = [] this.backReferenceNames = [] } reset(start, pattern, flags) { const unicode = flags.indexOf("u") !== -1 this.start = start | 0 this.source = pattern + "" this.flags = flags this.switchU = unicode && this.parser.options.ecmaVersion >= 6 this.switchN = unicode && this.parser.options.ecmaVersion >= 9 } raise(message) { this.parser.raiseRecoverable(this.start, `Invalid regular expression: /${this.source}/: ${message}`) } // If u flag is given, this returns the code point at the index (it combines a surrogate pair). // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair). at(i, forceU = false) { const s = this.source const l = s.length if (i >= l) { return -1 } const c = s.charCodeAt(i) if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { return c } const next = s.charCodeAt(i + 1) return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c } nextIndex(i, forceU = false) { const s = this.source const l = s.length if (i >= l) { return l } let c = s.charCodeAt(i), next if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l || (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) { return i + 1 } return i + 2 } current(forceU = false) { return this.at(this.pos, forceU) } lookahead(forceU = false) { return this.at(this.nextIndex(this.pos, forceU), forceU) } advance(forceU = false) { this.pos = this.nextIndex(this.pos, forceU) } eat(ch, forceU = false) { if (this.current(forceU) === ch) { this.advance(forceU) return true } return false } } function codePointToString(ch) { if (ch <= 0xFFFF) return String.fromCharCode(ch) ch -= 0x10000 return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00) } /** * Validate the flags part of a given RegExpLiteral. * * @param {RegExpValidationState} state The state to validate RegExp. * @returns {void} */ pp.validateRegExpFlags = function(state) { const validFlags = state.validFlags const flags = state.flags for (let i = 0; i < flags.length; i++) { const flag = flags.charAt(i) if (validFlags.indexOf(flag) === -1) { this.raise(state.start, "Invalid regular expression flag") } if (flags.indexOf(flag, i + 1) > -1) { this.raise(state.start, "Duplicate regular expression flag") } } } /** * Validate the pattern part of a given RegExpLiteral. * * @param {RegExpValidationState} state The state to validate RegExp. * @returns {void} */ pp.validateRegExpPattern = function(state) { this.regexp_pattern(state) // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of // parsing contains a |GroupName|, reparse with the goal symbol // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError* // exception if _P_ did not conform to the grammar, if any elements of _P_ // were not matched by the parse, or if any Early Error conditions exist. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { state.switchN = true this.regexp_pattern(state) } } // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern pp.regexp_pattern = function(state) { state.pos = 0 state.lastIntValue = 0 state.lastStringValue = "" state.lastAssertionIsQuantifiable = false state.numCapturingParens = 0 state.maxBackReference = 0 state.groupNames.length = 0 state.backReferenceNames.length = 0 this.regexp_disjunction(state) if (state.pos !== state.source.length) { // Make the same messages as V8. if (state.eat(0x29 /* ) */)) { state.raise("Unmatched ')'") } if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) { state.raise("Lone quantifier brackets") } } if (state.maxBackReference > state.numCapturingParens) { state.raise("Invalid escape") } for (const name of state.backReferenceNames) { if (state.groupNames.indexOf(name) === -1) { state.raise("Invalid named capture referenced") } } } // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction pp.regexp_disjunction = function(state) { this.regexp_alternative(state) while (state.eat(0x7C /* | */)) { this.regexp_alternative(state) } // Make the same message as V8. if (this.regexp_eatQuantifier(state, true)) { state.raise("Nothing to repeat") } if (state.eat(0x7B /* { */)) { state.raise("Lone quantifier brackets") } } // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative pp.regexp_alternative = function(state) { while (state.pos < state.source.length && this.regexp_eatTerm(state)) ; } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term pp.regexp_eatTerm = function(state) { if (this.regexp_eatAssertion(state)) { // Handle `QuantifiableAssertion Quantifier` alternative. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion // is a QuantifiableAssertion. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { // Make the same message as V8. if (state.switchU) { state.raise("Invalid quantifier") } } return true } if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { this.regexp_eatQuantifier(state) return true } return false } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion pp.regexp_eatAssertion = function(state) { const start = state.pos state.lastAssertionIsQuantifiable = false // ^, $ if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { return true } // \b \B if (state.eat(0x5C /* \ */)) { if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { return true } state.pos = start } // Lookahead / Lookbehind if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) { let lookbehind = false if (this.options.ecmaVersion >= 9) { lookbehind = state.eat(0x3C /* < */) } if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) { this.regexp_disjunction(state) if (!state.eat(0x29 /* ) */)) { state.raise("Unterminated group") } state.lastAssertionIsQuantifiable = !lookbehind return true } } state.pos = start return false } // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier pp.regexp_eatQuantifier = function(state, noError = false) { if (this.regexp_eatQuantifierPrefix(state, noError)) { state.eat(0x3F /* ? */) return true } return false } // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix pp.regexp_eatQuantifierPrefix = function(state, noError) { return ( state.eat(0x2A /* * */) || state.eat(0x2B /* + */) || state.eat(0x3F /* ? */) || this.regexp_eatBracedQuantifier(state, noError) ) } pp.regexp_eatBracedQuantifier = function(state, noError) { const start = state.pos if (state.eat(0x7B /* { */)) { let min = 0, max = -1 if (this.regexp_eatDecimalDigits(state)) { min = state.lastIntValue if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) { max = state.lastIntValue } if (state.eat(0x7D /* } */)) { // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term if (max !== -1 && max < min && !noError) { state.raise("numbers out of order in {} quantifier") } return true } } if (state.switchU && !noError) { state.raise("Incomplete quantifier") } state.pos = start } return false } // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom pp.regexp_eatAtom = function(state) { return ( this.regexp_eatPatternCharacters(state) || state.eat(0x2E /* . */) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) ) } pp.regexp_eatReverseSolidusAtomEscape = function(state) { const start = state.pos if (state.eat(0x5C /* \ */)) { if (this.regexp_eatAtomEscape(state)) { return true } state.pos = start } return false } pp.regexp_eatUncapturingGroup = function(state) { const start = state.pos if (state.eat(0x28 /* ( */)) { if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) { this.regexp_disjunction(state) if (state.eat(0x29 /* ) */)) { return true } state.raise("Unterminated group") } state.pos = start } return false } pp.regexp_eatCapturingGroup = function(state) { if (state.eat(0x28 /* ( */)) { if (this.options.ecmaVersion >= 9) { this.regexp_groupSpecifier(state) } else if (state.current() === 0x3F /* ? */) { state.raise("Invalid group") } this.regexp_disjunction(state) if (state.eat(0x29 /* ) */)) { state.numCapturingParens += 1 return true } state.raise("Unterminated group") } return false } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom pp.regexp_eatExtendedAtom = function(state) { return ( state.eat(0x2E /* . */) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) || this.regexp_eatInvalidBracedQuantifier(state) || this.regexp_eatExtendedPatternCharacter(state) ) } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier pp.regexp_eatInvalidBracedQuantifier = function(state) { if (this.regexp_eatBracedQuantifier(state, true)) { state.raise("Nothing to repeat") } return false } // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter pp.regexp_eatSyntaxCharacter = function(state) { const ch = state.current() if (isSyntaxCharacter(ch)) { state.lastIntValue = ch state.advance() return true } return false } function isSyntaxCharacter(ch) { return ( ch === 0x24 /* $ */ || ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ || ch === 0x2E /* . */ || ch === 0x3F /* ? */ || ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ || ch >= 0x7B /* { */ && ch <= 0x7D /* } */ ) } // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter // But eat eager. pp.regexp_eatPatternCharacters = function(state) { const start = state.pos let ch = 0 while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { state.advance() } return state.pos !== start } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter pp.regexp_eatExtendedPatternCharacter = function(state) { const ch = state.current() if ( ch !== -1 && ch !== 0x24 /* $ */ && !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) && ch !== 0x2E /* . */ && ch !== 0x3F /* ? */ && ch !== 0x5B /* [ */ && ch !== 0x5E /* ^ */ && ch !== 0x7C /* | */ ) { state.advance() return true } return false } // GroupSpecifier :: // [empty] // `?` GroupName pp.regexp_groupSpecifier = function(state) { if (state.eat(0x3F /* ? */)) { if (this.regexp_eatGroupName(state)) { if (state.groupNames.indexOf(state.lastStringValue) !== -1) { state.raise("Duplicate capture group name") } state.groupNames.push(state.lastStringValue) return } state.raise("Invalid group") } } // GroupName :: // `<` RegExpIdentifierName `>` // Note: this updates `state.lastStringValue` property with the eaten name. pp.regexp_eatGroupName = function(state) { state.lastStringValue = "" if (state.eat(0x3C /* < */)) { if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) { return true } state.raise("Invalid capture group name") } return false } // RegExpIdentifierName :: // RegExpIdentifierStart // RegExpIdentifierName RegExpIdentifierPart // Note: this updates `state.lastStringValue` property with the eaten name. pp.regexp_eatRegExpIdentifierName = function(state) { state.lastStringValue = "" if (this.regexp_eatRegExpIdentifierStart(state)) { state.lastStringValue += codePointToString(state.lastIntValue) while (this.regexp_eatRegExpIdentifierPart(state)) { state.lastStringValue += codePointToString(state.lastIntValue) } return true } return false } // RegExpIdentifierStart :: // UnicodeIDStart // `$` // `_` // `\` RegExpUnicodeEscapeSequence[+U] pp.regexp_eatRegExpIdentifierStart = function(state) { const start = state.pos const forceU = this.options.ecmaVersion >= 11 let ch = state.current(forceU) state.advance(forceU) if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { ch = state.lastIntValue } if (isRegExpIdentifierStart(ch)) { state.lastIntValue = ch return true } state.pos = start return false } function isRegExpIdentifierStart(ch) { return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ } // RegExpIdentifierPart :: // UnicodeIDContinue // `$` // `_` // `\` RegExpUnicodeEscapeSequence[+U] // <ZWNJ> // <ZWJ> pp.regexp_eatRegExpIdentifierPart = function(state) { const start = state.pos const forceU = this.options.ecmaVersion >= 11 let ch = state.current(forceU) state.advance(forceU) if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { ch = state.lastIntValue } if (isRegExpIdentifierPart(ch)) { state.lastIntValue = ch return true } state.pos = start return false } function isRegExpIdentifierPart(ch) { return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape pp.regexp_eatAtomEscape = function(state) { if ( this.regexp_eatBackReference(state) || this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) || (state.switchN && this.regexp_eatKGroupName(state)) ) { return true } if (state.switchU) { // Make the same message as V8. if (state.current() === 0x63 /* c */) { state.raise("Invalid unicode escape") } state.raise("Invalid escape") } return false } pp.regexp_eatBackReference = function(state) { const start = state.pos if (this.regexp_eatDecimalEscape(state)) { const n = state.lastIntValue if (state.switchU) { // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape if (n > state.maxBackReference) { state.maxBackReference = n } return true } if (n <= state.numCapturingParens) { return true } state.pos = start } return false } pp.regexp_eatKGroupName = function(state) { if (state.eat(0x6B /* k */)) { if (this.regexp_eatGroupName(state)) { state.backReferenceNames.push(state.lastStringValue) return true } state.raise("Invalid named reference") } return false } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape pp.regexp_eatCharacterEscape = function(state) { return ( this.regexp_eatControlEscape(state) || this.regexp_eatCControlLetter(state) || this.regexp_eatZero(state) || this.regexp_eatHexEscapeSequence(state) || this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) || this.regexp_eatIdentityEscape(state) ) } pp.regexp_eatCControlLetter = function(state) { const start = state.pos if (state.eat(0x63 /* c */)) { if (this.regexp_eatControlLetter(state)) { return true } state.pos = start } return false } pp.regexp_eatZero = function(state) { if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) { state.lastIntValue = 0 state.advance() return true } return false } // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape pp.regexp_eatControlEscape = function(state) { const ch = state.current() if (ch === 0x74 /* t */) { state.lastIntValue = 0x09 /* \t */ state.advance() return true } if (ch === 0x6E /* n */) { state.lastIntValue = 0x0A /* \n */ state.advance() return true } if (ch === 0x76 /* v */) { state.lastIntValue = 0x0B /* \v */ state.advance() return true } if (ch === 0x66 /* f */) { state.lastIntValue = 0x0C /* \f */ state.advance() return true } if (ch === 0x72 /* r */) { state.lastIntValue = 0x0D /* \r */ state.advance() return true } return false } // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter pp.regexp_eatControlLetter = function(state) { const ch = state.current() if (isControlLetter(ch)) { state.lastIntValue = ch % 0x20 state.advance() return true } return false } function isControlLetter(ch) { return ( (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) || (ch >= 0x61 /* a */ && ch <= 0x7A /* z */) ) } // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence pp.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU = false) { const start = state.pos const switchU = forceU || state.switchU if (state.eat(0x75 /* u */)) { if (this.regexp_eatFixedHexDigits(state, 4)) { const lead = state.lastIntValue if (switchU && lead >= 0xD800 && lead <= 0xDBFF) { const leadSurrogateEnd = state.pos if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) { const trail = state.lastIntValue if (trail >= 0xDC00 && trail <= 0xDFFF) { state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000 return true } } state.pos = leadSurrogateEnd state.lastIntValue = lead } return true } if ( switchU && state.eat(0x7B /* { */) && this.regexp_eatHexDigits(state) && state.eat(0x7D /* } */) && isValidUnicode(state.lastIntValue) ) { return true } if (switchU) { state.raise("Invalid unicode escape") } state.pos = start } return false } function isValidUnicode(ch) { return ch >= 0 && ch <= 0x10FFFF } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape pp.regexp_eatIdentityEscape = function(state) { if (state.switchU) { if (this.regexp_eatSyntaxCharacter(state)) { return true } if (state.eat(0x2F /* / */)) { state.lastIntValue = 0x2F /* / */ return true } return false } const ch = state.current() if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { state.lastIntValue = ch state.advance() return true } return false } // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape pp.regexp_eatDecimalEscape = function(state) { state.lastIntValue = 0 let ch = state.current() if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) { do { state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */) state.advance() } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) return true } return false } // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape pp.regexp_eatCharacterClassEscape = function(state) { const ch = state.current() if (isCharacterClassEscape(ch)) { state.lastIntValue = -1 state.advance() return true } if ( state.switchU && this.options.ecmaVersion >= 9 && (ch === 0x50 /* P */ || ch === 0x70 /* p */) ) { state.lastIntValue = -1 state.advance() if ( state.eat(0x7B /* { */) && this.regexp_eatUnicodePropertyValueExpression(state) && state.eat(0x7D /* } */) ) { return true } state.raise("Invalid property name") } return false } function isCharacterClassEscape(ch) { return ( ch === 0x64 /* d */ || ch === 0x44 /* D */ || ch === 0x73 /* s */ || ch === 0x53 /* S */ || ch === 0x77 /* w */ || ch === 0x57 /* W */ ) } // UnicodePropertyValueExpression :: // UnicodePropertyName `=` UnicodePropertyValue // LoneUnicodePropertyNameOrValue pp.regexp_eatUnicodePropertyValueExpression = function(state) { const start = state.pos // UnicodePropertyName `=` UnicodePropertyValue if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) { const name = state.lastStringValue if (this.regexp_eatUnicodePropertyValue(state)) { const value = state.lastStringValue this.regexp_validateUnicodePropertyNameAndValue(state, name, value) return true } } state.pos = start // LoneUnicodePropertyNameOrValue if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { const nameOrValue = state.lastStringValue this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue) return true } return false } pp.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { if (!has(state.unicodeProperties.nonBinary, name)) state.raise("Invalid property name") if (!state.unicodeProperties.nonBinary[name].test(value)) state.raise("Invalid property value") } pp.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { if (!state.unicodeProperties.binary.test(nameOrValue)) state.raise("Invalid property name") } // UnicodePropertyName :: // UnicodePropertyNameCharacters pp.regexp_eatUnicodePropertyName = function(state) { let ch = 0 state.lastStringValue = "" while (isUnicodePropertyNameCharacter(ch = state.current())) { state.lastStringValue += codePointToString(ch) state.advance() } return state.lastStringValue !== "" } function isUnicodePropertyNameCharacter(ch) { return isControlLetter(ch) || ch === 0x5F /* _ */ } // UnicodePropertyValue :: // UnicodePropertyValueCharacters pp.regexp_eatUnicodePropertyValue = function(state) { let ch = 0 state.lastStringValue = "" while (isUnicodePropertyValueCharacter(ch = state.current())) { state.lastStringValue += codePointToString(ch) state.advance() } return state.lastStringValue !== "" } function isUnicodePropertyValueCharacter(ch) { return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch) } // LoneUnicodePropertyNameOrValue :: // UnicodePropertyValueCharacters pp.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { return this.regexp_eatUnicodePropertyValue(state) } // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass pp.regexp_eatCharacterClass = function(state) { if (state.eat(0x5B /* [ */)) { state.eat(0x5E /* ^ */) this.regexp_classRanges(state) if (state.eat(0x5D /* ] */)) { return true } // Unreachable since it threw "unterminated regular expression" error before. state.raise("Unterminated character class") } return false } // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash pp.regexp_classRanges = function(state) { while (this.regexp_eatClassAtom(state)) { const left = state.lastIntValue if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) { const right = state.lastIntValue if (state.switchU && (left === -1 || right === -1)) { state.raise("Invalid character class") } if (left !== -1 && right !== -1 && left > right) { state.raise("Range out of order in character class") } } } } // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash pp.regexp_eatClassAtom = function(state) { const start = state.pos if (state.eat(0x5C /* \ */)) { if (this.regexp_eatClassEscape(state)) { return true } if (state.switchU) { // Make the same message as V8. const ch = state.current() if (ch === 0x63 /* c */ || isOctalDigit(ch)) { state.raise("Invalid class escape") } state.raise("Invalid escape") } state.pos = start } const ch = state.current() if (ch !== 0x5D /* ] */) { state.lastIntValue = ch state.advance() return true } return false } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape pp.regexp_eatClassEscape = function(state) { const start = state.pos if (state.eat(0x62 /* b */)) { state.lastIntValue = 0x08 /* <BS> */ return true } if (state.switchU && state.eat(0x2D /* - */)) { state.lastIntValue = 0x2D /* - */ return true } if (!state.switchU && state.eat(0x63 /* c */)) { if (this.regexp_eatClassControlLetter(state)) { return true } state.pos = start } return ( this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) ) } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter pp.regexp_eatClassControlLetter = function(state) { const ch = state.current() if (isDecimalDigit(ch) || ch === 0x5F /* _ */) { state.lastIntValue = ch % 0x20 state.advance() return true } return false } // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence pp.regexp_eatHexEscapeSequence = function(state) { const start = state.pos if (state.eat(0x78 /* x */)) { if (this.regexp_eatFixedHexDigits(state, 2)) { return true } if (state.switchU) { state.raise("Invalid escape") } state.pos = start } return false } // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits pp.regexp_eatDecimalDigits = function(state) { const start = state.pos let ch = 0 state.lastIntValue = 0 while (isDecimalDigit(ch = state.current())) { state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */) state.advance() } return state.pos !== start } function isDecimalDigit(ch) { return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits pp.regexp_eatHexDigits = function(state) { const start = state.pos let ch = 0 state.lastIntValue = 0 while (isHexDigit(ch = state.current())) { state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch) state.advance() } return state.pos !== start } function isHexDigit(ch) { return ( (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) || (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) || (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) ) } function hexToInt(ch) { if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) { return 10 + (ch - 0x41 /* A */) } if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) { return 10 + (ch - 0x61 /* a */) } return ch - 0x30 /* 0 */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence // Allows only 0-377(octal) i.e. 0-255(decimal). pp.regexp_eatLegacyOctalEscapeSequence = function(state) { if (this.regexp_eatOctalDigit(state)) { const n1 = state.lastIntValue if (this.regexp_eatOctalDigit(state)) { const n2 = state.lastIntValue if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue } else { state.lastIntValue = n1 * 8 + n2 } } else { state.lastIntValue = n1 } return true } return false } // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit pp.regexp_eatOctalDigit = function(state) { const ch = state.current() if (isOctalDigit(ch)) { state.lastIntValue = ch - 0x30 /* 0 */ state.advance() return true } state.lastIntValue = 0 return false } function isOctalDigit(ch) { return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence pp.regexp_eatFixedHexDigits = function(state, length) { const start = state.pos state.lastIntValue = 0 for (let i = 0; i < length; ++i) { const ch = state.current() if (!isHexDigit(ch)) { state.pos = start return false } state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch) state.advance() } return true }
import Vue from 'vue'; import Layout from 'component/layout/html'; Vue.component(Layout.name, Layout);
// monkey patching String.prototype.endsWith = function(suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; }; var libsw = new LibSpaceWalk(); var storedValues = {}; var colors = { orange: '#e89f49', lime: '#b6ce4e', turquise: '#5dd1a4', blue: '#3fc0c9', lightBlue: '#C1DFE1', lavender: '#8885ed', rose: '#c673d8', red: '#e25454' } libsw.onMessage = function(data) { if (data.type === 'ext.input.gamePad.sample') { var payload = data.payload; if (payload.type === 'digital') { // aka button press/release var digitalDiv = d3.select('#digital'); var selection = digitalDiv.selectAll('#' + payload.name).data([payload]); selection.enter() .append('div') .attr('id', function(d) { return d.name; }) .attr('class', 'digitalIndicator') .text(function(d) { return d.name; }) if (storedValues[payload.name]) { // on --> off transition if (storedValues[payload.name].value === 1 && payload.value === 0) { selection .style('background-color', colors.lavender) .transition() .duration(500) .style('width', '100px'); } // off --> on transition if (storedValues[payload.name].value === 0 && payload.value === 1) { selection .style('background-color', colors.red) .transition() .duration(500) .style('background-color', colors.lavender); } } if (payload.value === 1) { selection.transition() .duration(0) .style('width', '300px'); } // store value storedValues[payload.name] = payload; } else { // analog values, i.e. axes var selection = d3.select('#analog').selectAll('#' + payload.name).data([payload]); var div = selection.enter().append('div') .attr('id', payload.name) .text(payload.name); div.append('hr'); div.append('span') .text('•'); var margin = map(payload.range.min, payload.range.max, 0, 300, payload.value); selection.select('span') .style('margin-left', margin + 'px'); } } } libsw.onSessionStarted = function() { } // ================================= util ================================ function round(value, decimals) { decimals = decimals || 0; var v = value * Math.pow(10, decimals); return Math.round(v) / Math.pow(10, decimals); } function last(arr) { return arr[arr.length-1]; } // map value, from [a, b] to [r, s] function map(a, b, r, s, value) { var t = (value - a) / (b -a); return r + (s - r) * t; }
import BatchDownloadController, { buildDownloadOptionsIndex } from './base'; /** * Batch-download controller for downloads in individual sections within a file table of the file * gallery. It only offers one download options. * @param {object} dataset Contains dataset with files to download * @param {object} query QueryString of currently selected file facet terms */ export default class ElementsReferencesDownloadController extends BatchDownloadController { preBuildDownloadOptions(dataset, query) { this._elementsReferences = dataset.elements_references; this._query = query; this._downloadOptionsTemplate = [ { id: 'elements-references', label: 'Download reference files', title: 'Reference files', description: 'Downloads reference files with the selected output types.', query: '', }, ]; this._downloadOptionsTemplateIndex = buildDownloadOptionsIndex(this._downloadOptionsTemplate); } /** * Format the reference-file download query string. */ formatReferenceFileQuery() { this._query.addKeyValue('type', 'Reference'); this._elementsReferences?.forEach((elementsReference) => { this._query.addKeyValue('@id', elementsReference['@id']); }); this._referenceFileQueryString = this._query.format(); } /** * Overrides the base class's method to build all applicable query strings. */ buildQueryStrings() { this.formatReferenceFileQuery(); } /** * Overrides the base class's method to build the download options. */ buildDownloadOptions() { // Build all the query strings based on the dataset. this.buildQueryStrings(); // Add the base download options menu configurations. this._downloadOptions = [ { ...this._downloadOptionsTemplate[this._downloadOptionsTemplateIndex['elements-references']], query: this._referenceFileQueryString, }, ]; // Build the index of this class's custom download options. this._downloadOptionsIndex = buildDownloadOptionsIndex(this._downloadOptions); } }
function loadfs() { //check if browser supports file api and filereader features if (window.File && window.FileReader && window.FileList && window.Blob) { //this is not completely neccesary, just a nice function I found to make the //file size format friendlier //http://stackoverflow.com/questions/10420352/converting-file-size-in-bytes-to-human-readable function humanFileSize(bytes, si) { var thresh = si ? 1000 : 1024; if(bytes < thresh) return bytes + ' B'; var units = si ? ['kB','MB','GB','TB','PB','EB','ZB','YB'] : ['KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB']; var u = -1; do { bytes /= thresh; ++u; } while(bytes >= thresh); return bytes.toFixed(1)+' '+units[u]; } //this function is called when the input loads an image function renderDB(file){ var reader = new FileReader(); reader.onload = function(event){ // console.log("event") // console.log(event) source = event.target // console.log("source") // console.log(source) encobj = source.result.split(',') // console.log(encobj) if (encobj[0].includes("base64")) { $('#name').html(file.name) $('#size').html(humanFileSize(file.size, "MB")) $('#type').html(file.type) db = JSON.parse(atob(encobj[1])) // console.log("Name") // console.log(file.name) nb = new acorn.Notebook(db, file.name) console.log(nb) console.log(db) } } //when the file is read it triggers the onload event above. // console.log("Prefile"); // console.log(file); // console.log("Postfile"); reader.readAsDataURL(file); } //watch for change on the $('#acorndb').change(function() { //grab the first image in the fileList //in this example we are only loading one file. // console.log("first") // console.log(this.files[0].size) // console.log(this.files[0]) renderDB(this.files[0]) }); // console.log("Loaded") } else { alert('The File APIs are not fully supported in this browser.'); } }
var internApplication = (function(){ var currentLat, currentLong, responseData, currentRestaurant, currentRestaurantNum, initialSearchFinished; var options = {}; // set options based on filters chosen by user var setOptions = function(){ var radiusValue = document.getElementById('distanceFilter').querySelector('.selected').getAttribute('value'); options.radius = (radiusValue * 1609.34).toFixed(0); } // get user's current location var getLocation = function(callback){ console.log('getting location...'); // use html5 if(location.protocol == 'https:' && navigator.geolocation) { function getPosition(position){ currentLat = position.coords.latitude.toFixed(8); currentLong = position.coords.longitude.toFixed(8); callback(); } navigator.geolocation.getCurrentPosition(getPosition); // use freegeoip.net as a fallback } else { console.log('using freegeoip.net...'); var georequestOptions = { method: 'GET', url: 'http://www.freegeoip.net/json/' }; var geoRequest = new XMLHttpRequest(); geoRequest.onload = function(){ callback.apply(geoRequest); } geoRequest.open(georequestOptions.method, georequestOptions.url); geoRequest.send(); } } var search = function(){ // set search state initialSearchFinished = false; setOptions(); // use html5 if(location.protocol == 'https:' && navigator.geolocation) { getLocation(function(){ // get data based on current search getZomatoData(0, 20, function(){ reroll(); }); }); // use freegeoip.net as a fallback }else { getLocation(function(){ var geoRequestRes = JSON.parse(this.response); currentLat = geoRequestRes.latitude; currentLong = geoRequestRes.longitude; console.log(currentLat + ', ' + currentLong); // get data based on current search getZomatoData(0, 20, function(){ reroll(); }); }); } } var reroll = function(){ console.log('rerolling...'); // get random restaurant number based on current search randomRestaurant(responseData); // get the chosen restaurant data getZomatoData(currentRestaurantNum, 1, function(){ currentRestaurant = responseData; console.log(responseData); // populate result internApplicationView.populateResult(currentRestaurant.restaurants[0].restaurant.featured_image, currentRestaurant.restaurants[0].restaurant.name, currentRestaurant.restaurants[0].restaurant.location.address, currentRestaurant.restaurants[0].restaurant.price_range); }); // if the initial search has finished... if(!initialSearchFinished){ // search is finished initialSearchFinished = true; // hide loading screen $('#loadingScreen').animate({opacity: 0}, internApplicationView.filtersConfig.fadeTime, function(){ this.style.display = 'none'; }); } } // get Zomato data from the api var getZomatoData = function(start, count, callback){ console.log('getting Zomato response data...'); // options to be sent to server var dataOptions = { start: start, count: count, currentLat: currentLat, currentLong: currentLong, radius: options.radius }; console.log(dataOptions); // server request to get data $.ajax({ url: 'http://localhost:6060/get-zomato-data/', type: 'GET', data: dataOptions, success: function(returnedData) { responseData = returnedData; callback(); } }); } // pick a random restaurant from the api response var randomRestaurant = function(responseData){ console.log('picking random restaurant from results...'); var max = responseData.results_found; currentRestaurantNum = getRandomInt(max); } // selects a random intiger given a maximum number var getRandomInt = function(maxVal) { var min = 0; var max = maxVal; // Zomato request limits 'start' to 100, so only the first 100 results may be used if (max > 100){ max = 100; } return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive } return { getLocation: getLocation, options: options, reroll: reroll, search: search, setOptions: setOptions } }());
//Change 'test123' below and in python interface to a more secure password var Sequelize = require('sequelize'); var sequelize = new Sequelize('adna', 'postgres', 'test123', { dialect: 'postgres' }); module.exports = sequelize;
module.exports = function (grunt) { var js_files = ['Gruntfile.js', 'chance.js', 'test/*.js']; grunt.initConfig({ 'js-test': { options: { coverage: true, coverageTool: 'istanbul', coverageFormat: 'lcov', identifier: 'chance-coverage', reporter: "Spec", pattern: 'test/*.js' }, watch: { options: { coverage: false, reporter: "Dot", pattern: 'test/*.js', root: '.' } } }, jshint: { options: { // Enforcing curly: true, eqeqeq: true, immed: true, indent: 4, latedef: true, newcap: true, noarg: true, undef: true, unused: true, // Relaxing boss: true, eqnull: true, expr: true, sub: true, // Environments browser: true, mocha: true, node: true, // Custom Globals globals: { _: true, chai: true, chance: true, Chance: true, define: false, mocha: true, mochaPhantomJS: false, phoneNumber: true } }, all: js_files }, shell: { target: { command: 'cat coverage/chance-coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js && rm -rf ./coverage' } }, uglify: { my_target: { options: { sourceMap: true, sourceMapName: 'chance.min.js.map' }, files: { 'chance.min.js': ['chance.js'] } } }, watch: { options: { livereload: true }, files: js_files, tasks: ['jshint', 'js-test:watch', 'uglify'] } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-js-test'); grunt.loadNpmTasks('grunt-shell'); grunt.registerTask('default', ['watch']); grunt.registerTask('test', ['js-test', 'shell']); grunt.registerTask('test-ci', ['jshint', 'js-test', 'shell']); };
export default stats => (req, res, next) => res.send('Hello Server');
 /* var randomBetween = function (from, to) { return Math.floor(Math.random() * (to - from + 1) + from); }; */ var createUUID= (function (uuidRegEx, uuidReplacer) { return function () { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(uuidRegEx, uuidReplacer).toUpperCase(); }; })(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c == "x" ? r : (r & 3 | 8); return v.toString(16); }); /* var createDialog = function (options) { return new DialogView(options); }; */ var busy = function (show, zIndex) { if (show) { BusyOverLay.open(zIndex); } else { BusyOverLay.close(); } }; /* var byte2Str = function (val) { var possibleTypes = ['bytes', 'KB', 'MB', 'GB'], canContinue = false, count = 0; var size = parseInt(val, 10) ? Math.floor(parseInt(val, 10)) : ''; if (size == '') return '0 bytes'; do { if (size > 1000) { size = Math.floor((size / 1024) * 100) / 100; count++; canContinue = true; } else { canContinue = false; } } while (canContinue); return size + ' ' + possibleTypes[count]; }; */ var string = { contains: function (str, needle) { if (needle === '') return true; if (str == null) return false; str = str.toLowerCase(); needle = needle.toLowerCase(); return String(str).indexOf(needle) !== -1; }, trim: function (str) { if (str == null) return ''; return str.replace(/^\s+|\s+$/g, ''); }, isNumber: function (input) { return (input - 0) == input && (input + '').replace(/^\s+|\s+$/g, "").length > 0; //return !isNaN(parseFloat(n)) && isFinite(n); } }; /****************************************/ /* Dialog */ /****************************************/ // Dialog view //require("Backbone"); /* var DialogView = Backbone.View.extend({ tagName: 'div', id: utils.createUUID(), attributes: { 'class': "dialog-box" }, view: null, //new Backbone.View({initialize:function(){}, render:function(){ $(this.el).html('hello');return this;}}), initialize: function (params) { var self = this; if (params && params.view) { self.view = params.view; self.view.parentView = self; self.onClose = params.onClose; } }, render: function () { var self = this; this.bodyoverflow = $('body').css('overflow-y'); $('body').css({ 'overflow-y': 'hidden' }); this.$el.hide(); $('body').append(this.el); var inside_view = self.view.render(); this.$el.html(inside_view.$el); //debugger setTimeout($.proxy(function () { // position dialog //$(self.el).outerWidth() // // var top = ($(window).height() - $(self.$el).outerHeight()) * 0.5; // var left = ($(window).width() - $(self.$el).outerWidth()) * 0.5; // $(self.el).css({ // position: 'absolute', // top: top + 'px', // left: left + 'px', // position: 'absolute', // 'z-index': 10005 // }); // inside_view.$el.css({ // position: 'relative' // }); // $('body').css({ 'overflow-y': this.bodyoverflow }); // }, this), 10); return this; }, open: function () { //$('BODY').addClass('blackout'); $('body').append('<div id="' + this.id + '_overlay" class="blackout fullwindow"></div>'); this.render(); this.$el.fadeIn(250); window.dialog = this; }, close: function () { //$('BODY').removeClass('blackout'); $('#' + this.id + '_overlay').remove(); var self = this; self.view.remove(); self.remove(); if (self.onClose) { self.onClose(); } } }); */ var BusyOverLay = (function () { var overlay_id = createUUID(); return { open: function (zIndex) { var zstr = 'z-index:20000'; if (zIndex) { zstr = 'z-index:' + zIndex; } $('body').append('<div style="' + zstr + '" id="' + overlay_id + '_overlay" class="blackout fullwindow"><div style="" class="vault-busy"><div class="vault-busy-loading"></div></div></div>'); }, close: function () { $('#' + overlay_id + '_overlay').remove(); } }; })();
define(function(undefined){ /** * Represents a key on the keyboard. An enum of common keys can be found at {@link thruster.input.Keys}. * @class * @memberof thruster.input * @param {String} key The W3C key value for this key. See {@link http://www.w3.org/TR/DOM-Level-3-Events-key/}. * @param {Number} keyCode The keyCode returned by a keydown event when this key is pressed. Where keyCodes differ between browsers, this should be set to the most common of them. See {@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode}. * @param {String} [name] A human-readable name for this key. For printable character keys, this should be the upper case version of the character. If omitted, the key value will be used. * @param {String[]} [nonStandardKeys] An array of non-standard key values implemented by browsers for this key. For example, "Escape" has the unofficial value "Esc" in some browsers. See {@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key}. */ var Key = function(key, keyCode, name, nonStandardKeys){ this.key = (typeof key == 'undefined' ? 'Unidentified' : key); this.keyCode = keyCode || 0; this.name = (typeof name == 'undefined' ? this.key : name); // Name could be a falsy value, so check for type. this.nonStandardKeys = nonStandardKeys || []; }; /** * Checks if the given key is the same as this one. * @param {thruster.input.Key} other The other key to check against. * @returns {Boolean} True if the keys match, false if not (or if at least one key was unidentified). */ Key.prototype.equals = function(other){ // First, check if information is available for both keys. if (this.isUnidentified() || other.isUnidentified()){ // No information available for at least one key, return early. return false; } // Check if either key has a key value. They're much more reliable than keyCodes. if ( this.key != 'Unidentified' && this.key !== undefined && other.key != 'Unidentified' && other.key !== undefined ){ // Check official values. if (this.key == other.key){ return true; } // Check non-standard values. if (this.nonStandardKeys.length || other.nonStandardKeys.length){ // Check this key's non-standard values against the other key. for (var i in this.nonStandardKeys){ if (other.key === this.nonStandardKeys[i]){ return true; } } // Check the other key's non-standard values against this key. for (var i in other.nonStandardKeys){ if (this.key === other.nonStandardKeys[i]){ return true; } } // Finally, check non-standard key values against each other. for (var i in this.nonStandardKeys){ for (var j in other.nonStandardKeys){ if (this.nonStandardKeys[i] === other.nonStandardKeys[j]){ return true; } } } } } else { // As a backup, check keyCodes. They may not be reliable, but there's not much alternative. if ( this.keyCode !== 0 && // No need to check if other keyCode is 0. If it is, they won't be equal. this.keyCode === other.keyCode ){ return true; } } // If we get here, no match was found. return false; }; /** * Checks if this key is unidentified (key value of "Unidentified" or undefined AND a keyCode of 0). * @returns {Boolean} True if this key is unidentified, false if not. */ Key.prototype.isUnidentified = function(){ if ( (this.key == 'Unidentified' || typeof this.key == 'undefined') && this.nonStandardKeys.length == 0 && this.keyCode === 0 ){ return true; } return false; }; /** * Constructs a Key instance from a keydown or keyup event object. * @static * @param e The event object passed to the keyup or keydown event handler. In older browsers that don't pass an object to event handlers, window.event should be passed in instead. * @returns {(thruster.input.Key|Boolean)} A Key instance, or boolean false if the key could not be determined. */ Key.fromEventObject = function(e){ var key = e.key || String.fromCharCode(e.charCode).toLowerCase() || undefined, keyCode = e.keyCode, name = key || 'Key ' + keyCode; var newKey = new Key(key, keyCode, name); if (newKey.isUnidentified()){ // Key is unknown return false; } else { return newKey; } }; return Key; });
/// <reference path="./global.d.ts" /> // // @ts-check /** * Determine the prize of the pizza given the pizza and optional extras * * @param {Pizza} pizza name of the pizza to be made * @param {Extra[]} extras list of extras * * @returns {number} the price of the pizza */ export function pizzaPrice(pizza, ...extras) { throw new Error('Please implement the pizzaPrice function'); } /** * Calculate the prize of the total order, given individual orders * * @param {PizzaOrder[]} pizzaOrders a list of pizza orders * @returns {number} the price of the total order */ export function orderPrice(pizzaOrders) { throw new Error('Please implement the orderPrice function'); }
/** @jsx jsx */ import { Editor } from 'slate' import { jsx } from '../../..' export const run = editor => { Editor.liftNodes(editor, { at: [0, 1] }) } export const input = ( <editor> <block> <block>one</block> <block>two</block> <block>three</block> </block> </editor> ) export const output = ( <editor> <block> <block>one</block> </block> <block>two</block> <block> <block>three</block> </block> </editor> )
/** * Provides a set of classes and methods for handling Neuroevolution and * genetic algorithms. * * @param {options} An object of options for Neuroevolution. */ var Neuroevolution = function(options){ var self = this; // reference to the top scope of this module // Declaration of module parameters (options) and default values self.options = { /** * Logistic activation function. * * @param {a} Input value. * @return Logistic function output. */ activation: function(a){ ap = (-a)/1; return (1/(1 + Math.exp(ap))) }, /** * Returns a random value between -1 and 1. * * @return Random value. */ randomClamped: function(){ return Math.random() * 2 - 1; }, // various factors and parameters (along with default values). network:[1, [1], 1], // Perceptron network structure (1 hidden // layer). population:50, // Population by generation. elitism:0.2, // Best networks kepts unchanged for the next // generation (rate). randomBehaviour:0.2, // New random networks for the next generation // (rate). mutationRate:0.1, // Mutation rate on the weights of synapses. mutationRange:0.5, // Interval of the mutation changes on the // synapse weight. historic:0, // Latest generations saved. lowHistoric:false, // Only save score (not the network). scoreSort:-1, // Sort order (-1 = desc, 1 = asc). nbChild:1 // Number of children by breeding. } /** * Override default options. * * @param {options} An object of Neuroevolution options. * @return void */ self.set = function(options){ for(var i in options){ if(this.options[i] != undefined){ // Only override if the passed in value // is actually defined. self.options[i] = options[i]; } } } // Overriding default options with the pass in options self.set(options); /*NEURON**********************************************************************/ /** * Artificial Neuron class * * @constructor */ var Neuron = function(){ this.value = 0; this.weights = []; } /** * Initialize number of neuron weights to random clamped values. * * @param {nb} Number of neuron weights (number of inputs). * @return void */ Neuron.prototype.populate = function(nb){ this.weights = []; for(var i = 0; i < nb; i++){ this.weights.push(self.options.randomClamped()); } } /*LAYER***********************************************************************/ /** * Neural Network Layer class. * * @constructor * @param {index} Index of this Layer in the Network. */ var Layer = function(index){ this.id = index || 0; this.neurons = []; } /** * Populate the Layer with a set of randomly weighted Neurons. * * Each Neuron be initialied with nbInputs inputs with a random clamped * value. * * @param {nbNeurons} Number of neurons. * @param {nbInputs} Number of inputs. * @return void */ Layer.prototype.populate = function(nbNeurons, nbInputs){ this.neurons = []; for(var i = 0; i < nbNeurons; i++){ var n = new Neuron(); n.populate(nbInputs); this.neurons.push(n); } } /*NEURAL NETWORK**************************************************************/ /** * Neural Network class * * Composed of Neuron Layers. * * @constructor */ var Network = function(){ this.layers = []; } /** * Generate the Network layers. * * @param {input} Number of Neurons in Input layer. * @param {hidden} Number of Neurons per Hidden layer. * @param {output} Number of Neurons in Output layer. * @return void */ Network.prototype.perceptronGeneration = function(input, hiddens, output){ var index = 0; var previousNeurons = 0; var layer = new Layer(index); layer.populate(input, previousNeurons); // Number of Inputs will be set to // 0 since it is an input layer. previousNeurons = input; // number of input is size of previous layer. this.layers.push(layer); index++; for(var i in hiddens){ // Repeat same process as first layer for each hidden layer. var layer = new Layer(index); layer.populate(hiddens[i], previousNeurons); previousNeurons = hiddens[i]; this.layers.push(layer); index++; } var layer = new Layer(index); layer.populate(output, previousNeurons); // Number of input is equal to // the size of the last hidden // layer. this.layers.push(layer); } /** * Create a copy of the Network (neurons and weights). * * Returns number of neurons per layer and a flat array of all weights. * * @return Network data. */ Network.prototype.getSave = function(){ var datas = { neurons:[], // Number of Neurons per layer. weights:[] // Weights of each Neuron's inputs. }; for(var i in this.layers){ datas.neurons.push(this.layers[i].neurons.length); for(var j in this.layers[i].neurons){ for(var k in this.layers[i].neurons[j].weights){ // push all input weights of each Neuron of each Layer into a flat // array. datas.weights.push(this.layers[i].neurons[j].weights[k]); } } } return datas; } /** * Apply network data (neurons and weights). * * @param {save} Copy of network data (neurons and weights). * @return void */ Network.prototype.setSave = function(save){ var previousNeurons = 0; var index = 0; var indexWeights = 0; this.layers = []; for(var i in save.neurons){ // Create and populate layers. var layer = new Layer(index); layer.populate(save.neurons[i], previousNeurons); for(var j in layer.neurons){ for(var k in layer.neurons[j].weights){ // Apply neurons weights to each Neuron. layer.neurons[j].weights[k] = save.weights[indexWeights]; indexWeights++; // Increment index of flat array. } } previousNeurons = save.neurons[i]; index++; this.layers.push(layer); } } /** * Compute the output of an input. * * @param {inputs} Set of inputs. * @return Network output. */ Network.prototype.compute = function(inputs){ // Set the value of each Neuron in the input layer. for(var i in inputs){ if(this.layers[0] && this.layers[0].neurons[i]){ this.layers[0].neurons[i].value = inputs[i]; } } var prevLayer = this.layers[0]; // Previous layer is input layer. for(var i = 1; i < this.layers.length; i++){ for(var j in this.layers[i].neurons){ // For each Neuron in each layer. var sum = 0; for(var k in prevLayer.neurons){ // Every Neuron in the previous layer is an input to each Neuron in // the next layer. sum += prevLayer.neurons[k].value * this.layers[i].neurons[j].weights[k]; } // Compute the activation of the Neuron. this.layers[i].neurons[j].value = self.options.activation(sum); } prevLayer = this.layers[i]; } // All outputs of the Network. var out = []; var lastLayer = this.layers[this.layers.length - 1]; for(var i in lastLayer.neurons){ out.push(lastLayer.neurons[i].value); } return out; } /*GENOME**********************************************************************/ /** * Genome class. * * Composed of a score and a Neural Network. * * @constructor * * @param {score} * @param {network} */ var Genome = function(score, network){ this.score = score || 0; this.network = network || null; } /*GENERATION******************************************************************/ /** * Generation class. * * Composed of a set of Genomes. * * @constructor */ var Generation = function(){ this.genomes = []; } /** * Add a genome to the generation. * * @param {genome} Genome to add. * @return void. */ Generation.prototype.addGenome = function(genome){ // Locate position to insert Genome into. // The gnomes should remain sorted. for(var i = 0; i < this.genomes.length; i++){ // Sort in descending order. if(self.options.scoreSort < 0){ if(genome.score > this.genomes[i].score){ break; } // Sort in ascending order. }else{ if(genome.score < this.genomes[i].score){ break; } } } // Insert genome into correct position. this.genomes.splice(i, 0, genome); } /** * Breed to genomes to produce offspring(s). * * @param {g1} Genome 1. * @param {g2} Genome 2. * @param {nbChilds} Number of offspring (children). */ Generation.prototype.breed = function(g1, g2, nbChilds){ var datas = []; for(var nb = 0; nb < nbChilds; nb++){ // Deep clone of genome 1. var data = JSON.parse(JSON.stringify(g1)); for(var i in g2.network.weights){ // Genetic crossover // 0.5 is the crossover factor. // FIXME Really should be a predefined constant. if(Math.random() <= 0.5){ data.network.weights[i] = g2.network.weights[i]; } } // Perform mutation on some weights. for(var i in data.network.weights){ if(Math.random() <= self.options.mutationRate){ data.network.weights[i] += Math.random() * self.options.mutationRange * 2 - self.options.mutationRange; } } datas.push(data); } return datas; } /** * Generate the next generation. * * @return Next generation data array. */ Generation.prototype.generateNextGeneration = function(){ var nexts = []; for(var i = 0; i < Math.round(self.options.elitism * self.options.population); i++){ if(nexts.length < self.options.population){ // Push a deep copy of ith Genome's Nethwork. nexts.push(JSON.parse(JSON.stringify(this.genomes[i].network))); } } for(var i = 0; i < Math.round(self.options.randomBehaviour * self.options.population); i++){ var n = JSON.parse(JSON.stringify(this.genomes[0].network)); for(var k in n.weights){ n.weights[k] = self.options.randomClamped(); } if(nexts.length < self.options.population){ nexts.push(n); } } var max = 0; while(true){ for(var i = 0; i < max; i++){ // Create the children and push them to the nexts array. var childs = this.breed(this.genomes[i], this.genomes[max], (self.options.nbChild > 0 ? self.options.nbChild : 1) ); for(var c in childs){ nexts.push(childs[c].network); if(nexts.length >= self.options.population){ // Return once number of children is equal to the // population by generatino value. return nexts; } } } max++; if(max >= this.genomes.length - 1){ max = 0; } } } /*GENERATIONS*****************************************************************/ /** * Generations class. * * Hold's previous Generations and current Generation. * * @constructor */ var Generations = function(){ this.generations = []; var currentGeneration = new Generation(); } /** * Create the first generation. * * @param {input} Input layer. * @param {input} Hidden layer(s). * @param {output} Output layer. * @return First Generation. */ Generations.prototype.firstGeneration = function(input, hiddens, output){ // FIXME input, hiddens, output unused. var out = []; for(var i = 0; i < self.options.population; i++){ // Generate the Network and save it. var nn = new Network(); nn.perceptronGeneration(self.options.network[0], self.options.network[1], self.options.network[2]); out.push(nn.getSave()); } this.generations.push(new Generation()); return out; } /** * Create the next Generation. * * @return Next Generation. */ Generations.prototype.nextGeneration = function(){ if(this.generations.length == 0){ // Need to create first generation. return false; } var gen = this.generations[this.generations.length - 1] .generateNextGeneration(); this.generations.push(new Generation()); return gen; } /** * Add a genome to the Generations. * * @param {genome} * @return False if no Generations to add to. */ Generations.prototype.addGenome = function(genome){ // Can't add to a Generation if there are no Generations. if(this.generations.length == 0) return false; // FIXME addGenome returns void. return this.generations[this.generations.length - 1].addGenome(genome); } /*SELF************************************************************************/ self.generations = new Generations(); /** * Reset and create a new Generations object. * * @return void. */ self.restart = function(){ self.generations = new Generations(); } /** * Create the next generation. * * @return Neural Network array for next Generation. */ self.nextGeneration = function(){ var networks = []; if(self.generations.generations.length == 0){ // If no Generations, create first. networks = self.generations.firstGeneration(); }else{ // Otherwise, create next one. networks = self.generations.nextGeneration(); } // Create Networks from the current Generation. var nns = []; for(var i in networks){ var nn = new Network(); nn.setSave(networks[i]); nns.push(nn); } if(self.options.lowHistoric){ // Remove old Networks. if(self.generations.generations.length >= 2){ var genomes = self.generations .generations[self.generations.generations.length - 2] .genomes; for(var i in genomes){ delete genomes[i].network; } } } if(self.options.historic != -1){ // Remove older generations. if(self.generations.generations.length > self.options.historic + 1){ self.generations.generations.splice(0, self.generations.generations.length - (self.options.historic + 1)); } } return nns; } /** * Adds a new Genome with specified Neural Network and score. * * @param {network} Neural Network. * @param {score} Score value. * @return void. */ self.networkScore = function(network, score){ self.generations.addGenome(new Genome(score, network.getSave())); } }
Dagaz.Controller.persistense = "none"; Dagaz.Model.NO_SOUND = true; ZRF = { JUMP: 0, IF: 1, FORK: 2, FUNCTION: 3, IN_ZONE: 4, FLAG: 5, SET_FLAG: 6, POS_FLAG: 7, SET_POS_FLAG: 8, ATTR: 9, SET_ATTR: 10, PROMOTE: 11, MODE: 12, ON_BOARD_DIR: 13, ON_BOARD_POS: 14, PARAM: 15, LITERAL: 16, VERIFY: 20 }; Dagaz.Model.BuildDesign = function(design) { design.checkVersion("z2j", "2"); design.checkVersion("animate-drops", "false"); design.checkVersion("animate-captures", "false"); design.checkVersion("show-blink", "false"); design.checkVersion("animate-redo", "false"); design.addDirection("se"); design.addDirection("sw"); design.addDirection("ne"); design.addDirection("nw"); design.addPlayer("You", [0, 1, 2, 3]); design.addPlayer("Off", [0, 1, 2, 3]); design.addTurn(1); design.addPosition("a7", [8, 7, 0, 0]); design.addPosition("b7", [0, 1, 2, 3]); design.addPosition("c7", [0, 1, 2, 3]); design.addPosition("d7", [0, 1, 2, 3]); design.addPosition("e7", [0, 1, 2, 3]); design.addPosition("f7", [0, 1, 2, 3]); design.addPosition("g7", [0, 1, 2, 3]); design.addPosition("a6", [8, 7, -7, 0]); design.addPosition("b6", [8, 7, 0, -8]); design.addPosition("c6", [0, 1, 2, 3]); design.addPosition("d6", [0, 1, 2, 3]); design.addPosition("e6", [0, 1, 2, 3]); design.addPosition("f6", [0, 1, 2, 3]); design.addPosition("g6", [0, 1, 2, 3]); design.addPosition("a5", [8, 7, -7, 0]); design.addPosition("b5", [8, 7, -7, -8]); design.addPosition("c5", [8, 7, 0, -8]); design.addPosition("d5", [0, 1, 2, 3]); design.addPosition("e5", [0, 1, 2, 3]); design.addPosition("f5", [0, 1, 2, 3]); design.addPosition("g5", [0, 1, 2, 3]); design.addPosition("a4", [8, 7, -7, 0]); design.addPosition("b4", [8, 7, -7, -8]); design.addPosition("c4", [8, 7, -7, -8]); design.addPosition("d4", [8, 7, 0, -8]); design.addPosition("e4", [0, 1, 2, 3]); design.addPosition("f4", [0, 1, 2, 3]); design.addPosition("g4", [0, 1, 2, 3]); design.addPosition("a3", [8, 7, -7, 0]); design.addPosition("b3", [8, 7, -7, -8]); design.addPosition("c3", [8, 7, -7, -8]); design.addPosition("d3", [8, 7, -7, -8]); design.addPosition("e3", [8, 7, 0, -8]); design.addPosition("f3", [0, 1, 2, 3]); design.addPosition("g3", [0, 1, 2, 3]); design.addPosition("a2", [8, 7, -7, 0]); design.addPosition("b2", [8, 7, -7, -8]); design.addPosition("c2", [8, 7, -7, -8]); design.addPosition("d2", [8, 7, -7, -8]); design.addPosition("e2", [8, 7, -7, -8]); design.addPosition("f2", [8, 7, 0, -8]); design.addPosition("g2", [0, 1, 2, 3]); design.addPosition("a1", [0, 0, -7, 0]); design.addPosition("b1", [0, 0, -7, -8]); design.addPosition("c1", [0, 0, -7, -8]); design.addPosition("d1", [0, 0, -7, -8]); design.addPosition("e1", [0, 0, -7, -8]); design.addPosition("f1", [0, 0, -7, -8]); design.addPosition("g1", [0, 0, 0, -8]); design.addZone("board-zone", 1, [42, 43, 44, 45, 46, 47, 48, 35, 36, 37, 38, 39, 40, 28, 29, 30, 31, 32, 21, 22, 23, 24, 14, 15, 16, 7, 8, 0]); design.addZone("inner-zone", 1, [35, 36, 37, 38, 39, 40, 28, 29, 30, 31, 32, 21, 22, 23, 24, 14, 15, 16, 7, 8]); design.addCommand(0, ZRF.FUNCTION, 24); // from design.addCommand(0, ZRF.FUNCTION, 26); // capture design.addCommand(0, ZRF.FUNCTION, 25); // to design.addCommand(0, ZRF.FUNCTION, 28); // end design.addPiece("P00", 0, 1); design.addMove(0, 0, [], 0); design.addPiece("P01", 1, 2); design.addMove(1, 0, [], 0); design.addPiece("P02", 2, 3); design.addMove(2, 0, [], 0); design.addPiece("P03", 3, 4); design.addMove(3, 0, [], 0); design.addPiece("P04", 4, 5); design.addMove(4, 0, [], 0); design.addPiece("P05", 5, 6); design.addMove(5, 0, [], 0); design.addPiece("P06", 6, 7); design.addMove(6, 0, [], 0); design.addPiece("P11", 7, 3); design.addMove(7, 0, [], 0); design.addPiece("P12", 8, 4); design.addMove(8, 0, [], 0); design.addPiece("P13", 9, 5); design.addMove(9, 0, [], 0); design.addPiece("P14", 10, 6); design.addMove(10, 0, [], 0); design.addPiece("P15", 11, 7); design.addMove(11, 0, [], 0); design.addPiece("P16", 12, 8); design.addMove(12, 0, [], 0); design.addPiece("P22", 13, 5); design.addMove(13, 0, [], 0); design.addPiece("P23", 14, 6); design.addMove(14, 0, [], 0); design.addPiece("P24", 15, 7); design.addMove(15, 0, [], 0); design.addPiece("P25", 16, 8); design.addMove(16, 0, [], 0); design.addPiece("P26", 17, 9); design.addMove(17, 0, [], 0); design.addPiece("P33", 18, 7); design.addMove(18, 0, [], 0); design.addPiece("P34", 19, 8); design.addMove(19, 0, [], 0); design.addPiece("P35", 20, 9); design.addMove(20, 0, [], 0); design.addPiece("P36", 21, 10); design.addMove(21, 0, [], 0); design.addPiece("P44", 22, 9); design.addMove(22, 0, [], 0); design.addPiece("P45", 23, 10); design.addMove(23, 0, [], 0); design.addPiece("P46", 24, 11); design.addMove(24, 0, [], 0); design.addPiece("P55", 25, 11); design.addMove(25, 0, [], 0); design.addPiece("P56", 26, 12); design.addMove(26, 0, [], 0); design.addPiece("P66", 27, 13); design.addMove(27, 0, [], 0); } Dagaz.View.configure = function(view) { view.defPiece("YouP00", "You P00"); view.defPiece("OffP00", "Off P00"); view.defPiece("YouP01", "You P01"); view.defPiece("OffP01", "Off P01"); view.defPiece("YouP02", "You P02"); view.defPiece("OffP02", "Off P02"); view.defPiece("YouP03", "You P03"); view.defPiece("OffP03", "Off P03"); view.defPiece("YouP04", "You P04"); view.defPiece("OffP04", "Off P04"); view.defPiece("YouP05", "You P05"); view.defPiece("OffP05", "Off P05"); view.defPiece("YouP06", "You P06"); view.defPiece("OffP06", "Off P06"); view.defPiece("YouP11", "You P11"); view.defPiece("OffP11", "Off P11"); view.defPiece("YouP12", "You P12"); view.defPiece("OffP12", "Off P12"); view.defPiece("YouP13", "You P13"); view.defPiece("OffP13", "Off P13"); view.defPiece("YouP14", "You P14"); view.defPiece("OffP14", "Off P14"); view.defPiece("YouP15", "You P15"); view.defPiece("OffP15", "Off P15"); view.defPiece("YouP16", "You P16"); view.defPiece("OffP16", "Off P16"); view.defPiece("YouP22", "You P22"); view.defPiece("OffP22", "Off P22"); view.defPiece("YouP23", "You P23"); view.defPiece("OffP23", "Off P23"); view.defPiece("YouP24", "You P24"); view.defPiece("OffP24", "Off P24"); view.defPiece("YouP25", "You P25"); view.defPiece("OffP25", "Off P25"); view.defPiece("YouP26", "You P26"); view.defPiece("OffP26", "Off P26"); view.defPiece("YouP33", "You P33"); view.defPiece("OffP33", "Off P33"); view.defPiece("YouP34", "You P34"); view.defPiece("OffP34", "Off P34"); view.defPiece("YouP35", "You P35"); view.defPiece("OffP35", "Off P35"); view.defPiece("YouP36", "You P36"); view.defPiece("OffP36", "Off P36"); view.defPiece("YouP44", "You P44"); view.defPiece("OffP44", "Off P44"); view.defPiece("YouP45", "You P45"); view.defPiece("OffP45", "Off P45"); view.defPiece("YouP46", "You P46"); view.defPiece("OffP46", "Off P46"); view.defPiece("YouP55", "You P55"); view.defPiece("OffP55", "Off P55"); view.defPiece("YouP56", "You P56"); view.defPiece("OffP56", "Off P56"); view.defPiece("YouP66", "You P66"); view.defPiece("OffP66", "Off P66"); view.defPosition("a7", 156, 0, 52, 103); view.defPosition("b7", 208, 0, 52, 103); view.defPosition("c7", 260, 0, 52, 103); view.defPosition("d7", 312, 0, 52, 103); view.defPosition("e7", 364, 0, 52, 103); view.defPosition("f7", 416, 0, 52, 103); view.defPosition("g7", 468, 0, 52, 103); view.defPosition("a6", 130, 103, 52, 103); view.defPosition("b6", 182, 103, 52, 103); view.defPosition("c6", 234, 103, 52, 103); view.defPosition("d6", 286, 103, 52, 103); view.defPosition("e6", 338, 103, 52, 103); view.defPosition("f6", 390, 103, 52, 103); view.defPosition("g6", 442, 103, 52, 103); view.defPosition("a5", 104, 206, 52, 103); view.defPosition("b5", 156, 206, 52, 103); view.defPosition("c5", 208, 206, 52, 103); view.defPosition("d5", 260, 206, 52, 103); view.defPosition("e5", 312, 206, 52, 103); view.defPosition("f5", 364, 206, 52, 103); view.defPosition("g5", 416, 206, 52, 103); view.defPosition("a4", 78, 309, 52, 103); view.defPosition("b4", 130, 309, 52, 103); view.defPosition("c4", 182, 309, 52, 103); view.defPosition("d4", 234, 309, 52, 103); view.defPosition("e4", 286, 309, 52, 103); view.defPosition("f4", 338, 309, 52, 103); view.defPosition("g4", 390, 309, 52, 103); view.defPosition("a3", 52, 412, 52, 103); view.defPosition("b3", 104, 412, 52, 103); view.defPosition("c3", 156, 412, 52, 103); view.defPosition("d3", 208, 412, 52, 103); view.defPosition("e3", 260, 412, 52, 103); view.defPosition("f3", 312, 412, 52, 103); view.defPosition("g3", 364, 412, 52, 103); view.defPosition("a2", 26, 515, 52, 103); view.defPosition("b2", 78, 515, 52, 103); view.defPosition("c2", 130, 515, 52, 103); view.defPosition("d2", 182, 515, 52, 103); view.defPosition("e2", 234, 515, 52, 103); view.defPosition("f2", 286, 515, 52, 103); view.defPosition("g2", 338, 515, 52, 103); view.defPosition("a1", 0, 618, 52, 103); view.defPosition("b1", 52, 618, 52, 103); view.defPosition("c1", 104, 618, 52, 103); view.defPosition("d1", 156, 618, 52, 103); view.defPosition("e1", 208, 618, 52, 103); view.defPosition("f1", 260, 618, 52, 103); view.defPosition("g1", 312, 618, 52, 103); }
var VNode = require('../vnode/vnode.js'); var VText = require('../vnode/vtext.js'); var isVNode = require('../vnode/is-vnode'); var isVText = require('../vnode/is-vtext'); var isWidget = require('../vnode/is-widget'); var isHook = require('../vnode/is-vhook'); var isVThunk = require('../vnode/is-thunk'); var parseTag = require('./parse-tag.js'); var softSetHook = require('./hooks/soft-set-hook.js'); var evHook = require('./hooks/ev-hook.js'); module.exports = h; function h(tagName, properties, children) { var childNodes = []; var tag, props, key, namespace; if (!children && isChildren(properties)) { children = properties; props = {}; } props = props || properties || {}; tag = parseTag(tagName, props); // support keys if (props.hasOwnProperty('key')) { key = props.key; props.key = undefined; } // support namespace if (props.hasOwnProperty('namespace')) { namespace = props.namespace; props.namespace = undefined; } // fix cursor bug if (tag === 'INPUT' && !namespace && props.hasOwnProperty('value') && props.value !== undefined && !isHook(props.value) ) { props.value = softSetHook(props.value); } transformProperties(props); if (children !== undefined && children !== null) { addChild(children, childNodes, tag, props); } return new VNode(tag, props, childNodes, key, namespace); } function addChild(c, childNodes, tag, props) { if (typeof c === 'string') { childNodes.push(new VText(c)); } else if (isChild(c)) { childNodes.push(c); } else if (Array.isArray(c)) { for (var i = 0; i < c.length; i++) { addChild(c[i], childNodes, tag, props); } } else if (c === null || c === undefined) { return; } else { throw UnexpectedVirtualElement({ foreignObject: c, parentVnode: { tagName: tag, properties: props } }); } } function transformProperties(props) { for (var propName in props) { if (props.hasOwnProperty(propName)) { var value = props[propName]; if (isHook(value)) { continue; } if (propName.substr(0, 3) === 'ev-') { // add ev-foo support props[propName] = evHook(value); } } } } function isChild(x) { return isVNode(x) || isVText(x) || isWidget(x) || isVThunk(x); } function isChildren(x) { return typeof x === 'string' || Array.isArray(x) || isChild(x); } function UnexpectedVirtualElement(data) { var err = new Error(); err.type = 'virtual-hyperscript.unexpected.virtual-element'; err.message = `Unexpected virtual child passed to h(). Expected a VNode / Vthunk / VWidget / string but: got: ${errorString(data.foreignObject)}. The parent vnode is: ${errorString(data.parentVnode)} Suggested fix: change your h(..., [ ... ]) callsite.`; err.foreignObject = data.foreignObject; err.parentVnode = data.parentVnode; return err; } function errorString(obj) { try { return JSON.stringify(obj, null, ' '); } catch (e) { return String(obj); } }
/* ----------------------------------------------------------------------------- Kebab Project 1.5.x (Kebab Reloaded) http://kebab-project.com Copyright (c) 2010-2011 lab2023 - internet technologies TURKEY Inc. http://www.lab2023.com * LICENSE * * This source file is subject to the Dual Licensing Model that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://www.kebab-project.com/cms/licensing * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to info@lab2023.com so we can send you a copy immediately. ----------------------------------------------------------------------------- */ /** * Kebab.OS * * @namespace Kebab.i18n * @author Tayfun Öziş ERİKAN <tayfun.ozis.erikan@lab2023.com> * @author Yunus ÖZCAN <yunus.ozcan@lab2023.com> * @copyright Copyright (c) 2010-2011 lab2023 - internet technologies TURKEY Inc. (http://www.lab2023.com) * @license http://www.kebab-project.com/cms/licensing * @version 1.5.0 */ KebabOS.applications.applicationManager.application.languages.tr = { 'Application title':'Uygulama Başlığı', 'Application description':'Uygulama Açıklaması', 'Active ?':'Aktif ?' };
// // SmoothScroll for websites v1.4.0 (Balazs Galambosi) // http://www.smoothscroll.net/ // // Licensed under the terms of the MIT license. // // You may use it in your theme if you credit me. // It is also free to use on any individual website. // // Exception: // The only restriction is to not publish any // extension for browsers or native application // without getting a written permission first. // (function () { // Scroll Variables (tweakable) var defaultOptions = { // Scrolling Core frameRate : 150, // [Hz] animationTime : 400, // [ms] stepSize : 80, // [px] // Pulse (less tweakable) // ratio of "tail" to "acceleration" pulseAlgorithm : true, pulseScale : 4, pulseNormalize : 1, // Acceleration accelerationDelta : 50, // 50 accelerationMax : 3, // 3 // Keyboard Settings keyboardSupport : true, // option arrowScroll : 50, // [px] // Other touchpadSupport : false, // ignore touchpad by default fixedBackground : true, excluded : '' }; var options = defaultOptions; // Other Variables var isExcluded = false; var isFrame = false; var direction = { x: 0, y: 0 }; var initDone = false; var root = document.documentElement; var activeElement; var observer; var refreshSize; var deltaBuffer = []; var isMac = /^Mac/.test(navigator.platform); var key = { left: 37, up: 38, right: 39, down: 40, spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36 }; /*********************************************** * INITIALIZE ***********************************************/ /** * Tests if smooth scrolling is allowed. Shuts down everything if not. */ function initTest() { if (options.keyboardSupport) { addEvent('keydown', keydown); } } /** * Sets up scrolls array, determines if frames are involved. */ function init() { if (initDone || !document.body) return; initDone = true; var body = document.body; var html = document.documentElement; var windowHeight = window.innerHeight; var scrollHeight = body.scrollHeight; // check compat mode for root element root = (document.compatMode.indexOf('CSS') >= 0) ? html : body; activeElement = body; initTest(); // Checks if this script is running in a frame if (top != self) { isFrame = true; } /** * Please duplicate this radar for a Safari fix! * rdar://22376037 * https://openradar.appspot.com/radar?id=4965070979203072 * * Only applies to Safari now, Chrome fixed it in v45: * This fixes a bug where the areas left and right to * the content does not trigger the onmousewheel event * on some pages. e.g.: html, body { height: 100% } */ else if (scrollHeight > windowHeight && (body.offsetHeight <= windowHeight || html.offsetHeight <= windowHeight)) { var fullPageElem = document.createElement('div'); fullPageElem.style.cssText = 'position:absolute; z-index:-10000; ' + 'top:0; left:0; right:0; height:' + root.scrollHeight + 'px'; document.body.appendChild(fullPageElem); // DOM changed (throttled) to fix height var pendingRefresh; refreshSize = function () { if (pendingRefresh) return; // could also be: clearTimeout(pendingRefresh); pendingRefresh = setTimeout(function () { if (isExcluded) return; // could be running after cleanup fullPageElem.style.height = '0'; fullPageElem.style.height = root.scrollHeight + 'px'; pendingRefresh = null; }, 500); // act rarely to stay fast }; setTimeout(refreshSize, 10); addEvent('resize', refreshSize); // TODO: attributeFilter? var config = { attributes: true, childList: true, characterData: false // subtree: true }; observer = new MutationObserver(refreshSize); observer.observe(body, config); if (root.offsetHeight <= windowHeight) { var clearfix = document.createElement('div'); clearfix.style.clear = 'both'; body.appendChild(clearfix); } } // disable fixed background if (!options.fixedBackground && !isExcluded) { body.style.backgroundAttachment = 'scroll'; html.style.backgroundAttachment = 'scroll'; } } /** * Removes event listeners and other traces left on the page. */ function cleanup() { observer && observer.disconnect(); removeEvent(wheelEvent, wheel); removeEvent('mousedown', mousedown); removeEvent('keydown', keydown); removeEvent('resize', refreshSize); removeEvent('load', init); } /************************************************ * SCROLLING ************************************************/ var que = []; var pending = false; var lastScroll = Date.now(); /** * Pushes scroll actions to the scrolling queue. */ function scrollArray(elem, left, top) { directionCheck(left, top); if (options.accelerationMax != 1) { var now = Date.now(); var elapsed = now - lastScroll; if (elapsed < options.accelerationDelta) { var factor = (1 + (50 / elapsed)) / 2; if (factor > 1) { factor = Math.min(factor, options.accelerationMax); left *= factor; top *= factor; } } lastScroll = Date.now(); } // push a scroll command que.push({ x: left, y: top, lastX: (left < 0) ? 0.99 : -0.99, lastY: (top < 0) ? 0.99 : -0.99, start: Date.now() }); // don't act if there's a pending queue if (pending) { return; } var scrollWindow = (elem === document.body); var step = function (time) { var now = Date.now(); var scrollX = 0; var scrollY = 0; for (var i = 0; i < que.length; i++) { var item = que[i]; var elapsed = now - item.start; var finished = (elapsed >= options.animationTime); // scroll position: [0, 1] var position = (finished) ? 1 : elapsed / options.animationTime; // easing [optional] if (options.pulseAlgorithm) { position = pulse(position); } // only need the difference var x = (item.x * position - item.lastX) >> 0; var y = (item.y * position - item.lastY) >> 0; // add this to the total scrolling scrollX += x; scrollY += y; // update last values item.lastX += x; item.lastY += y; // delete and step back if it's over if (finished) { que.splice(i, 1); i--; } } // scroll left and top if (scrollWindow) { window.scrollBy(scrollX, scrollY); } else { if (scrollX) elem.scrollLeft += scrollX; if (scrollY) elem.scrollTop += scrollY; } // clean up if there's nothing left to do if (!left && !top) { que = []; } if (que.length) { requestFrame(step, elem, (1000 / options.frameRate + 1)); } else { pending = false; } }; // start a new queue of actions requestFrame(step, elem, 0); pending = true; } /*********************************************** * EVENTS ***********************************************/ /** * Mouse wheel handler. * @param {Object} event */ function wheel(event) { if (!initDone) { init(); } var target = event.target; var overflowing = overflowingAncestor(target); // use default if there's no overflowing // element or default action is prevented // or it's a zooming event with CTRL if (!overflowing || event.defaultPrevented || event.ctrlKey) { return true; } // leave embedded content alone (flash & pdf) if (isNodeName(activeElement, 'embed') || (isNodeName(target, 'embed') && /\.pdf/i.test(target.src)) || isNodeName(activeElement, 'object')) { return true; } var deltaX = -event.wheelDeltaX || event.deltaX || 0; var deltaY = -event.wheelDeltaY || event.deltaY || 0; if (isMac) { if (event.wheelDeltaX && isDivisible(event.wheelDeltaX, 120)) { deltaX = -120 * (event.wheelDeltaX / Math.abs(event.wheelDeltaX)); } if (event.wheelDeltaY && isDivisible(event.wheelDeltaY, 120)) { deltaY = -120 * (event.wheelDeltaY / Math.abs(event.wheelDeltaY)); } } // use wheelDelta if deltaX/Y is not available if (!deltaX && !deltaY) { deltaY = -event.wheelDelta || 0; } // line based scrolling (Firefox mostly) if (event.deltaMode === 1) { deltaX *= 40; deltaY *= 40; } // check if it's a touchpad scroll that should be ignored if (!options.touchpadSupport && isTouchpad(deltaY)) { return true; } // scale by step size // delta is 120 most of the time // synaptics seems to send 1 sometimes if (Math.abs(deltaX) > 1.2) { deltaX *= options.stepSize / 120; } if (Math.abs(deltaY) > 1.2) { deltaY *= options.stepSize / 120; } scrollArray(overflowing, deltaX, deltaY); event.preventDefault(); scheduleClearCache(); } /** * Keydown event handler. * @param {Object} event */ function keydown(event) { var target = event.target; var modifier = event.ctrlKey || event.altKey || event.metaKey || (event.shiftKey && event.keyCode !== key.spacebar); // our own tracked active element could've been removed from the DOM if (!document.contains(activeElement)) { activeElement = document.activeElement; } // do nothing if user is editing text // or using a modifier key (except shift) // or in a dropdown // or inside interactive elements var inputNodeNames = /^(textarea|select|embed|object)$/i; var buttonTypes = /^(button|submit|radio|checkbox|file|color|image)$/i; if ( inputNodeNames.test(target.nodeName) || isNodeName(target, 'input') && !buttonTypes.test(target.type) || isNodeName(activeElement, 'video') || isInsideYoutubeVideo(event) || target.isContentEditable || event.defaultPrevented || modifier ) { return true; } // spacebar should trigger button press if ((isNodeName(target, 'button') || isNodeName(target, 'input') && buttonTypes.test(target.type)) && event.keyCode === key.spacebar) { return true; } var shift, x = 0, y = 0; var elem = overflowingAncestor(activeElement); var clientHeight = elem.clientHeight; if (elem == document.body) { clientHeight = window.innerHeight; } switch (event.keyCode) { case key.up: y = -options.arrowScroll; break; case key.down: y = options.arrowScroll; break; case key.spacebar: // (+ shift) shift = event.shiftKey ? 1 : -1; y = -shift * clientHeight * 0.9; break; case key.pageup: y = -clientHeight * 0.9; break; case key.pagedown: y = clientHeight * 0.9; break; case key.home: y = -elem.scrollTop; break; case key.end: var damt = elem.scrollHeight - elem.scrollTop - clientHeight; y = (damt > 0) ? damt+10 : 0; break; case key.left: x = -options.arrowScroll; break; case key.right: x = options.arrowScroll; break; default: return true; // a key we don't care about } scrollArray(elem, x, y); event.preventDefault(); scheduleClearCache(); } /** * Mousedown event only for updating activeElement */ function mousedown(event) { activeElement = event.target; } /*********************************************** * OVERFLOW ***********************************************/ var uniqueID = (function () { var i = 0; return function (el) { return el.uniqueID || (el.uniqueID = i++); }; })(); var cache = {}; // cleared out after a scrolling session var clearCacheTimer; //setInterval(function () { cache = {}; }, 10 * 1000); function scheduleClearCache() { clearTimeout(clearCacheTimer); clearCacheTimer = setInterval(function () { cache = {}; }, 1*1000); } function setCache(elems, overflowing) { for (var i = elems.length; i--;) cache[uniqueID(elems[i])] = overflowing; return overflowing; } // (body) (root) // | hidden | visible | scroll | auto | // hidden | no | no | YES | YES | // visible | no | YES | YES | YES | // scroll | no | YES | YES | YES | // auto | no | YES | YES | YES | function overflowingAncestor(el) { var elems = []; var body = document.body; var rootScrollHeight = root.scrollHeight; do { var cached = cache[uniqueID(el)]; if (cached) { return setCache(elems, cached); } elems.push(el); if (rootScrollHeight === el.scrollHeight) { var topOverflowsNotHidden = overflowNotHidden(root) && overflowNotHidden(body); var isOverflowCSS = topOverflowsNotHidden || overflowAutoOrScroll(root); if (isFrame && isContentOverflowing(root) || !isFrame && isOverflowCSS) { return setCache(elems, getScrollRoot()); } } else if (isContentOverflowing(el) && overflowAutoOrScroll(el)) { return setCache(elems, el); } } while (el = el.parentElement); } function isContentOverflowing(el) { return (el.clientHeight + 10 < el.scrollHeight); } // typically for <body> and <html> function overflowNotHidden(el) { var overflow = getComputedStyle(el, '').getPropertyValue('overflow-y'); return (overflow !== 'hidden'); } // for all other elements function overflowAutoOrScroll(el) { var overflow = getComputedStyle(el, '').getPropertyValue('overflow-y'); return (overflow === 'scroll' || overflow === 'auto'); } /*********************************************** * HELPERS ***********************************************/ function addEvent(type, fn) { window.addEventListener(type, fn, false); } function removeEvent(type, fn) { window.removeEventListener(type, fn, false); } function isNodeName(el, tag) { return (el.nodeName||'').toLowerCase() === tag.toLowerCase(); } function directionCheck(x, y) { x = (x > 0) ? 1 : -1; y = (y > 0) ? 1 : -1; if (direction.x !== x || direction.y !== y) { direction.x = x; direction.y = y; que = []; lastScroll = 0; } } var deltaBufferTimer; if (window.localStorage && localStorage.SS_deltaBuffer) { deltaBuffer = localStorage.SS_deltaBuffer.split(','); } function isTouchpad(deltaY) { if (!deltaY) return; if (!deltaBuffer.length) { deltaBuffer = [deltaY, deltaY, deltaY]; } deltaY = Math.abs(deltaY) deltaBuffer.push(deltaY); deltaBuffer.shift(); clearTimeout(deltaBufferTimer); deltaBufferTimer = setTimeout(function () { if (window.localStorage) { localStorage.SS_deltaBuffer = deltaBuffer.join(','); } }, 1000); return !allDeltasDivisableBy(120) && !allDeltasDivisableBy(100); } function isDivisible(n, divisor) { return (Math.floor(n / divisor) == n / divisor); } function allDeltasDivisableBy(divisor) { return (isDivisible(deltaBuffer[0], divisor) && isDivisible(deltaBuffer[1], divisor) && isDivisible(deltaBuffer[2], divisor)); } function isInsideYoutubeVideo(event) { var elem = event.target; var isControl = false; if (document.URL.indexOf ('www.youtube.com/watch') != -1) { do { isControl = (elem.classList && elem.classList.contains('html5-video-controls')); if (isControl) break; } while (elem = elem.parentNode); } return isControl; } var requestFrame = (function () { return (window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (callback, element, delay) { window.setTimeout(callback, delay || (1000/60)); }); })(); var MutationObserver = (window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver); var getScrollRoot = (function() { var SCROLL_ROOT; return function() { if (!SCROLL_ROOT) { var dummy = document.createElement('div'); dummy.style.cssText = 'height:10000px;width:1px;'; document.body.appendChild(dummy); var bodyScrollTop = document.body.scrollTop; var docElScrollTop = document.documentElement.scrollTop; window.scrollBy(0, 3); if (document.body.scrollTop != bodyScrollTop) (SCROLL_ROOT = document.body); else (SCROLL_ROOT = document.documentElement); window.scrollBy(0, -3); document.body.removeChild(dummy); } return SCROLL_ROOT; }; })(); /*********************************************** * PULSE (by Michael Herf) ***********************************************/ /** * Viscous fluid with a pulse for part and decay for the rest. * - Applies a fixed force over an interval (a damped acceleration), and * - Lets the exponential bleed away the velocity over a longer interval * - Michael Herf, http://stereopsis.com/stopping/ */ function pulse_(x) { var val, start, expx; // test x = x * options.pulseScale; if (x < 1) { // acceleartion val = x - (1 - Math.exp(-x)); } else { // tail // the previous animation ended here: start = Math.exp(-1); // simple viscous drag x -= 1; expx = 1 - Math.exp(-x); val = start + (expx * (1 - start)); } return val * options.pulseNormalize; } function pulse(x) { if (x >= 1) return 1; if (x <= 0) return 0; if (options.pulseNormalize == 1) { options.pulseNormalize /= pulse_(1); } return pulse_(x); } /*********************************************** * FIRST RUN ***********************************************/ var userAgent = window.navigator.userAgent; var isEdge = /Edge/.test(userAgent); // thank you MS var isChrome = /chrome/i.test(userAgent) && !isEdge; var isSafari = /safari/i.test(userAgent) && !isEdge; var isMobile = /mobile/i.test(userAgent); var isEnabledForBrowser = (isChrome || isSafari) && !isMobile; var wheelEvent; if ('onwheel' in document.createElement('div')) wheelEvent = 'wheel'; else if ('onmousewheel' in document.createElement('div')) wheelEvent = 'mousewheel'; if (wheelEvent && isEnabledForBrowser) { addEvent(wheelEvent, wheel); addEvent('mousedown', mousedown); addEvent('load', init); } /*********************************************** * PUBLIC INTERFACE ***********************************************/ function SmoothScroll(optionsToSet) { for (var key in optionsToSet) if (defaultOptions.hasOwnProperty(key)) options[key] = optionsToSet[key]; } SmoothScroll.destroy = cleanup; if (window.SmoothScrollOptions) // async API SmoothScroll(window.SmoothScrollOptions) if (typeof define === 'function' && define.amd) define(function() { return SmoothScroll; }); else if ('object' == typeof exports) module.exports = SmoothScroll; else window.SmoothScroll = SmoothScroll; })();
var assert = require('assert'); var NotificationCenter = require('notifications/notificationcenter'); var Notification = require('notifications/notification'); /* Sender */ function Sender(nc) { this.notificationCenter = nc; }; Sender.prototype.postNotification = function(name, info) { this.notificationCenter.post(name, this, info); }; /* Observer */ function Observer(nc) { this.notificationCenter = nc; this.observed = []; }; Observer.prototype.observe = function(name, object) { var self = this; this.notificationCenter.addObserver(name, object, function(notif) { self.observed.push(notif); }); }; module.exports = { 'test aliases': function() { var nc = new NotificationCenter(); assert.equal(nc.on, nc.addObserver); assert.equal(nc.off, nc.removeObserver); }, 'test add observer for notification with a particular name from a specific sender': function() { var nc = new NotificationCenter(); nc.addObserver('notification', this, function(){}); assert.equal(nc._entries[0][0], 'notification'); assert.equal(nc._entries[0][1], this); assert.equal(typeof nc._entries[0][2], 'function'); }, 'test add observer for notifications with a particular name from any sender': function() { var nc = new NotificationCenter(); nc.addObserver('notification', function(){}); assert.equal(nc._entries[0][0], 'notification'); assert.equal(nc._entries[0][1], null); assert.equal(typeof nc._entries[0][2], 'function'); nc.addObserver('notification', null, function(){}); assert.equal(nc._entries[1][0], 'notification'); assert.equal(nc._entries[1][1], null); assert.equal(typeof nc._entries[1][2], 'function'); }, 'test add observer for notifications from a specific sender': function() { var nc = new NotificationCenter(); nc.addObserver(this, function(){}); assert.equal(nc._entries[0][0], null); assert.equal(nc._entries[0][1], this); assert.equal(typeof nc._entries[0][2], 'function'); nc.addObserver(null, this, function(){}); assert.equal(nc._entries[1][0], null); assert.equal(nc._entries[1][1], this); assert.equal(typeof nc._entries[1][2], 'function'); }, 'test add observer for all notifications': function() { var nc = new NotificationCenter(); nc.addObserver(function(){}); assert.equal(nc._entries[0][0], null); assert.equal(nc._entries[0][1], null); assert.equal(typeof nc._entries[0][2], 'function'); nc.addObserver(null, function(){}); assert.equal(nc._entries[1][0], null); assert.equal(nc._entries[1][1], null); assert.equal(typeof nc._entries[1][2], 'function'); nc.addObserver(null, null, function(){}); assert.equal(nc._entries[2][0], null); assert.equal(nc._entries[2][1], null); assert.equal(typeof nc._entries[2][2], 'function'); }, 'test remove observer for notification with a particular name from a specific sender': function() { var s1 = new Sender(); var s2 = new Sender(); var nc = new NotificationCenter(); var f = function(){}; nc.addObserver('notification', s1, f); nc.addObserver('notification', s2, f); assert.equal(nc._entries.length, 2); nc.removeObserver('notification', s1, f); assert.equal(nc._entries.length, 1); assert.equal(nc._entries[0][0], 'notification'); assert.equal(nc._entries[0][1], s2); assert.equal(nc._entries[0][2], f); }, 'test remove observer for notifications with a particular name from any sender': function() { var s1 = new Sender(); var s2 = new Sender(); var nc = new NotificationCenter(); var f = function(){}; nc.addObserver('notification-1', s1, f); nc.addObserver('notification-1', s2, f); nc.addObserver('notification-2', s2, f); assert.equal(nc._entries.length, 3); nc.removeObserver('notification-1', f); assert.equal(nc._entries.length, 1); assert.equal(nc._entries[0][0], 'notification-2'); assert.equal(nc._entries[0][1], s2); assert.equal(nc._entries[0][2], f); }, 'test remove observer for notifications from a specific sender': function() { var s1 = new Sender(); var s2 = new Sender(); var nc = new NotificationCenter(); var f = function(){}; nc.addObserver('notification-1', s1, f); nc.addObserver('notification-1', s2, f); nc.addObserver('notification-2', s2, f); assert.equal(nc._entries.length, 3); nc.removeObserver(s2, f); assert.equal(nc._entries.length, 1); assert.equal(nc._entries[0][0], 'notification-1'); assert.equal(nc._entries[0][1], s1); assert.equal(nc._entries[0][2], f); }, 'test remove observer for all notifications': function() { var s1 = new Sender(); var s2 = new Sender(); var s3 = new Sender(); var nc = new NotificationCenter(); var f1 = function(){}; var f2 = function(){}; nc.addObserver('notification-1', s1, f1); nc.addObserver('notification-2', s2, f1); nc.addObserver('notification-3', s3, f2); assert.equal(nc._entries.length, 3); nc.removeObserver(f1); assert.equal(nc._entries.length, 1); assert.equal(nc._entries[0][0], 'notification-3'); assert.equal(nc._entries[0][1], s3); assert.equal(nc._entries[0][2], f2); }, 'test observe notification with a particular name from a specific sender' : function() { var nc = new NotificationCenter(); var o = new Observer(nc); var s1 = new Sender(nc); var s2 = new Sender(nc); o.observe('notification', s1); s2.postNotification('notification', { foo: 'baz' }); assert.equal(o.observed.length, 0); s1.postNotification('notification', { foo: 'bar' }); assert.equal(o.observed.length, 1); }, 'test observe notification with a particular name from any sender' : function() { var nc = new NotificationCenter(); var o = new Observer(nc); var s1 = new Sender(nc); var s2 = new Sender(nc); o.observe('notification', null); s2.postNotification('notification', { foo: 'baz' }); assert.equal(o.observed.length, 1); s1.postNotification('notification', { foo: 'bar' }); assert.equal(o.observed.length, 2); }, 'test observe notifications from a specific sender' : function() { var nc = new NotificationCenter(); var o = new Observer(nc); var s1 = new Sender(nc); var s2 = new Sender(nc); o.observe(null, s1); s2.postNotification('notification', { foo: 'baz' }); assert.equal(o.observed.length, 0); s1.postNotification('notification-1', { item: '1' }); assert.equal(o.observed.length, 1); s1.postNotification('notification-2', { item: '2' }); assert.equal(o.observed.length, 2); }, 'test observe all notifications' : function() { var nc = new NotificationCenter(); var o = new Observer(nc); var s1 = new Sender(nc); var s2 = new Sender(nc); o.observe(null, null); s1.postNotification('notification-1', { item: '1' }); assert.equal(o.observed.length, 1); s2.postNotification('notification-2', { item: '2' }); assert.equal(o.observed.length, 2); }, 'test post notification with name object and info' : function() { var nc = new NotificationCenter(); var o = new Observer(nc); var s = new Sender(); o.observe('notification', s); nc.post('notification', s, { foo: 'bar' }); assert.equal(o.observed[0].name, 'notification'); assert.equal(o.observed[0].object, s); assert.equal(o.observed[0].info['foo'], 'bar'); }, 'test post notification with name and object' : function() { var nc = new NotificationCenter(); var o = new Observer(nc); var s = new Sender(); o.observe('notification', s); nc.post('notification', s); assert.equal(o.observed[0].name, 'notification'); assert.equal(o.observed[0].object, s); assert.equal(o.observed[0].info, null); }, 'test post notification with notification' : function() { var nc = new NotificationCenter(); var o = new Observer(nc); var s = new Sender(); o.observe('notification', s); var n = new Notification('notification', s); nc.post(n); assert.equal(o.observed[0].name, 'notification'); assert.equal(o.observed[0].object, s); assert.equal(o.observed[0].info, null); } }
const BloomFilter = require('@mixmaxhq/bloom-filter'); /** * `sha.js` is an isomorphic hashing library that implements its hashing functions synchronously. * This is important for our usage of it, as we wish to support this library without resorting to * browser-only or node-only APIs. * * We could use `createHash`, which is a top level dependency of browserify's crypto polyfill - * however, adding said library to this module bloats the bundle size to around 150 kb. We can * avoid this by only using the hashing function we need and make use of browserify's Buffer * polyfill for anything after that. */ const sha256 = require('sha.js/sha256'); const MAX_UINT_32 = Math.pow(2, 32); /** * Deserializes a user gate and checks users against the gate. * * This is a constructor, and must be called with `new`. * * @param {Object} encodedGate - JSON produced by `UserGateEncoder`. * @param {Object=} options * @property {float=} sample - the percentage of users we wish to let in. */ class UserGate { // eslint-disable-next-line no-unused-vars constructor(encodedGate, options) { encodedGate = encodedGate || {}; if (encodedGate.list) { encodedGate.list.vData = new Buffer(encodedGate.list.vData.data); this._list = new BloomFilter(encodedGate.list); } this._sample = encodedGate.sample; options = options || {}; } /** * Checks whether _user_ (a string identifier similar to those encoded) is allowed * through the gate, either because: * * - they're on the list * - they're part of the first _sample_ users * * Sampling is done by hashing the user string and projecting it onto a sample space * (more on this below). This sampling technique is deterministic: a user will either * always be allowed through the gate, even if they reload, or they never will. * * Checking against the list requires an exact match. However, sampling is * case-insensitive. * * @param {String} user * * @return {Boolean} `true` if _user_ is allowed through the gate, `false` otherwise. */ allows(user) { return this._matchesSample(user) || this._matchesList(user); } _matchesList(user) { if (!this._list) return false; return this._list.contains(user); } _matchesSample(user) { if (typeof this._sample !== 'number' || !(this._sample >= 0 && this._sample <= 1)) return false; if (!user) return false; // Allow for case insensitivity, which was a feature in V2.0 of this library. user = user.toLowerCase(); // We've got to project `user` onto the sample space (i.e. convert it to a number between 0 and // 1) in a way that is a) deterministic b) uniform. We do this by hashing the user, converting it // to an unsigned 32-bit integer, and then normalizing by the size of the max UInt32--essentially // this solution https://stats.stackexchange.com/a/70884 but with only two buckets ("matches", // or "doesn't match"). const hash = new sha256(); const buf = hash.update(user).digest(); // This method of conversion-to-integer will truncate the hash to the first four bytes. But hashes // are designed to be random in each individual bit https://crypto.stackexchange.com/a/26859, so // this is no less uniform--just with greater likelihood of collisions, which is fine for us since // we're collapsing the distribution onto two buckets anyway. const uint32 = Buffer.from(buf).readUInt32BE(0); const sample = uint32 / MAX_UINT_32; return sample <= this._sample; } } module.exports = UserGate;
var express = require('express') , passport = require('passport') , util = require('util') , FamilySearchStrategy = require('passport-familysearch').LegacyStrategy; var FAMILYSEARCH_DEVELOPER_KEY = "insert_familysearch_developer_key_here"; // Passport session setup. // To support persistent login sessions, Passport needs to be able to // serialize users into and deserialize users out of the session. Typically, // this will be as simple as storing the user ID when serializing, and finding // the user by ID when deserializing. However, since this example does not // have a database of user records, the complete FamilySearch profile is // serialized and deserialized. passport.serializeUser(function(user, done) { done(null, user); }); passport.deserializeUser(function(obj, done) { done(null, obj); }); // Use the FamilySearchStrategy within Passport. // Strategies in passport require a `verify` function, which accept // credentials (in this case, a token, tokenSecret, and FamilySearch profile), and // invoke a callback with a user object. passport.use(new FamilySearchStrategy({ requestTokenURL: 'https://sandbox.familysearch.org/identity/v2/request_token', accessTokenURL: 'https://sandbox.familysearch.org/identity/v2/access_token', userAuthorizationURL: 'https://sandbox.familysearch.org/identity/v2/authorize', userProfileURL: 'https://sandbox.familysearch.org/identity/v2/user', consumerKey: FAMILYSEARCH_DEVELOPER_KEY, consumerSecret: '', callbackURL: "http://127.0.0.1:3000/auth/familysearch/callback" }, function(token, tokenSecret, profile, done) { // asynchronous verification, for effect... process.nextTick(function () { // To keep the example simple, the user's FamilySearch profile is returned to // represent the logged-in user. In a typical application, you would want // to associate the FamilySearch account with a user record in your database, // and return that user instead. return done(null, profile); }); } )); var app = express(); // configure Express app.configure(function() { app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.use(express.logger()); app.use(express.cookieParser()); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.session({ secret: 'keyboard cat' })); // Initialize Passport! Also use passport.session() middleware, to support // persistent login sessions (recommended). app.use(passport.initialize()); app.use(passport.session()); app.use(app.router); app.use(express.static(__dirname + '/public')); }); app.get('/', function(req, res){ res.render('index', { user: req.user }); }); app.get('/account', ensureAuthenticated, function(req, res){ res.render('account', { user: req.user }); }); app.get('/login', function(req, res){ res.render('login', { user: req.user }); }); // GET /auth/familysearch // Use passport.authenticate() as route middleware to authenticate the // request. The first step in FamilySearch authentication will involve redirecting // the user to familysearch.org. After authorization, FamilySearch will redirect the user // back to this application at /auth/familysearch/callback app.get('/auth/familysearch', passport.authenticate('familysearch'), function(req, res){ // The request will be redirected to FamilySearch for authentication, so this // function will not be called. }); // GET /auth/familysearch/callback // Use passport.authenticate() as route middleware to authenticate the // request. If authentication fails, the user will be redirected back to the // login page. Otherwise, the primary route function function will be called, // which, in this example, will redirect the user to the home page. app.get('/auth/familysearch/callback', passport.authenticate('familysearch', { failureRedirect: '/login' }), function(req, res) { res.redirect('/'); }); app.get('/logout', function(req, res){ req.logout(); res.redirect('/'); }); app.listen(3000); // Simple route middleware to ensure user is authenticated. // Use this route middleware on any resource that needs to be protected. If // the request is authenticated (typically via a persistent login session), // the request will proceed. Otherwise, the user will be redirected to the // login page. function ensureAuthenticated(req, res, next) { if (req.isAuthenticated()) { return next(); } res.redirect('/login') }
//index.js const AV = require('../../libs/av-weapp-min.js') var app = getApp() Page({ data: { motto: 'Hello World', userInfo: {} }, //事件处理函数 bindViewTap: function() { wx.navigateTo({ url: '../logs/logs' }) }, onLoad: function() { console.log('onLoad') this.saveUser() }, saveUser() { var that = this //调用应用实例的方法获取全局数据 app.getUserInfo(function(userInfo) { //update data that.setData({ userInfo: userInfo }) wx.setStorage({ key: "userInfo", data: userInfo }) let nickName = that.data.userInfo.nickName let avatarUrl = that.data.userInfo.avatarUrl let gender = that.data.userInfo.gender AV.Query.doCloudQuery('insert into _User(username, password , avatarUrl, gender) values("' + nickName + '","123", "' + avatarUrl + '",' + gender + ')').then(function(data) { // data 中的 results 是本次查询返回的结果,AV.Object 实例列表 var results = data.results; }, function(error) { //查询失败,查看 error console.log(error); }); }) }, createPlan() { wx.navigateTo({ url: '/pages/plan/index' }) } })
'use strict'; module.exports = ['$q', '$log', '$http', 'authService', chapterService]; function chapterService($q, $log, $http, authService) { $log.debug('chapterService()'); let service = {}; service.createChapter = (manuscriptData, chapterData) => { $log.debug('chapterService.createChapter()'); return authService.getToken() .then(token => { let url = `${__API_URL__}/api/manuscript/${manuscriptData._id}/chapter`; // eslint-disable-line let config = { headers: { Accept: 'application/json', 'Content-Type': 'application/json', Authorization: `Bearer ${token}` } }; return $http.post(url, chapterData, config); }) .then(res => { $log.log('chapter created'); let chapter = res.data; manuscriptData.chapters.unshift(chapter); return chapter; }) .catch(err => { $log.error(err.message); return $q.reject(err); }); }; service.updateChapter = (manuscriptData, chapterData) => { $log.debug('chapterService.updateChapter()'); return authService.getToken() .then(token => { let url = `${__API_URL__}/api/manuscript/${manuscriptData._id}/chapter/${chapterData._id}`; // eslint-disable-line let config = { headers: { Accept: 'application/json', Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' } }; return $http.put(url, chapterData, config); }) .then(res => { for (let i = 0; i < manuscriptData.chapters.length; i++) { let current = manuscriptData.chapters[i]; if (current._id === chapterData._id) { manuscriptData.chapters[i] = res.data; break; } } return res.data; }) .catch(err => { $log.error(err.message); return $q.reject(err); }); }; service.deleteChapter = function(manuscriptData, chapterData) { $log.debug('chapterService.deletePost()'); return authService.getToken() .then(token => { let url = `${__API_URL__}/api/manuscript/${manuscriptData._id}/chapter/${chapterData._id}`; // eslint-disable-line let config = { headers: { Authorization: `Bearer ${token}` } }; return $http.delete(url, config); }) .then(res => { //eslint-disable-line for (let i = 0; i < manuscriptData.chapters.length; i++) { let current = manuscriptData.chapters[i]; if (current._id === chapterData._id) { manuscriptData.chapters.splice(i, 1); break; } } }) .catch(err => { $log.error(err.message); return $q.reject(err); }); }; service.fetchAllChaptersFromDB = function() { $log.debug('chapterService.fetchAllChaptersFromDB()'); let url = `${__API_URL__}/api/chapters`; //eslint-disable-line let config = { headers: { Accept: 'application/json', 'Content-Type': 'application/json' } }; return $http.get(url, config); }; return service; }
'use strict' let cli = require('heroku-cli-util') let co = require('co') let emptyFormationErr = (app) => { return new Error(`No process types on ${cli.color.app(app)}. Upload a Procfile to add process types. https://devcenter.heroku.com/articles/procfile`) } function * run (context, heroku) { const compact = require('lodash.compact') let app = context.app function parse (args) { return compact(args.map((arg) => { let change = arg.match(/^([a-zA-Z0-9_]+)([=+-]\d+)(?::([\w-]+))?$/) if (!change) return let quantity = change[2][0] === '=' ? change[2].substr(1) : change[2] return {type: change[1], quantity, size: change[3]} })) } let changes = parse(context.args) if (changes.length === 0) { let formation = yield heroku.get(`/apps/${app}/formation`) if (formation.length === 0) throw emptyFormationErr(app) cli.log(formation.map((d) => `${d.type}=${d.quantity}:${d.size}`).sort().join(' ')) } else { yield cli.action('Scaling dynos', {success: false}, co(function * () { let formation = yield heroku.request({method: 'PATCH', path: `/apps/${app}/formation`, body: {updates: changes}}) let output = formation.filter((f) => changes.find((c) => c.type === f.type)) .map((d) => `${cli.color.green(d.type)} at ${d.quantity}:${d.size}`) cli.action.done(`done, now running ${output.join(', ')}`) })) } } let cmd = { variableArgs: true, description: 'scale dyno quantity up or down', help: `Appending a size (eg. web=2:Standard-2X) allows simultaneous scaling and resizing. Omitting any arguments will display the app's current dyno formation, in a format suitable for passing back into ps:scale. Examples: $ heroku ps:scale web=3:Standard-2X worker+1 Scaling dynos... done, now running web at 3:Standard-2X, worker at 1:Standard-1X. $ heroku ps:scale web=3:Standard-2X worker=1:Standard-1X `, needsAuth: true, needsApp: true, run: cli.command(co.wrap(run)) } exports.ps = Object.assign({}, cmd, {topic: 'ps', command: 'scale'}) exports.root = Object.assign({}, cmd, {topic: 'scale', command: null}) exports.dyno = Object.assign({}, cmd, {topic: 'dyno', command: 'scale'})