code
stringlengths
2
1.05M
const DrawCard = require('../../drawcard.js'); class Harmonize extends DrawCard { setupCardAbilities(ability) { this.action({ title: 'Send a character home from each side', cannotBeMirrored: true, targets: { myCharacter: { cardCondition: (card, context) => card.isDefending() && card.controller === context.player, gameAction: ability.actions.sendHome() }, oppCharacter: { dependsOn: 'myCharacter', cardCondition: (card, context) => card.isAttacking() && card.costLessThan(context.targets.myCharacter.getCost() + 1), gameAction: ability.actions.sendHome() } }, effect: 'send home {1} and {2}', effectArgs: context => [context.targets.myCharacter, context.targets.oppCharacter] }); } } Harmonize.id = 'harmonize'; module.exports = Harmonize;
// *********************************************** // This example commands.js shows you how to // create the custom command: 'login'. // // The commands.js file is a great place to // modify existing commands and create custom // commands for use throughout your tests. // // You can read more about custom commands here: // https://on.cypress.io/api/commands // *********************************************** // // Cypress.addParentCommand("login", function(email, password){ // var email = email || "joe@example.com" // var password = password || "foobar" // // var log = Cypress.Log.command({ // name: "login", // message: [email, password], // onConsole: function(){ // return { // email: email, // password: password // } // } // }) // // cy // .visit("/login", {log: false}) // .contains("Log In", {log: false}) // .get("#email", {log: false}).type(email, {log: false}) // .get("#password", {log: false}).type(password, {log: false}) // .get("button", {log: false}).click({log: false}) //this should submit the form // .get("h1", {log: false}).contains("Dashboard", {log: false}) //we should be on the dashboard now // .url({log: false}).should("match", /dashboard/, {log: false}) // .then(function(){ // log.snapshot().end() // }) // })
/** Used to map aliases to their real names. */ exports.aliasToReal = { // Lodash aliases. 'each': 'forEach', 'eachRight': 'forEachRight', 'entries': 'toPairs', 'entriesIn': 'toPairsIn', 'extend': 'assignIn', 'extendWith': 'assignInWith', 'first': 'head', // Ramda aliases. '__': 'placeholder', 'all': 'every', 'allPass': 'overEvery', 'always': 'constant', 'any': 'some', 'anyPass': 'overSome', 'apply': 'spread', 'assoc': 'set', 'assocPath': 'set', 'complement': 'negate', 'compose': 'flowRight', 'contains': 'includes', 'dissoc': 'unset', 'dissocPath': 'unset', 'equals': 'isEqual', 'identical': 'eq', 'init': 'initial', 'invertObj': 'invert', 'juxt': 'over', 'omitAll': 'omit', 'nAry': 'ary', 'path': 'get', 'pathEq': 'matchesProperty', 'pathOr': 'getOr', 'paths': 'at', 'pickAll': 'pick', 'pipe': 'flow', 'pluck': 'map', 'prop': 'get', 'propEq': 'matchesProperty', 'propOr': 'getOr', 'props': 'at', 'unapply': 'rest', 'unnest': 'flatten', 'useWith': 'overArgs', 'whereEq': 'filter', 'zipObj': 'zipObject' }; /** Used to map ary to method names. */ exports.aryMethod = { '1': [ 'attempt', 'castArray', 'ceil', 'create', 'curry', 'curryRight', 'floor', 'flow', 'flowRight', 'fromPairs', 'invert', 'iteratee', 'memoize', 'method', 'methodOf', 'mixin', 'over', 'overEvery', 'overSome', 'rest', 'reverse', 'round', 'runInContext', 'spread', 'template', 'trim', 'trimEnd', 'trimStart', 'uniqueId', 'words' ], '2': [ 'add', 'after', 'ary', 'assign', 'assignIn', 'at', 'before', 'bind', 'bindAll', 'bindKey', 'chunk', 'cloneDeepWith', 'cloneWith', 'concat', 'countBy', 'curryN', 'curryRightN', 'debounce', 'defaults', 'defaultsDeep', 'delay', 'difference', 'divide', 'drop', 'dropRight', 'dropRightWhile', 'dropWhile', 'endsWith', 'eq', 'every', 'filter', 'find', 'findIndex', 'findKey', 'findLast', 'findLastIndex', 'findLastKey', 'flatMap', 'flatMapDeep', 'flattenDepth', 'forEach', 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'get', 'groupBy', 'gt', 'gte', 'has', 'hasIn', 'includes', 'indexOf', 'intersection', 'invertBy', 'invoke', 'invokeMap', 'isEqual', 'isMatch', 'join', 'keyBy', 'lastIndexOf', 'lt', 'lte', 'map', 'mapKeys', 'mapValues', 'matchesProperty', 'maxBy', 'meanBy', 'merge', 'minBy', 'multiply', 'nth', 'omit', 'omitBy', 'overArgs', 'pad', 'padEnd', 'padStart', 'parseInt', 'partial', 'partialRight', 'partition', 'pick', 'pickBy', 'pull', 'pullAll', 'pullAt', 'random', 'range', 'rangeRight', 'rearg', 'reject', 'remove', 'repeat', 'restFrom', 'result', 'sampleSize', 'some', 'sortBy', 'sortedIndex', 'sortedIndexOf', 'sortedLastIndex', 'sortedLastIndexOf', 'sortedUniqBy', 'split', 'spreadFrom', 'startsWith', 'subtract', 'sumBy', 'take', 'takeRight', 'takeRightWhile', 'takeWhile', 'tap', 'throttle', 'thru', 'times', 'trimChars', 'trimCharsEnd', 'trimCharsStart', 'truncate', 'union', 'uniqBy', 'uniqWith', 'unset', 'unzipWith', 'without', 'wrap', 'xor', 'zip', 'zipObject', 'zipObjectDeep' ], '3': [ 'assignInWith', 'assignWith', 'clamp', 'differenceBy', 'differenceWith', 'findFrom', 'findIndexFrom', 'findLastFrom', 'findLastIndexFrom', 'getOr', 'includesFrom', 'indexOfFrom', 'inRange', 'intersectionBy', 'intersectionWith', 'invokeArgs', 'invokeArgsMap', 'isEqualWith', 'isMatchWith', 'flatMapDepth', 'lastIndexOfFrom', 'mergeWith', 'orderBy', 'padChars', 'padCharsEnd', 'padCharsStart', 'pullAllBy', 'pullAllWith', 'reduce', 'reduceRight', 'replace', 'set', 'slice', 'sortedIndexBy', 'sortedLastIndexBy', 'transform', 'unionBy', 'unionWith', 'update', 'xorBy', 'xorWith', 'zipWith' ], '4': [ 'fill', 'setWith', 'updateWith' ] }; /** Used to map ary to rearg configs. */ exports.aryRearg = { '2': [1, 0], '3': [2, 0, 1], '4': [3, 2, 0, 1] }; /** Used to map method names to their iteratee ary. */ exports.iterateeAry = { 'dropRightWhile': 1, 'dropWhile': 1, 'every': 1, 'filter': 1, 'find': 1, 'findFrom': 1, 'findIndex': 1, 'findIndexFrom': 1, 'findKey': 1, 'findLast': 1, 'findLastFrom': 1, 'findLastIndex': 1, 'findLastIndexFrom': 1, 'findLastKey': 1, 'flatMap': 1, 'flatMapDeep': 1, 'flatMapDepth': 1, 'forEach': 1, 'forEachRight': 1, 'forIn': 1, 'forInRight': 1, 'forOwn': 1, 'forOwnRight': 1, 'map': 1, 'mapKeys': 1, 'mapValues': 1, 'partition': 1, 'reduce': 2, 'reduceRight': 2, 'reject': 1, 'remove': 1, 'some': 1, 'takeRightWhile': 1, 'takeWhile': 1, 'times': 1, 'transform': 2 }; /** Used to map method names to iteratee rearg configs. */ exports.iterateeRearg = { 'mapKeys': [1] }; /** Used to map method names to rearg configs. */ exports.methodRearg = { 'assignInWith': [1, 2, 0], 'assignWith': [1, 2, 0], 'differenceBy': [1, 2, 0], 'differenceWith': [1, 2, 0], 'getOr': [2, 1, 0], 'intersectionBy': [1, 2, 0], 'intersectionWith': [1, 2, 0], 'isEqualWith': [1, 2, 0], 'isMatchWith': [2, 1, 0], 'mergeWith': [1, 2, 0], 'padChars': [2, 1, 0], 'padCharsEnd': [2, 1, 0], 'padCharsStart': [2, 1, 0], 'pullAllBy': [2, 1, 0], 'pullAllWith': [2, 1, 0], 'setWith': [3, 1, 2, 0], 'sortedIndexBy': [2, 1, 0], 'sortedLastIndexBy': [2, 1, 0], 'unionBy': [1, 2, 0], 'unionWith': [1, 2, 0], 'updateWith': [3, 1, 2, 0], 'xorBy': [1, 2, 0], 'xorWith': [1, 2, 0], 'zipWith': [1, 2, 0] }; /** Used to map method names to spread configs. */ exports.methodSpread = { 'invokeArgs': 2, 'invokeArgsMap': 2, 'partial': 1, 'partialRight': 1, 'without': 1 }; /** Used to identify methods which mutate arrays or objects. */ exports.mutate = { 'array': { 'fill': true, 'pull': true, 'pullAll': true, 'pullAllBy': true, 'pullAllWith': true, 'pullAt': true, 'remove': true, 'reverse': true }, 'object': { 'assign': true, 'assignIn': true, 'assignInWith': true, 'assignWith': true, 'defaults': true, 'defaultsDeep': true, 'merge': true, 'mergeWith': true }, 'set': { 'set': true, 'setWith': true, 'unset': true, 'update': true, 'updateWith': true } }; /** Used to track methods with placeholder support */ exports.placeholder = { 'bind': true, 'bindKey': true, 'curry': true, 'curryRight': true, 'partial': true, 'partialRight': true }; /** Used to map real names to their aliases. */ exports.realToAlias = (function() { var hasOwnProperty = Object.prototype.hasOwnProperty, object = exports.aliasToReal, result = {}; for (var key in object) { var value = object[key]; if (hasOwnProperty.call(result, value)) { result[value].push(key); } else { result[value] = [key]; } } return result; }()); /** Used to map method names to other names. */ exports.remap = { 'curryN': 'curry', 'curryRightN': 'curryRight', 'findFrom': 'find', 'findIndexFrom': 'findIndex', 'findLastFrom': 'findLast', 'findLastIndexFrom': 'findLastIndex', 'getOr': 'get', 'includesFrom': 'includes', 'indexOfFrom': 'indexOf', 'invokeArgs': 'invoke', 'invokeArgsMap': 'invokeMap', 'lastIndexOfFrom': 'lastIndexOf', 'padChars': 'pad', 'padCharsEnd': 'padEnd', 'padCharsStart': 'padStart', 'restFrom': 'rest', 'spreadFrom': 'spread', 'trimChars': 'trim', 'trimCharsEnd': 'trimEnd', 'trimCharsStart': 'trimStart' }; /** Used to track methods that skip fixing their arity. */ exports.skipFixed = { 'castArray': true, 'flow': true, 'flowRight': true, 'iteratee': true, 'mixin': true, 'runInContext': true }; /** Used to track methods that skip rearranging arguments. */ exports.skipRearg = { 'add': true, 'assign': true, 'assignIn': true, 'bind': true, 'bindKey': true, 'concat': true, 'difference': true, 'divide': true, 'eq': true, 'gt': true, 'gte': true, 'isEqual': true, 'lt': true, 'lte': true, 'matchesProperty': true, 'merge': true, 'multiply': true, 'overArgs': true, 'partial': true, 'partialRight': true, 'random': true, 'range': true, 'rangeRight': true, 'subtract': true, 'zip': true, 'zipObject': true };
var arrayOfJsStrings = [ {"foo": 'bar'}, {"a b c": {unquoted:"nested"}}, {"hyphen-ated": [1,2,3]}, {unquoted: "<html>here<script>var a = 'string';</script></html>"} ]; if (typeof module !== 'undefined' && module.exports) { module.exports = arrayOfJsStrings; }
import * as actions from './actions'; import * as authActions from '../auth/actions'; import User from './user'; import { Record, Seq } from 'immutable'; import { firebaseActions, mapAuthToUser } from '../lib/redux-firebase'; const InitialState = Record({ // Undefined is absence of evidence. Null is evidence of absence. list: undefined, viewer: undefined }); const initialState = new InitialState; const reviveList = list => list && Seq(list) .map(json => new User(json)) .sortBy(user => -user.authenticatedAt) .toList(); const revive = ({ list, viewer }) => initialState.merge({ list: reviveList(list), viewer: viewer ? new User(viewer) : null }); export default function usersReducer(state = initialState, action) { if (!(state instanceof InitialState)) return revive(state); switch (action.type) { case authActions.LOGIN_SUCCESS: { const { email, id } = action.payload; const user = new User({ email, id }); return state.set('viewer', user); } case firebaseActions.REDUX_FIREBASE_ON_AUTH: { const { authData } = action.payload; // Handle logout. if (!authData) { return state.delete('viewer'); } const user = new User(mapAuthToUser(authData)); return state.set('viewer', user); } case actions.ON_USERS_LIST: { const { list } = action.payload; return state.set('list', reviveList(list)); } } return state; }
import LegendEffectOpacity from './LegendEffectOpacity'; export default { LegendEffectOpacity, };
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S11.9.4_A8_T3; * @section: 11.9.4, 11.9.6; * @assertion: If Type(x) is different from Type(y), return false; * @description: x or y is primitive string; */ //CHECK#1 if ("1" === new String("1")) { $ERROR('#1: "1" !== new String("1")'); } //CHECK#2 if ("1" === true) { $ERROR('#2: "1" !== true'); } //CHECK#3 if ("1" === new Boolean("1")) { $ERROR('#3: "1" !== new Boolean("1")'); } //CHECK#4 if ("1" === 1) { $ERROR('#4: "1" === 1'); } //CHECK#5 if ("1" === new Number("1")) { $ERROR('#5: "1" === new Number("1")'); } //CHECK#6 if (new String(false) === false) { $ERROR('#6: new Number(false) !== false'); } //CHECK#7 if (false === "0") { $ERROR('#7: false !== "0"'); } //CHECK#8 if ("0" === new Boolean("0")) { $ERROR('#8: "0" !== new Boolean("0")'); } //CHECK#9 if (false === 0) { $ERROR('#9: false !== 0'); } //CHECK#10 if (false === new Number(false)) { $ERROR('#10: false !== new Number(false)'); } //CHECK#11 if ("1" === {valueOf: function () {return "1"}}) { $ERROR('#11: "1" === {valueOf: function () {return "1"}}'); }
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM5.61 16.78C4.6 15.45 4 13.8 4 12s.6-3.45 1.61-4.78C7.06 8.31 8 10.05 8 12s-.94 3.69-2.39 4.78zM12 20c-1.89 0-3.63-.66-5-1.76 1.83-1.47 3-3.71 3-6.24S8.83 7.23 7 5.76C8.37 4.66 10.11 4 12 4s3.63.66 5 1.76c-1.83 1.47-3 3.71-3 6.24s1.17 4.77 3 6.24c-1.37 1.1-3.11 1.76-5 1.76zm6.39-3.22C16.94 15.69 16 13.95 16 12s.94-3.69 2.39-4.78C19.4 8.55 20 10.2 20 12s-.6 3.45-1.61 4.78z" }), 'SportsBaseballOutlined'); exports.default = _default;
var div = document.createElement('div'); div.innerHTML = 'Script was loaded and added this div!'; document.body.appendChild(div);
import { configure } from "enzyme"; import Adapter from "enzyme-adapter-react-16"; configure({ adapter: new Adapter() });
{ "ADP_currencyISO" : "peseta andorrana", "ADP_currencyPlural" : "pesetas andorranas", "ADP_currencySingular" : "peseta andorrana", "ADP_currencySymbol" : "ADP", "AED_currencyISO" : "dírham de los Emiratos Árabes Unidos", "AED_currencyPlural" : "dirhams de los Emiratos Árabes Unidos", "AED_currencySingular" : "dirham de los Emiratos Árabes Unidos", "AED_currencySymbol" : "AED", "AFA_currencyISO" : "afgani (1927-2002)", "AFA_currencyPlural" : "dirhams de los Emiratos Árabes Unidos", "AFA_currencySingular" : "dirham de los Emiratos Árabes Unidos", "AFA_currencySymbol" : "AFA", "AFN_currencyISO" : "afgani", "AFN_currencyPlural" : "afganis afganos", "AFN_currencySingular" : "afgani afgano", "AFN_currencySymbol" : "Af", "ALK_currencyISO" : "afgani", "ALK_currencyPlural" : "afganis afganos", "ALK_currencySingular" : "afgani afgano", "ALK_currencySymbol" : "Af", "ALL_currencyISO" : "lek albanés", "ALL_currencyPlural" : "lekë albaneses", "ALL_currencySingular" : "lek albanés", "ALL_currencySymbol" : "ALL", "AMD_currencyISO" : "dram armenio", "AMD_currencyPlural" : "dram armenios", "AMD_currencySingular" : "dram armenio", "AMD_currencySymbol" : "AMD", "ANG_currencyISO" : "florín de las Antillas Neerlandesas", "ANG_currencyPlural" : "florines de las Antillas Neerlandesas", "ANG_currencySingular" : "florín de las Antillas Neerlandesas", "ANG_currencySymbol" : "NAf.", "AOA_currencyISO" : "kwanza angoleño", "AOA_currencyPlural" : "kwanzas angoleños", "AOA_currencySingular" : "kwanza angoleño", "AOA_currencySymbol" : "Kz", "AOK_currencyISO" : "kwanza angoleño (1977-1990)", "AOK_currencyPlural" : "kwanzas angoleños", "AOK_currencySingular" : "kwanza angoleño", "AOK_currencySymbol" : "AOK", "AON_currencyISO" : "nuevo kwanza angoleño (1990-2000)", "AON_currencyPlural" : "kwanzas angoleños", "AON_currencySingular" : "kwanza angoleño", "AON_currencySymbol" : "AON", "AOR_currencyISO" : "kwanza reajustado angoleño (1995-1999)", "AOR_currencyPlural" : "kwanzas angoleños", "AOR_currencySingular" : "kwanza angoleño", "AOR_currencySymbol" : "AOR", "ARA_currencyISO" : "austral argentino", "ARA_currencyPlural" : "australes argentinos", "ARA_currencySingular" : "austral argentino", "ARA_currencySymbol" : "₳", "ARL_currencyISO" : "ARL", "ARL_currencyPlural" : "australes argentinos", "ARL_currencySingular" : "austral argentino", "ARL_currencySymbol" : "$L", "ARM_currencyISO" : "ARM", "ARM_currencyPlural" : "australes argentinos", "ARM_currencySingular" : "austral argentino", "ARM_currencySymbol" : "m$n", "ARP_currencyISO" : "peso argentino (1983-1985)", "ARP_currencyPlural" : "pesos argentinos (ARP)", "ARP_currencySingular" : "peso argentino (ARP)", "ARP_currencySymbol" : "ARP", "ARS_currencyISO" : "peso argentino", "ARS_currencyPlural" : "pesos argentinos", "ARS_currencySingular" : "peso argentino", "ARS_currencySymbol" : "AR$", "ATS_currencyISO" : "chelín austriaco", "ATS_currencyPlural" : "chelines austriacos", "ATS_currencySingular" : "chelín austriaco", "ATS_currencySymbol" : "ATS", "AUD_currencyISO" : "dólar australiano", "AUD_currencyPlural" : "dólares australianos", "AUD_currencySingular" : "dólar australiano", "AUD_currencySymbol" : "AU$", "AWG_currencyISO" : "florín de Aruba", "AWG_currencyPlural" : "florines de Aruba", "AWG_currencySingular" : "florín de Aruba", "AWG_currencySymbol" : "Afl.", "AZM_currencyISO" : "manat azerí (1993-2006)", "AZM_currencyPlural" : "florines de Aruba", "AZM_currencySingular" : "florín de Aruba", "AZM_currencySymbol" : "AZM", "AZN_currencyISO" : "manat azerí", "AZN_currencyPlural" : "manat azeríes", "AZN_currencySingular" : "manat azerí", "AZN_currencySymbol" : "man.", "BAD_currencyISO" : "dinar bosnio", "BAD_currencyPlural" : "dinares bosnios", "BAD_currencySingular" : "dinar bosnio", "BAD_currencySymbol" : "BAD", "BAM_currencyISO" : "marco convertible de Bosnia-Herzegovina", "BAM_currencyPlural" : "marcos convertibles de Bosnia-Herzegovina", "BAM_currencySingular" : "marco convertible de Bosnia-Herzegovina", "BAM_currencySymbol" : "KM", "BAN_currencyISO" : "marco convertible de Bosnia-Herzegovina", "BAN_currencyPlural" : "marcos convertibles de Bosnia-Herzegovina", "BAN_currencySingular" : "marco convertible de Bosnia-Herzegovina", "BAN_currencySymbol" : "KM", "BBD_currencyISO" : "dólar de Barbados", "BBD_currencyPlural" : "dólares de Barbados", "BBD_currencySingular" : "dólar de Barbados", "BBD_currencySymbol" : "Bds$", "BDT_currencyISO" : "taka de Bangladesh", "BDT_currencyPlural" : "taka de Bangladesh", "BDT_currencySingular" : "taka de Bangladesh", "BDT_currencySymbol" : "Tk", "BEC_currencyISO" : "franco belga (convertible)", "BEC_currencyPlural" : "francos belgas (convertibles)", "BEC_currencySingular" : "franco belga (convertible)", "BEC_currencySymbol" : "BEC", "BEF_currencyISO" : "franco belga", "BEF_currencyPlural" : "francos belgas", "BEF_currencySingular" : "franco belga", "BEF_currencySymbol" : "BF", "BEL_currencyISO" : "franco belga (financiero)", "BEL_currencyPlural" : "francos belgas (financieros)", "BEL_currencySingular" : "franco belga (financiero)", "BEL_currencySymbol" : "BEL", "BGL_currencyISO" : "lev fuerte búlgaro", "BGL_currencyPlural" : "leva fuertes búlgaros", "BGL_currencySingular" : "lev fuerte búlgaro", "BGL_currencySymbol" : "BGL", "BGM_currencyISO" : "lev fuerte búlgaro", "BGM_currencyPlural" : "leva fuertes búlgaros", "BGM_currencySingular" : "lev fuerte búlgaro", "BGM_currencySymbol" : "BGL", "BGN_currencyISO" : "nuevo lev búlgaro", "BGN_currencyPlural" : "nuevos leva búlgaros", "BGN_currencySingular" : "nuevo lev búlgaro", "BGN_currencySymbol" : "BGN", "BGO_currencyISO" : "nuevo lev búlgaro", "BGO_currencyPlural" : "nuevos leva búlgaros", "BGO_currencySingular" : "nuevo lev búlgaro", "BGO_currencySymbol" : "BGN", "BHD_currencyISO" : "dinar bahreiní", "BHD_currencyPlural" : "dinares bahreiníes", "BHD_currencySingular" : "dinar bahreiní", "BHD_currencySymbol" : "BD", "BIF_currencyISO" : "franco de Burundi", "BIF_currencyPlural" : "francos de Burundi", "BIF_currencySingular" : "franco de Burundi", "BIF_currencySymbol" : "FBu", "BMD_currencyISO" : "dólar de Bermudas", "BMD_currencyPlural" : "dólares de Bermudas", "BMD_currencySingular" : "dólar de Bermudas", "BMD_currencySymbol" : "BD$", "BND_currencyISO" : "dólar de Brunéi", "BND_currencyPlural" : "dólares de Brunéi", "BND_currencySingular" : "dólar de Brunéi", "BND_currencySymbol" : "BN$", "BOB_currencyISO" : "boliviano", "BOB_currencyPlural" : "bolivianos", "BOB_currencySingular" : "boliviano", "BOB_currencySymbol" : "Bs", "BOL_currencyISO" : "boliviano", "BOL_currencyPlural" : "bolivianos", "BOL_currencySingular" : "boliviano", "BOL_currencySymbol" : "Bs", "BOP_currencyISO" : "peso boliviano", "BOP_currencyPlural" : "pesos bolivianos", "BOP_currencySingular" : "peso boliviano", "BOP_currencySymbol" : "$b.", "BOV_currencyISO" : "MVDOL boliviano", "BOV_currencyPlural" : "MVDOL bolivianos", "BOV_currencySingular" : "MVDOL boliviano", "BOV_currencySymbol" : "BOV", "BRB_currencyISO" : "nuevo cruceiro brasileño (1967-1986)", "BRB_currencyPlural" : "nuevos cruzados brasileños (BRB)", "BRB_currencySingular" : "nuevo cruzado brasileño (BRB)", "BRB_currencySymbol" : "BRB", "BRC_currencyISO" : "cruzado brasileño", "BRC_currencyPlural" : "cruzados brasileños", "BRC_currencySingular" : "cruzado brasileño", "BRC_currencySymbol" : "BRC", "BRE_currencyISO" : "cruceiro brasileño (1990-1993)", "BRE_currencyPlural" : "cruceiros brasileños (BRE)", "BRE_currencySingular" : "cruceiro brasileño (BRE)", "BRE_currencySymbol" : "BRE", "BRL_currencyISO" : "real brasileño", "BRL_currencyPlural" : "reales brasileños", "BRL_currencySingular" : "real brasileño", "BRL_currencySymbol" : "R$", "BRN_currencyISO" : "nuevo cruzado brasileño", "BRN_currencyPlural" : "nuevos cruzados brasileños", "BRN_currencySingular" : "nuevo cruzado brasileño", "BRN_currencySymbol" : "BRN", "BRR_currencyISO" : "cruceiro brasileño", "BRR_currencyPlural" : "cruceiros brasileños", "BRR_currencySingular" : "cruceiro brasileño", "BRR_currencySymbol" : "BRR", "BRZ_currencyISO" : "cruceiro brasileño", "BRZ_currencyPlural" : "cruceiros brasileños", "BRZ_currencySingular" : "cruceiro brasileño", "BRZ_currencySymbol" : "BRR", "BSD_currencyISO" : "dólar de las Bahamas", "BSD_currencyPlural" : "dólares de las Bahamas", "BSD_currencySingular" : "dólar de las Bahamas", "BSD_currencySymbol" : "BS$", "BTN_currencyISO" : "ngultrum butanés", "BTN_currencyPlural" : "ngultrum butaneses", "BTN_currencySingular" : "ngultrum butanés", "BTN_currencySymbol" : "Nu.", "BUK_currencyISO" : "kyat birmano", "BUK_currencyPlural" : "kyat birmanos", "BUK_currencySingular" : "kyat birmano", "BUK_currencySymbol" : "BUK", "BWP_currencyISO" : "pula botsuano", "BWP_currencyPlural" : "pula botsuanas", "BWP_currencySingular" : "pula botsuana", "BWP_currencySymbol" : "BWP", "BYB_currencyISO" : "nuevo rublo bielorruso (1994-1999)", "BYB_currencyPlural" : "nuevos rublos bielorrusos", "BYB_currencySingular" : "nuevo rublo bielorruso", "BYB_currencySymbol" : "BYB", "BYR_currencyISO" : "rublo bielorruso", "BYR_currencyPlural" : "rublos bielorrusos", "BYR_currencySingular" : "rublo bielorruso", "BYR_currencySymbol" : "BYR", "BZD_currencyISO" : "dólar de Belice", "BZD_currencyPlural" : "dólares de Belice", "BZD_currencySingular" : "dólar de Belice", "BZD_currencySymbol" : "BZ$", "CAD_currencyISO" : "dólar canadiense", "CAD_currencyPlural" : "dólares canadienses", "CAD_currencySingular" : "dólar canadiense", "CAD_currencySymbol" : "CA$", "CDF_currencyISO" : "franco congoleño", "CDF_currencyPlural" : "francos congoleños", "CDF_currencySingular" : "franco congoleño", "CDF_currencySymbol" : "CDF", "CHE_currencyISO" : "euro WIR", "CHE_currencyPlural" : "euros WIR", "CHE_currencySingular" : "euro WIR", "CHE_currencySymbol" : "CHE", "CHF_currencyISO" : "franco suizo", "CHF_currencyPlural" : "francos suizos", "CHF_currencySingular" : "franco suizo", "CHF_currencySymbol" : "CHF", "CHW_currencyISO" : "franco WIR", "CHW_currencyPlural" : "francos WIR", "CHW_currencySingular" : "franco WIR", "CHW_currencySymbol" : "CHW", "CLE_currencyISO" : "CLE", "CLE_currencyPlural" : "francos WIR", "CLE_currencySingular" : "franco WIR", "CLE_currencySymbol" : "Eº", "CLF_currencyISO" : "unidad de fomento chilena", "CLF_currencyPlural" : "unidades de fomento chilenas", "CLF_currencySingular" : "unidad de fomento chilena", "CLF_currencySymbol" : "CLF", "CLP_currencyISO" : "peso chileno", "CLP_currencyPlural" : "pesos chilenos", "CLP_currencySingular" : "peso chileno", "CLP_currencySymbol" : "CL$", "CNX_currencyISO" : "peso chileno", "CNX_currencyPlural" : "pesos chilenos", "CNX_currencySingular" : "peso chileno", "CNX_currencySymbol" : "CL$", "CNY_currencyISO" : "yuan renminbi chino", "CNY_currencyPlural" : "pesos chilenos", "CNY_currencySingular" : "yuan renminbi chino", "CNY_currencySymbol" : "CN¥", "COP_currencyISO" : "peso colombiano", "COP_currencyPlural" : "pesos colombianos", "COP_currencySingular" : "peso colombiano", "COP_currencySymbol" : "CO$", "COU_currencyISO" : "unidad de valor real colombiana", "COU_currencyPlural" : "unidades de valor reales", "COU_currencySingular" : "unidad de valor real", "COU_currencySymbol" : "COU", "CRC_currencyISO" : "colón costarricense", "CRC_currencyPlural" : "colones costarricenses", "CRC_currencySingular" : "colón costarricense", "CRC_currencySymbol" : "₡", "CSD_currencyISO" : "antiguo dinar serbio", "CSD_currencyPlural" : "antiguos dinares serbios", "CSD_currencySingular" : "antiguo dinar serbio", "CSD_currencySymbol" : "CSD", "CSK_currencyISO" : "corona fuerte checoslovaca", "CSK_currencyPlural" : "coronas fuertes checoslovacas", "CSK_currencySingular" : "corona fuerte checoslovaca", "CSK_currencySymbol" : "CSK", "CUC_currencyISO" : "CUC", "CUC_currencyPlural" : "coronas fuertes checoslovacas", "CUC_currencySingular" : "corona fuerte checoslovaca", "CUC_currencySymbol" : "CUC$", "CUP_currencyISO" : "peso cubano", "CUP_currencyPlural" : "pesos cubanos", "CUP_currencySingular" : "peso cubano", "CUP_currencySymbol" : "CU$", "CVE_currencyISO" : "escudo de Cabo Verde", "CVE_currencyPlural" : "escudos de Cabo Verde", "CVE_currencySingular" : "escudo de Cabo Verde", "CVE_currencySymbol" : "CV$", "CYP_currencyISO" : "libra chipriota", "CYP_currencyPlural" : "libras chipriotas", "CYP_currencySingular" : "libra chipriota", "CYP_currencySymbol" : "CY£", "CZK_currencyISO" : "corona checa", "CZK_currencyPlural" : "coronas checas", "CZK_currencySingular" : "corona checa", "CZK_currencySymbol" : "Kč", "DDM_currencyISO" : "ostmark de Alemania del Este", "DDM_currencyPlural" : "marcos de la República Democrática Alemana", "DDM_currencySingular" : "marco de la República Democrática Alemana", "DDM_currencySymbol" : "DDM", "DEM_currencyISO" : "marco alemán", "DEM_currencyPlural" : "marcos alemanes", "DEM_currencySingular" : "marco alemán", "DEM_currencySymbol" : "DM", "DJF_currencyISO" : "franco de Yibuti", "DJF_currencyPlural" : "marcos alemanes", "DJF_currencySingular" : "marco alemán", "DJF_currencySymbol" : "Fdj", "DKK_currencyISO" : "corona danesa", "DKK_currencyPlural" : "coronas danesas", "DKK_currencySingular" : "corona danesa", "DKK_currencySymbol" : "Dkr", "DOP_currencyISO" : "peso dominicano", "DOP_currencyPlural" : "pesos dominicanos", "DOP_currencySingular" : "peso dominicano", "DOP_currencySymbol" : "RD$", "DZD_currencyISO" : "dinar argelino", "DZD_currencyPlural" : "dinares argelinos", "DZD_currencySingular" : "dinar argelino", "DZD_currencySymbol" : "DA", "ECS_currencyISO" : "sucre ecuatoriano", "ECS_currencyPlural" : "sucres ecuatorianos", "ECS_currencySingular" : "sucre ecuatoriano", "ECS_currencySymbol" : "ECS", "ECV_currencyISO" : "unidad de valor constante (UVC) ecuatoriana", "ECV_currencyPlural" : "unidades de valor constante (UVC) ecuatorianas", "ECV_currencySingular" : "unidad de valor constante (UVC) ecuatoriana", "ECV_currencySymbol" : "ECV", "EEK_currencyISO" : "corona estonia", "EEK_currencyPlural" : "coronas estonias", "EEK_currencySingular" : "corona estonia", "EEK_currencySymbol" : "Ekr", "EGP_currencyISO" : "libra egipcia", "EGP_currencyPlural" : "libras egipcias", "EGP_currencySingular" : "libra egipcia", "EGP_currencySymbol" : "EG£", "ERN_currencyISO" : "nakfa eritreo", "ERN_currencyPlural" : "libras egipcias", "ERN_currencySingular" : "libra egipcia", "ERN_currencySymbol" : "Nfk", "ESA_currencyISO" : "peseta española (cuenta A)", "ESA_currencyPlural" : "pesetas españolas (cuenta A)", "ESA_currencySingular" : "peseta española (cuenta A)", "ESA_currencySymbol" : "ESA", "ESB_currencyISO" : "peseta española (cuenta convertible)", "ESB_currencyPlural" : "pesetas españolas (cuenta convertible)", "ESB_currencySingular" : "peseta española (cuenta convertible)", "ESB_currencySymbol" : "ESB", "ESP_currencyISO" : "peseta española", "ESP_currencyPlural" : "pesetas españolas", "ESP_currencySingular" : "peseta española", "ESP_currencySymbol" : "₧", "ETB_currencyISO" : "birr etíope", "ETB_currencyPlural" : "pesetas españolas", "ETB_currencySingular" : "peseta española", "ETB_currencySymbol" : "Br", "EUR_currencyISO" : "euro", "EUR_currencyPlural" : "euros", "EUR_currencySingular" : "euro", "EUR_currencySymbol" : "€", "FIM_currencyISO" : "marco finlandés", "FIM_currencyPlural" : "marcos finlandeses", "FIM_currencySingular" : "marco finlandés", "FIM_currencySymbol" : "mk", "FJD_currencyISO" : "dólar de las Islas Fiyi", "FJD_currencyPlural" : "marcos finlandeses", "FJD_currencySingular" : "marco finlandés", "FJD_currencySymbol" : "FJ$", "FKP_currencyISO" : "libra de las Islas Malvinas", "FKP_currencyPlural" : "libras de las Islas Malvinas", "FKP_currencySingular" : "libra de las Islas Malvinas", "FKP_currencySymbol" : "FK£", "FRF_currencyISO" : "franco francés", "FRF_currencyPlural" : "francos franceses", "FRF_currencySingular" : "franco francés", "FRF_currencySymbol" : "₣", "GBP_currencyISO" : "libra esterlina británica", "GBP_currencyPlural" : "libras esterlinas británicas", "GBP_currencySingular" : "libra esterlina británica", "GBP_currencySymbol" : "£", "GEK_currencyISO" : "kupon larit georgiano", "GEK_currencyPlural" : "libras esterlinas británicas", "GEK_currencySingular" : "libra esterlina británica", "GEK_currencySymbol" : "GEK", "GEL_currencyISO" : "lari georgiano", "GEL_currencyPlural" : "libras esterlinas británicas", "GEL_currencySingular" : "libra esterlina británica", "GEL_currencySymbol" : "GEL", "GHC_currencyISO" : "cedi ghanés (1979-2007)", "GHC_currencyPlural" : "libras esterlinas británicas", "GHC_currencySingular" : "libra esterlina británica", "GHC_currencySymbol" : "₵", "GHS_currencyISO" : "GHS", "GHS_currencyPlural" : "libras esterlinas británicas", "GHS_currencySingular" : "libra esterlina británica", "GHS_currencySymbol" : "GH₵", "GIP_currencyISO" : "libra de Gibraltar", "GIP_currencyPlural" : "libras gibraltareñas", "GIP_currencySingular" : "libra gibraltareña", "GIP_currencySymbol" : "GI£", "GMD_currencyISO" : "dalasi gambiano", "GMD_currencyPlural" : "libras gibraltareñas", "GMD_currencySingular" : "libra gibraltareña", "GMD_currencySymbol" : "GMD", "GNF_currencyISO" : "franco guineano", "GNF_currencyPlural" : "francos guineanos", "GNF_currencySingular" : "franco guineano", "GNF_currencySymbol" : "FG", "GNS_currencyISO" : "syli guineano", "GNS_currencyPlural" : "francos guineanos", "GNS_currencySingular" : "franco guineano", "GNS_currencySymbol" : "GNS", "GQE_currencyISO" : "ekuele de Guinea Ecuatorial", "GQE_currencyPlural" : "ekueles de Guinea Ecuatorial", "GQE_currencySingular" : "ekuele de Guinea Ecuatorial", "GQE_currencySymbol" : "GQE", "GRD_currencyISO" : "dracma griego", "GRD_currencyPlural" : "dracmas griegos", "GRD_currencySingular" : "dracma griego", "GRD_currencySymbol" : "₯", "GTQ_currencyISO" : "quetzal guatemalteco", "GTQ_currencyPlural" : "quetzales guatemaltecos", "GTQ_currencySingular" : "quetzal guatemalteco", "GTQ_currencySymbol" : "GTQ", "GWE_currencyISO" : "escudo de Guinea Portuguesa", "GWE_currencyPlural" : "quetzales guatemaltecos", "GWE_currencySingular" : "quetzal guatemalteco", "GWE_currencySymbol" : "GWE", "GWP_currencyISO" : "peso de Guinea-Bissáu", "GWP_currencyPlural" : "quetzales guatemaltecos", "GWP_currencySingular" : "quetzal guatemalteco", "GWP_currencySymbol" : "GWP", "GYD_currencyISO" : "dólar guyanés", "GYD_currencyPlural" : "quetzales guatemaltecos", "GYD_currencySingular" : "quetzal guatemalteco", "GYD_currencySymbol" : "GY$", "HKD_currencyISO" : "dólar de Hong Kong", "HKD_currencyPlural" : "dólares de Hong Kong", "HKD_currencySingular" : "dólar de Hong Kong", "HKD_currencySymbol" : "HK$", "HNL_currencyISO" : "lempira hondureño", "HNL_currencyPlural" : "lempiras hondureños", "HNL_currencySingular" : "lempira hondureño", "HNL_currencySymbol" : "HNL", "HRD_currencyISO" : "dinar croata", "HRD_currencyPlural" : "dinares croatas", "HRD_currencySingular" : "dinar croata", "HRD_currencySymbol" : "HRD", "HRK_currencyISO" : "kuna croata", "HRK_currencyPlural" : "kunas croatas", "HRK_currencySingular" : "kuna croata", "HRK_currencySymbol" : "kn", "HTG_currencyISO" : "gourde haitiano", "HTG_currencyPlural" : "kunas croatas", "HTG_currencySingular" : "kuna croata", "HTG_currencySymbol" : "HTG", "HUF_currencyISO" : "florín húngaro", "HUF_currencyPlural" : "florines húngaros", "HUF_currencySingular" : "florín húngaro", "HUF_currencySymbol" : "Ft", "IDR_currencyISO" : "rupia indonesia", "IDR_currencyPlural" : "rupias indonesias", "IDR_currencySingular" : "rupia indonesia", "IDR_currencySymbol" : "Rp", "IEP_currencyISO" : "libra irlandesa", "IEP_currencyPlural" : "libras irlandesas", "IEP_currencySingular" : "libra irlandesa", "IEP_currencySymbol" : "IR£", "ILP_currencyISO" : "libra israelí", "ILP_currencyPlural" : "libras israelíes", "ILP_currencySingular" : "libra israelí", "ILP_currencySymbol" : "I£", "ILR_currencyISO" : "libra israelí", "ILR_currencyPlural" : "libras israelíes", "ILR_currencySingular" : "libra israelí", "ILR_currencySymbol" : "I£", "ILS_currencyISO" : "nuevo sheqel israelí", "ILS_currencyPlural" : "libras israelíes", "ILS_currencySingular" : "libra israelí", "ILS_currencySymbol" : "₪", "INR_currencyISO" : "rupia india", "INR_currencyPlural" : "rupias indias", "INR_currencySingular" : "rupia india", "INR_currencySymbol" : "Rs", "IQD_currencyISO" : "dinar iraquí", "IQD_currencyPlural" : "dinares iraquíes", "IQD_currencySingular" : "dinar iraquí", "IQD_currencySymbol" : "IQD", "IRR_currencyISO" : "rial iraní", "IRR_currencyPlural" : "dinares iraquíes", "IRR_currencySingular" : "dinar iraquí", "IRR_currencySymbol" : "IRR", "ISJ_currencyISO" : "rial iraní", "ISJ_currencyPlural" : "dinares iraquíes", "ISJ_currencySingular" : "dinar iraquí", "ISJ_currencySymbol" : "IRR", "ISK_currencyISO" : "corona islandesa", "ISK_currencyPlural" : "coronas islandesas", "ISK_currencySingular" : "corona islandesa", "ISK_currencySymbol" : "Ikr", "ITL_currencyISO" : "lira italiana", "ITL_currencyPlural" : "liras italianas", "ITL_currencySingular" : "lira italiana", "ITL_currencySymbol" : "IT₤", "JMD_currencyISO" : "dólar de Jamaica", "JMD_currencyPlural" : "dólares de Jamaica", "JMD_currencySingular" : "dólar de Jamaica", "JMD_currencySymbol" : "J$", "JOD_currencyISO" : "dinar jordano", "JOD_currencyPlural" : "dinares jordanos", "JOD_currencySingular" : "dinar jordano", "JOD_currencySymbol" : "JD", "JPY_currencyISO" : "yen japonés", "JPY_currencyPlural" : "yenes japoneses", "JPY_currencySingular" : "yen japonés", "JPY_currencySymbol" : "JP¥", "KES_currencyISO" : "chelín keniata", "KES_currencyPlural" : "yenes japoneses", "KES_currencySingular" : "yen japonés", "KES_currencySymbol" : "Ksh", "KGS_currencyISO" : "som kirguís", "KGS_currencyPlural" : "yenes japoneses", "KGS_currencySingular" : "yen japonés", "KGS_currencySymbol" : "KGS", "KHR_currencyISO" : "riel camboyano", "KHR_currencyPlural" : "yenes japoneses", "KHR_currencySingular" : "yen japonés", "KHR_currencySymbol" : "KHR", "KMF_currencyISO" : "franco comorense", "KMF_currencyPlural" : "yenes japoneses", "KMF_currencySingular" : "yen japonés", "KMF_currencySymbol" : "CF", "KPW_currencyISO" : "won norcoreano", "KPW_currencyPlural" : "yenes japoneses", "KPW_currencySingular" : "yen japonés", "KPW_currencySymbol" : "KPW", "KRH_currencyISO" : "won norcoreano", "KRH_currencyPlural" : "yenes japoneses", "KRH_currencySingular" : "yen japonés", "KRH_currencySymbol" : "KPW", "KRO_currencyISO" : "won norcoreano", "KRO_currencyPlural" : "yenes japoneses", "KRO_currencySingular" : "yen japonés", "KRO_currencySymbol" : "KPW", "KRW_currencyISO" : "won surcoreano", "KRW_currencyPlural" : "yenes japoneses", "KRW_currencySingular" : "yen japonés", "KRW_currencySymbol" : "₩", "KWD_currencyISO" : "dinar kuwaití", "KWD_currencyPlural" : "yenes japoneses", "KWD_currencySingular" : "yen japonés", "KWD_currencySymbol" : "KD", "KYD_currencyISO" : "dólar de las Islas Caimán", "KYD_currencyPlural" : "dólares de las Islas Caimán", "KYD_currencySingular" : "dólar de las Islas Caimán", "KYD_currencySymbol" : "KY$", "KZT_currencyISO" : "tenge kazako", "KZT_currencyPlural" : "dólares de las Islas Caimán", "KZT_currencySingular" : "dólar de las Islas Caimán", "KZT_currencySymbol" : "KZT", "LAK_currencyISO" : "kip laosiano", "LAK_currencyPlural" : "dólares de las Islas Caimán", "LAK_currencySingular" : "dólar de las Islas Caimán", "LAK_currencySymbol" : "₭", "LBP_currencyISO" : "libra libanesa", "LBP_currencyPlural" : "libras libanesas", "LBP_currencySingular" : "libra libanesa", "LBP_currencySymbol" : "LB£", "LKR_currencyISO" : "rupia de Sri Lanka", "LKR_currencyPlural" : "rupias de Sri Lanka", "LKR_currencySingular" : "rupia de Sri Lanka", "LKR_currencySymbol" : "SLRs", "LRD_currencyISO" : "dólar liberiano", "LRD_currencyPlural" : "dólares liberianos", "LRD_currencySingular" : "dólar liberiano", "LRD_currencySymbol" : "L$", "LSL_currencyISO" : "loti lesothense", "LSL_currencyPlural" : "dólares liberianos", "LSL_currencySingular" : "dólar liberiano", "LSL_currencySymbol" : "LSL", "LTL_currencyISO" : "litas lituano", "LTL_currencyPlural" : "litas lituanas", "LTL_currencySingular" : "litas lituana", "LTL_currencySymbol" : "Lt", "LTT_currencyISO" : "talonas lituano", "LTT_currencyPlural" : "talonas lituanas", "LTT_currencySingular" : "talonas lituana", "LTT_currencySymbol" : "LTT", "LUC_currencyISO" : "franco convertible luxemburgués", "LUC_currencyPlural" : "francos convertibles luxemburgueses", "LUC_currencySingular" : "franco convertible luxemburgués", "LUC_currencySymbol" : "LUC", "LUF_currencyISO" : "franco luxemburgués", "LUF_currencyPlural" : "francos luxemburgueses", "LUF_currencySingular" : "franco luxemburgués", "LUF_currencySymbol" : "LUF", "LUL_currencyISO" : "franco financiero luxemburgués", "LUL_currencyPlural" : "francos financieros luxemburgueses", "LUL_currencySingular" : "franco financiero luxemburgués", "LUL_currencySymbol" : "LUL", "LVL_currencyISO" : "lats letón", "LVL_currencyPlural" : "lats letones", "LVL_currencySingular" : "lats letón", "LVL_currencySymbol" : "Ls", "LVR_currencyISO" : "rublo letón", "LVR_currencyPlural" : "rublos letones", "LVR_currencySingular" : "rublo letón", "LVR_currencySymbol" : "LVR", "LYD_currencyISO" : "dinar libio", "LYD_currencyPlural" : "dinares libios", "LYD_currencySingular" : "dinar libio", "LYD_currencySymbol" : "LD", "MAD_currencyISO" : "dirham marroquí", "MAD_currencyPlural" : "dirhams marroquíes", "MAD_currencySingular" : "dirham marroquí", "MAD_currencySymbol" : "MAD", "MAF_currencyISO" : "franco marroquí", "MAF_currencyPlural" : "francos marroquíes", "MAF_currencySingular" : "franco marroquí", "MAF_currencySymbol" : "MAF", "MCF_currencyISO" : "franco marroquí", "MCF_currencyPlural" : "francos marroquíes", "MCF_currencySingular" : "franco marroquí", "MCF_currencySymbol" : "MAF", "MDC_currencyISO" : "franco marroquí", "MDC_currencyPlural" : "francos marroquíes", "MDC_currencySingular" : "franco marroquí", "MDC_currencySymbol" : "MAF", "MDL_currencyISO" : "leu moldavo", "MDL_currencyPlural" : "francos marroquíes", "MDL_currencySingular" : "franco marroquí", "MDL_currencySymbol" : "MDL", "MGA_currencyISO" : "ariary malgache", "MGA_currencyPlural" : "francos marroquíes", "MGA_currencySingular" : "franco marroquí", "MGA_currencySymbol" : "MGA", "MGF_currencyISO" : "franco malgache", "MGF_currencyPlural" : "francos marroquíes", "MGF_currencySingular" : "franco marroquí", "MGF_currencySymbol" : "MGF", "MKD_currencyISO" : "dinar macedonio", "MKD_currencyPlural" : "dinares macedonios", "MKD_currencySingular" : "dinar macedonio", "MKD_currencySymbol" : "MKD", "MKN_currencyISO" : "dinar macedonio", "MKN_currencyPlural" : "dinares macedonios", "MKN_currencySingular" : "dinar macedonio", "MKN_currencySymbol" : "MKD", "MLF_currencyISO" : "franco malí", "MLF_currencyPlural" : "dinares macedonios", "MLF_currencySingular" : "dinar macedonio", "MLF_currencySymbol" : "MLF", "MMK_currencyISO" : "kyat de Myanmar", "MMK_currencyPlural" : "dinares macedonios", "MMK_currencySingular" : "dinar macedonio", "MMK_currencySymbol" : "MMK", "MNT_currencyISO" : "tugrik mongol", "MNT_currencyPlural" : "dinares macedonios", "MNT_currencySingular" : "dinar macedonio", "MNT_currencySymbol" : "₮", "MOP_currencyISO" : "pataca de Macao", "MOP_currencyPlural" : "dinares macedonios", "MOP_currencySingular" : "dinar macedonio", "MOP_currencySymbol" : "MOP$", "MRO_currencyISO" : "ouguiya mauritano", "MRO_currencyPlural" : "dinares macedonios", "MRO_currencySingular" : "dinar macedonio", "MRO_currencySymbol" : "UM", "MTL_currencyISO" : "lira maltesa", "MTL_currencyPlural" : "liras maltesas", "MTL_currencySingular" : "lira maltesa", "MTL_currencySymbol" : "Lm", "MTP_currencyISO" : "libra maltesa", "MTP_currencyPlural" : "libras maltesas", "MTP_currencySingular" : "libra maltesa", "MTP_currencySymbol" : "MT£", "MUR_currencyISO" : "rupia mauriciana", "MUR_currencyPlural" : "libras maltesas", "MUR_currencySingular" : "libra maltesa", "MUR_currencySymbol" : "MURs", "MVP_currencyISO" : "rupia mauriciana", "MVP_currencyPlural" : "libras maltesas", "MVP_currencySingular" : "libra maltesa", "MVP_currencySymbol" : "MURs", "MVR_currencyISO" : "rufiyaa de Maldivas", "MVR_currencyPlural" : "libras maltesas", "MVR_currencySingular" : "libra maltesa", "MVR_currencySymbol" : "MVR", "MWK_currencyISO" : "kwacha de Malawi", "MWK_currencyPlural" : "libras maltesas", "MWK_currencySingular" : "libra maltesa", "MWK_currencySymbol" : "MWK", "MXN_currencyISO" : "peso mexicano", "MXN_currencyPlural" : "pesos mexicanos", "MXN_currencySingular" : "peso mexicano", "MXN_currencySymbol" : "MX$", "MXP_currencyISO" : "peso de plata mexicano (1861-1992)", "MXP_currencyPlural" : "pesos de plata mexicanos (MXP)", "MXP_currencySingular" : "peso de plata mexicano (MXP)", "MXP_currencySymbol" : "MXP", "MXV_currencyISO" : "unidad de inversión (UDI) mexicana", "MXV_currencyPlural" : "unidades de inversión (UDI) mexicanas", "MXV_currencySingular" : "unidad de inversión (UDI) mexicana", "MXV_currencySymbol" : "MXV", "MYR_currencyISO" : "ringgit malasio", "MYR_currencyPlural" : "unidades de inversión (UDI) mexicanas", "MYR_currencySingular" : "unidad de inversión (UDI) mexicana", "MYR_currencySymbol" : "RM", "MZE_currencyISO" : "escudo mozambiqueño", "MZE_currencyPlural" : "escudos mozambiqueños", "MZE_currencySingular" : "escudo mozambiqueño", "MZE_currencySymbol" : "MZE", "MZM_currencyISO" : "antiguo metical mozambiqueño", "MZM_currencyPlural" : "escudos mozambiqueños", "MZM_currencySingular" : "escudo mozambiqueño", "MZM_currencySymbol" : "Mt", "MZN_currencyISO" : "metical mozambiqueño", "MZN_currencyPlural" : "escudos mozambiqueños", "MZN_currencySingular" : "escudo mozambiqueño", "MZN_currencySymbol" : "MTn", "NAD_currencyISO" : "dólar de Namibia", "NAD_currencyPlural" : "escudos mozambiqueños", "NAD_currencySingular" : "escudo mozambiqueño", "NAD_currencySymbol" : "N$", "NGN_currencyISO" : "naira nigeriano", "NGN_currencyPlural" : "escudos mozambiqueños", "NGN_currencySingular" : "escudo mozambiqueño", "NGN_currencySymbol" : "₦", "NIC_currencyISO" : "córdoba nicaragüense", "NIC_currencyPlural" : "córdobas nicaragüenses", "NIC_currencySingular" : "córdoba nicaragüense", "NIC_currencySymbol" : "NIC", "NIO_currencyISO" : "córdoba oro nicaragüense", "NIO_currencyPlural" : "córdobas oro nicaragüenses", "NIO_currencySingular" : "córdoba oro nicaragüense", "NIO_currencySymbol" : "C$", "NLG_currencyISO" : "florín neerlandés", "NLG_currencyPlural" : "florines neerlandeses", "NLG_currencySingular" : "florín neerlandés", "NLG_currencySymbol" : "fl", "NOK_currencyISO" : "corona noruega", "NOK_currencyPlural" : "coronas noruegas", "NOK_currencySingular" : "corona noruega", "NOK_currencySymbol" : "Nkr", "NPR_currencyISO" : "rupia nepalesa", "NPR_currencyPlural" : "rupias nepalesas", "NPR_currencySingular" : "rupia nepalesa", "NPR_currencySymbol" : "NPRs", "NZD_currencyISO" : "dólar neozelandés", "NZD_currencyPlural" : "dólares neozelandeses", "NZD_currencySingular" : "dólar neozelandés", "NZD_currencySymbol" : "NZ$", "OMR_currencyISO" : "rial omaní", "OMR_currencyPlural" : "dólares neozelandeses", "OMR_currencySingular" : "dólar neozelandés", "OMR_currencySymbol" : "OMR", "PAB_currencyISO" : "balboa panameño", "PAB_currencyPlural" : "balboas panameños", "PAB_currencySingular" : "balboa panameño", "PAB_currencySymbol" : "B/.", "PEI_currencyISO" : "inti peruano", "PEI_currencyPlural" : "intis peruanos", "PEI_currencySingular" : "inti peruano", "PEI_currencySymbol" : "I/.", "PEN_currencyISO" : "nuevo sol peruano", "PEN_currencyPlural" : "nuevos soles peruanos", "PEN_currencySingular" : "nuevo sol peruano", "PEN_currencySymbol" : "S/.", "PES_currencyISO" : "sol peruano", "PES_currencyPlural" : "soles peruanos", "PES_currencySingular" : "sol peruano", "PES_currencySymbol" : "PES", "PGK_currencyISO" : "kina de Papúa Nueva Guinea", "PGK_currencyPlural" : "soles peruanos", "PGK_currencySingular" : "sol peruano", "PGK_currencySymbol" : "PGK", "PHP_currencyISO" : "peso filipino", "PHP_currencyPlural" : "pesos filipinos", "PHP_currencySingular" : "peso filipino", "PHP_currencySymbol" : "₱", "PKR_currencyISO" : "rupia pakistaní", "PKR_currencyPlural" : "pesos filipinos", "PKR_currencySingular" : "peso filipino", "PKR_currencySymbol" : "PKRs", "PLN_currencyISO" : "zloty polaco", "PLN_currencyPlural" : "zlotys polacos", "PLN_currencySingular" : "zloty polaco", "PLN_currencySymbol" : "zł", "PLZ_currencyISO" : "zloty polaco (1950-1995)", "PLZ_currencyPlural" : "zlotys polacos (PLZ)", "PLZ_currencySingular" : "zloty polaco (PLZ)", "PLZ_currencySymbol" : "PLZ", "PTE_currencyISO" : "escudo portugués", "PTE_currencyPlural" : "escudos portugueses", "PTE_currencySingular" : "escudo portugués", "PTE_currencySymbol" : "Esc", "PYG_currencyISO" : "guaraní paraguayo", "PYG_currencyPlural" : "guaraníes paraguayos", "PYG_currencySingular" : "guaraní paraguayo", "PYG_currencySymbol" : "₲", "QAR_currencyISO" : "riyal de Qatar", "QAR_currencyPlural" : "guaraníes paraguayos", "QAR_currencySingular" : "guaraní paraguayo", "QAR_currencySymbol" : "QR", "RHD_currencyISO" : "dólar rodesiano", "RHD_currencyPlural" : "guaraníes paraguayos", "RHD_currencySingular" : "guaraní paraguayo", "RHD_currencySymbol" : "RH$", "ROL_currencyISO" : "antiguo leu rumano", "ROL_currencyPlural" : "antiguos lei rumanos", "ROL_currencySingular" : "antiguo leu rumano", "ROL_currencySymbol" : "ROL", "RON_currencyISO" : "leu rumano", "RON_currencyPlural" : "lei rumanos", "RON_currencySingular" : "leu rumano", "RON_currencySymbol" : "RON", "RSD_currencyISO" : "dinar serbio", "RSD_currencyPlural" : "dinares serbios", "RSD_currencySingular" : "dinar serbio", "RSD_currencySymbol" : "din.", "RUB_currencyISO" : "rublo ruso", "RUB_currencyPlural" : "rublos rusos", "RUB_currencySingular" : "rublo ruso", "RUB_currencySymbol" : "RUB", "RUR_currencyISO" : "rublo ruso (1991-1998)", "RUR_currencyPlural" : "rublos rusos (RUR)", "RUR_currencySingular" : "rublo ruso (RUR)", "RUR_currencySymbol" : "RUR", "RWF_currencyISO" : "franco ruandés", "RWF_currencyPlural" : "francos ruandeses", "RWF_currencySingular" : "franco ruandés", "RWF_currencySymbol" : "RWF", "SAR_currencyISO" : "riyal saudí", "SAR_currencyPlural" : "francos ruandeses", "SAR_currencySingular" : "franco ruandés", "SAR_currencySymbol" : "SR", "SBD_currencyISO" : "dólar de las Islas Salomón", "SBD_currencyPlural" : "dólares de las Islas Salomón", "SBD_currencySingular" : "dólar de las Islas Salomón", "SBD_currencySymbol" : "SI$", "SCR_currencyISO" : "rupia de Seychelles", "SCR_currencyPlural" : "dólares de las Islas Salomón", "SCR_currencySingular" : "dólar de las Islas Salomón", "SCR_currencySymbol" : "SRe", "SDD_currencyISO" : "dinar sudanés", "SDD_currencyPlural" : "dinares sudaneses", "SDD_currencySingular" : "dinar sudanés", "SDD_currencySymbol" : "LSd", "SDG_currencyISO" : "libra sudanesa", "SDG_currencyPlural" : "libras sudanesas", "SDG_currencySingular" : "libra sudanesa", "SDG_currencySymbol" : "SDG", "SDP_currencyISO" : "libra sudanesa antigua", "SDP_currencyPlural" : "libras sudanesas antiguas", "SDP_currencySingular" : "libra sudanesa antigua", "SDP_currencySymbol" : "SDP", "SEK_currencyISO" : "corona sueca", "SEK_currencyPlural" : "coronas suecas", "SEK_currencySingular" : "corona sueca", "SEK_currencySymbol" : "Skr", "SGD_currencyISO" : "dólar singapurense", "SGD_currencyPlural" : "coronas suecas", "SGD_currencySingular" : "corona sueca", "SGD_currencySymbol" : "S$", "SHP_currencyISO" : "libra de Santa Elena", "SHP_currencyPlural" : "libras de Santa Elena", "SHP_currencySingular" : "libra de Santa Elena", "SHP_currencySymbol" : "SH£", "SIT_currencyISO" : "tólar esloveno", "SIT_currencyPlural" : "tólares eslovenos", "SIT_currencySingular" : "tólar esloveno", "SIT_currencySymbol" : "SIT", "SKK_currencyISO" : "corona eslovaca", "SKK_currencyPlural" : "coronas eslovacas", "SKK_currencySingular" : "corona eslovaca", "SKK_currencySymbol" : "Sk", "SLL_currencyISO" : "leone de Sierra Leona", "SLL_currencyPlural" : "coronas eslovacas", "SLL_currencySingular" : "corona eslovaca", "SLL_currencySymbol" : "Le", "SOS_currencyISO" : "chelín somalí", "SOS_currencyPlural" : "chelines somalíes", "SOS_currencySingular" : "chelín somalí", "SOS_currencySymbol" : "Ssh", "SRD_currencyISO" : "dólar surinamés", "SRD_currencyPlural" : "chelines somalíes", "SRD_currencySingular" : "chelín somalí", "SRD_currencySymbol" : "SR$", "SRG_currencyISO" : "florín surinamés", "SRG_currencyPlural" : "chelines somalíes", "SRG_currencySingular" : "chelín somalí", "SRG_currencySymbol" : "Sf", "SSP_currencyISO" : "florín surinamés", "SSP_currencyPlural" : "chelines somalíes", "SSP_currencySingular" : "chelín somalí", "SSP_currencySymbol" : "Sf", "STD_currencyISO" : "dobra de Santo Tomé y Príncipe", "STD_currencyPlural" : "chelines somalíes", "STD_currencySingular" : "chelín somalí", "STD_currencySymbol" : "Db", "SUR_currencyISO" : "rublo soviético", "SUR_currencyPlural" : "rublos soviéticos", "SUR_currencySingular" : "rublo soviético", "SUR_currencySymbol" : "SUR", "SVC_currencyISO" : "colón salvadoreño", "SVC_currencyPlural" : "colones salvadoreños", "SVC_currencySingular" : "colón salvadoreño", "SVC_currencySymbol" : "SV₡", "SYP_currencyISO" : "libra siria", "SYP_currencyPlural" : "libras sirias", "SYP_currencySingular" : "libra siria", "SYP_currencySymbol" : "SY£", "SZL_currencyISO" : "lilangeni suazi", "SZL_currencyPlural" : "libras sirias", "SZL_currencySingular" : "libra siria", "SZL_currencySymbol" : "SZL", "THB_currencyISO" : "baht tailandés", "THB_currencyPlural" : "libras sirias", "THB_currencySingular" : "libra siria", "THB_currencySymbol" : "฿", "TJR_currencyISO" : "rublo tayiko", "TJR_currencyPlural" : "libras sirias", "TJR_currencySingular" : "libra siria", "TJR_currencySymbol" : "TJR", "TJS_currencyISO" : "somoni tayiko", "TJS_currencyPlural" : "libras sirias", "TJS_currencySingular" : "libra siria", "TJS_currencySymbol" : "TJS", "TMM_currencyISO" : "manat turcomano", "TMM_currencyPlural" : "libras sirias", "TMM_currencySingular" : "libra siria", "TMM_currencySymbol" : "TMM", "TMT_currencyISO" : "manat turcomano", "TMT_currencyPlural" : "libras sirias", "TMT_currencySingular" : "libra siria", "TMT_currencySymbol" : "TMM", "TND_currencyISO" : "dinar tunecino", "TND_currencyPlural" : "libras sirias", "TND_currencySingular" : "libra siria", "TND_currencySymbol" : "DT", "TOP_currencyISO" : "paʻanga tongano", "TOP_currencyPlural" : "libras sirias", "TOP_currencySingular" : "libra siria", "TOP_currencySymbol" : "T$", "TPE_currencyISO" : "escudo timorense", "TPE_currencyPlural" : "libras sirias", "TPE_currencySingular" : "libra siria", "TPE_currencySymbol" : "TPE", "TRL_currencyISO" : "lira turca antigua", "TRL_currencyPlural" : "liras turcas antiguas", "TRL_currencySingular" : "lira turca antigua", "TRL_currencySymbol" : "TRL", "TRY_currencyISO" : "nueva lira turca", "TRY_currencyPlural" : "liras turcas", "TRY_currencySingular" : "lira turca", "TRY_currencySymbol" : "TL", "TTD_currencyISO" : "dólar de Trinidad y Tobago", "TTD_currencyPlural" : "liras turcas", "TTD_currencySingular" : "lira turca", "TTD_currencySymbol" : "TT$", "TWD_currencyISO" : "nuevo dólar taiwanés", "TWD_currencyPlural" : "liras turcas", "TWD_currencySingular" : "lira turca", "TWD_currencySymbol" : "NT$", "TZS_currencyISO" : "chelín tanzano", "TZS_currencyPlural" : "liras turcas", "TZS_currencySingular" : "lira turca", "TZS_currencySymbol" : "TSh", "UAH_currencyISO" : "grivna ucraniana", "UAH_currencyPlural" : "grivnias ucranianas", "UAH_currencySingular" : "grivnia ucraniana", "UAH_currencySymbol" : "₴", "UAK_currencyISO" : "karbovanet ucraniano", "UAK_currencyPlural" : "karbovanets ucranianos", "UAK_currencySingular" : "karbovanet ucraniano", "UAK_currencySymbol" : "UAK", "UGS_currencyISO" : "chelín ugandés (1966-1987)", "UGS_currencyPlural" : "karbovanets ucranianos", "UGS_currencySingular" : "karbovanet ucraniano", "UGS_currencySymbol" : "UGS", "UGX_currencyISO" : "chelín ugandés", "UGX_currencyPlural" : "chelines ugandeses", "UGX_currencySingular" : "chelín ugandés", "UGX_currencySymbol" : "USh", "USD_currencyISO" : "dólar estadounidense", "USD_currencyPlural" : "dólares estadounidenses", "USD_currencySingular" : "dólar estadounidense", "USD_currencySymbol" : "US$", "USN_currencyISO" : "dólar estadounidense (día siguiente)", "USN_currencyPlural" : "dólares estadounidenses (día siguiente)", "USN_currencySingular" : "dólar estadounidense (día siguiente)", "USN_currencySymbol" : "USN", "USS_currencyISO" : "dólar estadounidense (mismo día)", "USS_currencyPlural" : "dólares estadounidenses (mismo día)", "USS_currencySingular" : "dólar estadounidense (mismo día)", "USS_currencySymbol" : "USS", "UYI_currencyISO" : "peso uruguayo en unidades indexadas", "UYI_currencyPlural" : "pesos uruguayos en unidades indexadas", "UYI_currencySingular" : "peso uruguayo en unidades indexadas", "UYI_currencySymbol" : "UYI", "UYP_currencyISO" : "peso uruguayo (1975-1993)", "UYP_currencyPlural" : "pesos uruguayos (UYP)", "UYP_currencySingular" : "peso uruguayo (UYP)", "UYP_currencySymbol" : "UYP", "UYU_currencyISO" : "peso uruguayo", "UYU_currencyPlural" : "pesos uruguayos", "UYU_currencySingular" : "peso uruguayo", "UYU_currencySymbol" : "$", "UZS_currencyISO" : "sum uzbeko", "UZS_currencyPlural" : "pesos uruguayos", "UZS_currencySingular" : "peso uruguayo", "UZS_currencySymbol" : "UZS", "VEB_currencyISO" : "bolívar venezolano", "VEB_currencyPlural" : "bolívares venezolanos", "VEB_currencySingular" : "bolívar venezolano", "VEB_currencySymbol" : "VEB", "VEF_currencyISO" : "bolívar fuerte venezolano", "VEF_currencyPlural" : "bolívares fuertes venezolanos", "VEF_currencySingular" : "bolívar fuerte venezolano", "VEF_currencySymbol" : "Bs.F.", "VND_currencyISO" : "dong vietnamita", "VND_currencyPlural" : "bolívares fuertes venezolanos", "VND_currencySingular" : "bolívar fuerte venezolano", "VND_currencySymbol" : "₫", "VNN_currencyISO" : "dong vietnamita", "VNN_currencyPlural" : "bolívares fuertes venezolanos", "VNN_currencySingular" : "bolívar fuerte venezolano", "VNN_currencySymbol" : "₫", "VUV_currencyISO" : "vatu vanuatuense", "VUV_currencyPlural" : "bolívares fuertes venezolanos", "VUV_currencySingular" : "bolívar fuerte venezolano", "VUV_currencySymbol" : "VT", "WST_currencyISO" : "tala samoano", "WST_currencyPlural" : "bolívares fuertes venezolanos", "WST_currencySingular" : "bolívar fuerte venezolano", "WST_currencySymbol" : "WS$", "XAF_currencyISO" : "franco CFA BEAC", "XAF_currencyPlural" : "bolívares fuertes venezolanos", "XAF_currencySingular" : "bolívar fuerte venezolano", "XAF_currencySymbol" : "FCFA", "XAG_currencyISO" : "plata", "XAG_currencyPlural" : "plata", "XAG_currencySingular" : "plata", "XAG_currencySymbol" : "XAG", "XAU_currencyISO" : "oro", "XAU_currencyPlural" : "oro", "XAU_currencySingular" : "oro", "XAU_currencySymbol" : "XAU", "XBA_currencyISO" : "unidad compuesta europea", "XBA_currencyPlural" : "unidades compuestas europeas", "XBA_currencySingular" : "unidad compuesta europea", "XBA_currencySymbol" : "XBA", "XBB_currencyISO" : "unidad monetaria europea", "XBB_currencyPlural" : "unidades monetarias europeas", "XBB_currencySingular" : "unidad monetaria europea", "XBB_currencySymbol" : "XBB", "XBC_currencyISO" : "unidad de cuenta europea (XBC)", "XBC_currencyPlural" : "unidades de cuenta europeas (XBC)", "XBC_currencySingular" : "unidad de cuenta europea (XBC)", "XBC_currencySymbol" : "XBC", "XBD_currencyISO" : "unidad de cuenta europea (XBD)", "XBD_currencyPlural" : "unidades de cuenta europeas (XBD)", "XBD_currencySingular" : "unidad de cuenta europea (XBD)", "XBD_currencySymbol" : "XBD", "XCD_currencyISO" : "dólar del Caribe Oriental", "XCD_currencyPlural" : "dólares del Caribe Oriental", "XCD_currencySingular" : "dólar del Caribe Oriental", "XCD_currencySymbol" : "EC$", "XDR_currencyISO" : "derechos especiales de giro", "XDR_currencyPlural" : "dólares del Caribe Oriental", "XDR_currencySingular" : "dólar del Caribe Oriental", "XDR_currencySymbol" : "XDR", "XEU_currencyISO" : "unidad de moneda europea", "XEU_currencyPlural" : "unidades de moneda europeas", "XEU_currencySingular" : "unidad de moneda europea", "XEU_currencySymbol" : "XEU", "XFO_currencyISO" : "franco oro francés", "XFO_currencyPlural" : "francos oro franceses", "XFO_currencySingular" : "franco oro francés", "XFO_currencySymbol" : "XFO", "XFU_currencyISO" : "franco UIC francés", "XFU_currencyPlural" : "francos UIC franceses", "XFU_currencySingular" : "franco UIC francés", "XFU_currencySymbol" : "XFU", "XOF_currencyISO" : "franco CFA BCEAO", "XOF_currencyPlural" : "francos UIC franceses", "XOF_currencySingular" : "franco UIC francés", "XOF_currencySymbol" : "CFA", "XPD_currencyISO" : "paladio", "XPD_currencyPlural" : "paladio", "XPD_currencySingular" : "paladio", "XPD_currencySymbol" : "XPD", "XPF_currencyISO" : "franco CFP", "XPF_currencyPlural" : "paladio", "XPF_currencySingular" : "paladio", "XPF_currencySymbol" : "CFPF", "XPT_currencyISO" : "platino", "XPT_currencyPlural" : "platino", "XPT_currencySingular" : "platino", "XPT_currencySymbol" : "XPT", "XRE_currencyISO" : "fondos RINET", "XRE_currencyPlural" : "platino", "XRE_currencySingular" : "platino", "XRE_currencySymbol" : "XRE", "XSU_currencyISO" : "fondos RINET", "XSU_currencyPlural" : "platino", "XSU_currencySingular" : "platino", "XSU_currencySymbol" : "XRE", "XTS_currencyISO" : "código reservado para pruebas", "XTS_currencyPlural" : "platino", "XTS_currencySingular" : "platino", "XTS_currencySymbol" : "XTS", "XUA_currencyISO" : "código reservado para pruebas", "XUA_currencyPlural" : "platino", "XUA_currencySingular" : "platino", "XUA_currencySymbol" : "XTS", "XXX_currencyISO" : "Sin divisa", "XXX_currencyPlural" : "monedas desconocidas/no válidas", "XXX_currencySingular" : "moneda desconocida/no válida", "XXX_currencySymbol" : "XXX", "YDD_currencyISO" : "dinar yemení", "YDD_currencyPlural" : "monedas desconocidas/no válidas", "YDD_currencySingular" : "moneda desconocida/no válida", "YDD_currencySymbol" : "YDD", "YER_currencyISO" : "rial yemení", "YER_currencyPlural" : "monedas desconocidas/no válidas", "YER_currencySingular" : "moneda desconocida/no válida", "YER_currencySymbol" : "YR", "YUD_currencyISO" : "dinar fuerte yugoslavo", "YUD_currencyPlural" : "monedas desconocidas/no válidas", "YUD_currencySingular" : "moneda desconocida/no válida", "YUD_currencySymbol" : "YUD", "YUM_currencyISO" : "super dinar yugoslavo", "YUM_currencyPlural" : "monedas desconocidas/no válidas", "YUM_currencySingular" : "moneda desconocida/no válida", "YUM_currencySymbol" : "YUM", "YUN_currencyISO" : "dinar convertible yugoslavo", "YUN_currencyPlural" : "dinares convertibles yugoslavos", "YUN_currencySingular" : "dinar convertible yugoslavo", "YUN_currencySymbol" : "YUN", "YUR_currencyISO" : "dinar convertible yugoslavo", "YUR_currencyPlural" : "dinares convertibles yugoslavos", "YUR_currencySingular" : "dinar convertible yugoslavo", "YUR_currencySymbol" : "YUN", "ZAL_currencyISO" : "rand sudafricano (financiero)", "ZAL_currencyPlural" : "dinares convertibles yugoslavos", "ZAL_currencySingular" : "dinar convertible yugoslavo", "ZAL_currencySymbol" : "ZAL", "ZAR_currencyISO" : "rand sudafricano", "ZAR_currencyPlural" : "dinares convertibles yugoslavos", "ZAR_currencySingular" : "dinar convertible yugoslavo", "ZAR_currencySymbol" : "R", "ZMK_currencyISO" : "kwacha zambiano", "ZMK_currencyPlural" : "dinares convertibles yugoslavos", "ZMK_currencySingular" : "dinar convertible yugoslavo", "ZMK_currencySymbol" : "ZK", "ZRN_currencyISO" : "nuevo zaire zaireño", "ZRN_currencyPlural" : "dinares convertibles yugoslavos", "ZRN_currencySingular" : "dinar convertible yugoslavo", "ZRN_currencySymbol" : "NZ", "ZRZ_currencyISO" : "zaire zaireño", "ZRZ_currencyPlural" : "dinares convertibles yugoslavos", "ZRZ_currencySingular" : "dinar convertible yugoslavo", "ZRZ_currencySymbol" : "ZRZ", "ZWD_currencyISO" : "dólar de Zimbabue", "ZWD_currencyPlural" : "dinares convertibles yugoslavos", "ZWD_currencySingular" : "dinar convertible yugoslavo", "ZWD_currencySymbol" : "Z$", "ZWL_currencyISO" : "dólar de Zimbabue", "ZWL_currencyPlural" : "dinares convertibles yugoslavos", "ZWL_currencySingular" : "dinar convertible yugoslavo", "ZWL_currencySymbol" : "Z$", "ZWR_currencyISO" : "dólar de Zimbabue", "ZWR_currencyPlural" : "dinares convertibles yugoslavos", "ZWR_currencySingular" : "dinar convertible yugoslavo", "ZWR_currencySymbol" : "Z$", "currencyFormat" : "¤ #,##0.00;(¤ #,##0.00)", "currencyPatternPlural" : "e u", "currencyPatternSingular" : "{0} {1}", "decimalFormat" : "#,##0.###", "decimalSeparator" : ",", "defaultCurrency" : "UYU", "exponentialSymbol" : "E", "groupingSeparator" : ".", "infinitySign" : "∞", "minusSign" : "-", "nanSymbol" : "NaN", "numberZero" : "0", "perMilleSign" : "‰", "percentFormat" : "#,##0%", "percentSign" : "%", "plusSign" : "+", "scientificFormat" : "#E0" }
'use strict'; (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery', 'moment'], factory); } else if (typeof exports === 'object') { // Node/CommonJS module.exports = factory(require('jquery'), require('moment')); } else { // Browser globals root.Calendar = factory(jQuery, moment); } } (this, function ($, moment) { function Calendar(settings) { var self = this; this.calIsOpen = false; this.presetIsOpen = false; this.sameDayRange = settings.same_day_range || false; this.element = settings.element || $('.daterange'); this.selected = null; this.type = this.element.hasClass('daterange--single') ? 'single' : 'double'; this.format = settings.format || {}; this.format.input = settings.format && settings.format.input || 'MMMM D, YYYY'; this.format.preset = settings.format && settings.format.preset || 'll'; this.format.jump_month = settings.format && settings.format.jump_month || 'MMMM'; this.format.jump_year = settings.format && settings.format.jump_year || 'YYYY'; this.days_array = settings.days_array && settings.days_array.length == 7 ? settings.days_array : ['S','M','T','W','T','F','S']; this.earliest_date = settings.earliest_date ? moment(new Date(settings.earliest_date)).startOf('day') : moment(new Date('January 1, 1900')).startOf('day'); this.latest_date = settings.latest_date ? moment(new Date(settings.latest_date)).endOf('day') : moment(new Date('December 31, 2900')).endOf('day'); this.end_date = settings.end_date ? new Date(settings.end_date) : (this.type == 'double' ? new Date() : null); this.start_date = settings.start_date ? new Date(settings.start_date) : (this.type == 'double' ? new Date(moment(this.end_date).subtract(1, 'month')) : null); this.current_date = settings.current_date ? new Date(settings.current_date) : (this.type == 'single' ? new Date() : null); this.callback = settings.callback || this.calendarSetDates; this.calendarHTML(this.type); $('.dr-presets', this.element).click(function() { self.presetToggle(); }); $('.dr-list-item', this.element).click(function() { var start = $('.dr-item-aside', this).data('start'); var end = $('.dr-item-aside', this).data('end'); self.start_date = self.calendarCheckDate(start); self.end_date = self.calendarCheckDate(end); self.calendarSetDates(); self.presetToggle(); self.calendarSaveDates(); }); $('.dr-date', this.element).on({ 'click': function() { self.calendarOpen(this); }, 'keyup': function(event) { if (event.keyCode == 9 && !self.calIsOpen && !self.start_date && !self.end_date) self.calendarOpen(this); }, 'keydown': function(event) { switch (event.keyCode) { case 9: // Tab if ($(self.selected).hasClass('dr-date-start')) { event.preventDefault(); self.calendarCheckDates(); self.calendarSetDates(); $('.dr-date-end', self.element).trigger('click'); } else { self.calendarCheckDates(); self.calendarSetDates(); self.calendarSaveDates(); self.calendarClose('force'); } break; case 13: // Enter event.preventDefault(); self.calendarCheckDates(); self.calendarSetDates(); self.calendarSaveDates(); self.calendarClose('force'); break; case 27: // ESC self.calendarSetDates(); self.calendarClose('force'); break; case 38: // Up event.preventDefault(); var timeframe = 'day'; if (event.shiftKey) timeframe = 'week'; if (event.metaKey) timeframe = 'month'; var back = moment(self.current_date).subtract(1, timeframe); $(this).html(back.format(self.format.input)); self.current_date = back._d; break; case 40: // Down event.preventDefault(); var timeframe = 'day'; if (event.shiftKey) timeframe = 'week'; if (event.metaKey) timeframe = 'month'; var forward = moment(self.current_date).add(1, timeframe); $(this).html(forward.format(self.format.input)); self.current_date = forward._d; break; } } }); $('.dr-month-switcher i', this.element).click(function() { var m = $('.dr-month-switcher span', self.element).data('month'); var y = $('.dr-year-switcher span', self.element).data('year'); var this_moment = moment([y, m, 1]); var back = this_moment.clone().subtract(1, 'month'); var forward = this_moment.clone().add(1, 'month').startOf('day'); if ($(this).hasClass('dr-left')) { self.calendarOpen(self.selected, back); } else if ($(this).hasClass('dr-right')) { self.calendarOpen(self.selected, forward); } }); $('.dr-year-switcher i', this.element).click(function() { var m = $('.dr-month-switcher span', self.element).data('month'); var y = $('.dr-year-switcher span', self.element).data('year'); var this_moment = moment([y, m, 1]); var back = this_moment.clone().subtract(1, 'year'); var forward = this_moment.clone().add(1, 'year').startOf('day'); if ($(this).hasClass('dr-left')) { self.calendarOpen(self.selected, back); } else if ($(this).hasClass('dr-right')) { self.calendarOpen(self.selected, forward); } }); $('.dr-dates-dash', this.element).click(function() { $('.dr-date-start', self.element).trigger('click'); }); // Once you click into a selection.. this lets you click out $(this.element).click(function(event) { $('html').one('click',function() { if (self.presetIsOpen) self.presetToggle(); if (self.calIsOpen) { if ($(self.selected).hasClass("dr-date-end")) self.calendarSaveDates(); self.calendarSetDates(); self.calendarClose('force'); } }); event.stopPropagation(); }); // If you tab into a selection.. this lets you click out $(this.element).add('.dr-date', this.element).focus(function(event) { $(window).one('click',function() { if (self.calIsOpen) { self.calendarSetDates(); self.calendarClose('force'); } }); event.stopPropagation(); }); } Calendar.prototype.presetToggle = function() { if (this.presetIsOpen == false) { this.presetIsOpen = true; this.presetCreate(); } else if (this.presetIsOpen) { this.presetIsOpen = false; } if (this.calIsOpen == true) this.calendarClose(); $('.dr-preset-list', this.element).slideToggle(200); $('.dr-input', this.element).toggleClass('dr-active'); $('.dr-presets', this.element).toggleClass('dr-active'); } Calendar.prototype.presetCreate = function() { var self = this; var date = this.latest_date; var last_day = moment(date).endOf('month'); var is_last_day = last_day.isSame(date); var first_day; $('.dr-list-item', this.element).each(function() { var month_count = $(this).data('months'); if (!is_last_day) last_day = moment(date).subtract(1, 'month').endOf('month').startOf('day'); if (typeof month_count == 'number') { first_day = moment(date).subtract(is_last_day ? month_count - 1 : month_count, 'month').startOf('month'); if (month_count == 12) first_day = moment(date).subtract(is_last_day ? 11 : 12, 'month').startOf('month').startOf('day'); } else if (month_count == 'all') { first_day = moment(self.earliest_date); last_day = moment(self.latest_date); } else { first_day = moment(self.latest_date).subtract(29, 'day'); last_day = moment(self.latest_date); } if (first_day.isBefore(self.earliest_date)) return $(this).remove() $('.dr-item-aside', this) .data('start', first_day.toISOString()) .data('end', last_day.toISOString()) .html(first_day.format(self.format.preset) +' &ndash; '+ last_day.format(self.format.preset)); }); } Calendar.prototype.calendarSetDates = function() { $('.dr-date-start', this.element).html(moment(this.start_date).format(this.format.input)); $('.dr-date-end', this.element).html(moment(this.end_date).format(this.format.input)); if (!this.start_date && !this.end_date) { var old_date = $('.dr-date', this.element).html(); var new_date = moment(this.current_date).format(this.format.input); if (old_date != new_date) $('.dr-date', this.element).html(new_date); } } Calendar.prototype.calendarSaveDates = function() { return this.callback(); } Calendar.prototype.calendarCheckDate = function(d) { var regex = /(?!<=\d)(st|nd|rd|th)/; var d_array = d ? d.replace(regex, '').split(' ') : []; // Today if (d == 'today' || d == 'now') d = moment().isAfter(this.latest_date) ? this.latest_date : moment(); // Earliest if (d == 'earliest') d = this.earliest_date; // Latest if (d == 'latest') d = this.latest_date; // Convert string to a date if keyword ago or ahead exists if (d && (d.toString().indexOf('ago') != -1 || d.toString().indexOf('ahead') != -1)) d = this.stringToDate(d); // Add current year if year is not included if (d_array.length == 2) { d_array.push(moment().format(this.display_year_format)) d = d_array.join(' '); } // Convert using settings format if (d && $.type(d) == 'string') { var parsed_d = moment(d, this.format.input); if (parsed_d.isValid()) d = parsed_d; } return new Date(d); } Calendar.prototype.calendarCheckDates = function() { var s = $('.dr-date-start', this.element).html(); var e = $('.dr-date-end', this.element).html(); var c = $(this.selected).html(); // Modify strings via some specific keywords to create valid dates // Year to date if (s == 'ytd' || e == 'ytd') { s = moment().startOf('year'); e = moment().isAfter(this.latest_date) ? this.latest_date : moment(); } // Finally set all strings as dates else { s = this.calendarCheckDate(s); e = this.calendarCheckDate(e); } c = this.calendarCheckDate(c); if (moment(c).isSame(s) && moment(s).isAfter(e)) { e = moment(s).add(6, 'day'); // c = e.clone(); } if (moment(c).isSame(e) && moment(e).isBefore(s)) { s = moment(e).subtract(6, 'day'); // c = s.clone(); } if (moment(e).isBefore(this.earliest_date) || moment(s).isBefore(this.earliest_date)) { s = moment(this.earliest_date); e = moment(this.earliest_date).add(6, 'day'); } if (moment(e).isAfter(this.latest_date) || moment(s).isAfter(this.latest_date)) { s = moment(this.latest_date).subtract(6, 'day'); e = moment(this.latest_date); } // Is this a valid date? if (moment(s).isSame(e) && !this.sameDayRange) return this.calendarSetDates(); // Push and save if it's valid otherwise return to previous state this.start_date = s == 'Invalid Date' ? this.start_date : s; this.end_date = e == 'Invalid Date' ? this.end_date : e; this.current_date = c == 'Invalid Date' ? this.current_date : c; } Calendar.prototype.stringToDate = function(str) { var date_arr = str.split(' '); if (date_arr[2] == 'ago') { return moment(this.current_date).subtract(date_arr[0], date_arr[1]); } else if (date_arr[2] == 'ahead') { return moment(this.current_date).add(date_arr[0], date_arr[1]); } return this.current_date; } Calendar.prototype.calendarOpen = function(selected, switcher) { var self = this; var other; var cal_width = $('.dr-dates', this.element).innerWidth() - 8; this.selected = selected || this.selected; if (this.presetIsOpen == true) this.presetToggle(); if (this.calIsOpen == true) this.calendarClose(switcher ? 'switcher' : undefined); this.calendarCheckDates(); this.calendarCreate(switcher); this.calendarSetDates(); var next_month = moment(switcher || this.current_date).add(1, 'month').startOf('month').startOf('day'); var past_month = moment(switcher || this.current_date).subtract(1, 'month').endOf('month'); var next_year = moment(switcher || this.current_date).add(1, 'year').startOf('month').startOf('day'); var past_year = moment(switcher || this.current_date).subtract(1, 'year').endOf('month'); var this_moment = moment(switcher || this.current_date); $('.dr-month-switcher span', this.element) .data('month', this_moment.month()) .html(this_moment.format(this.format.jump_month)); $('.dr-year-switcher span', this.element) .data('year', this_moment.year()) .html(this_moment.format(this.format.jump_year)); $('.dr-switcher i', this.element).removeClass('dr-disabled'); if (next_month.isAfter(this.latest_date)) $('.dr-month-switcher .dr-right', this.element).addClass('dr-disabled'); if (past_month.isBefore(this.earliest_date)) $('.dr-month-switcher .dr-left', this.element).addClass('dr-disabled'); if (next_year.isAfter(this.latest_date)) $('.dr-year-switcher .dr-right', this.element).addClass('dr-disabled'); if (past_year.isBefore(this.earliest_date)) $('.dr-year-switcher .dr-left', this.element).addClass('dr-disabled'); $('.dr-day', this.element).on({ mouseenter: function() { var selected = $(this); var start_date = moment(self.start_date); var end_date = moment(self.end_date); var current_date = moment(self.current_date); if ($(self.selected).hasClass("dr-date-start")) { selected.addClass('dr-hover dr-hover-before'); $('.dr-start', self.element).css({'border': 'none', 'padding-left': '0.3125rem'}); setMaybeRange('start'); } if ($(self.selected).hasClass("dr-date-end")) { selected.addClass('dr-hover dr-hover-after'); $('.dr-end', self.element).css({'border': 'none', 'padding-right': '0.3125rem'}); setMaybeRange('end'); } if (!self.start_date && !self.end_date) selected.addClass('dr-maybe'); $('.dr-selected', self.element).css('background-color', 'transparent'); function setMaybeRange(type) { other = undefined; self.range(6 * 7).forEach(function(i) { var next = selected.next().data('date'); var prev = selected.prev().data('date'); var curr = selected.data('date'); if (!curr) return false; if (!prev) prev = curr; if (!next) next = curr; if (type == 'start') { if (moment(next).isSame(self.end_date) || (self.sameDayRange && moment(curr).isSame(self.end_date))) return false; if (moment(curr).isAfter(self.end_date)) { other = other || moment(curr).add(6, 'day').startOf('day'); if (i > 5 || (next ? moment(next).isAfter(self.latest_date) : false)) { $(selected).addClass('dr-end'); other = moment(curr); return false; } } selected = selected.next().addClass('dr-maybe'); } else if (type == 'end') { if (moment(prev).isSame(self.start_date) || (self.sameDayRange && moment(curr).isSame(self.start_date))) return false; if (moment(curr).isBefore(self.start_date)) { other = other || moment(curr).subtract(6, 'day'); if (i > 5 || (prev ? moment(prev).isBefore(self.earliest_date) : false)) { $(selected).addClass('dr-start'); other = moment(curr); return false; } } selected = selected.prev().addClass('dr-maybe'); } }); } }, mouseleave: function() { if ($(this).hasClass('dr-hover-before dr-end')) $(this).removeClass('dr-end'); if ($(this).hasClass('dr-hover-after dr-start')) $(this).removeClass('dr-start'); $(this).removeClass('dr-hover dr-hover-before dr-hover-after'); $('.dr-start, .dr-end', self.element).css({'border': '', 'padding': ''}); $('.dr-maybe:not(.dr-current)', self.element).removeClass('dr-start dr-end'); $('.dr-day', self.element).removeClass('dr-maybe'); $('.dr-selected', self.element).css('background-color', ''); }, mousedown: function() { var date = $(this).data('date'); var string = moment(date).format(self.format.input); if (other) { $('.dr-date', self.element) .not(self.selected) .html(other.format(self.format.input)); } $(self.selected).html(string); self.calendarOpen(self.selected); if ($(self.selected).hasClass('dr-date-start')) { $('.dr-date-end', self.element).trigger('click'); } else { self.calendarSaveDates(); self.calendarClose('force'); } } }); $('.dr-calendar', this.element) .css('width', cal_width) .slideDown(200); $('.dr-input', this.element).addClass('dr-active'); $(selected).addClass('dr-active').focus(); $(this.element).addClass('dr-active'); this.calIsOpen = true; } Calendar.prototype.calendarClose = function(type) { var self = this; if (!this.calIsOpen || this.presetIsOpen || type == 'force') { $('.dr-calendar', this.element).slideUp(200, function() { $('.dr-day', self.element).remove(); }); } else { $('.dr-day', this.element).remove(); } if (type == 'switcher') { return false; } $('.dr-input, .dr-date', this.element).removeClass('dr-active'); $(this.element).removeClass('dr-active'); this.calIsOpen = false; } Calendar.prototype.calendarCreate = function(switcher) { var self = this; var array = this.calendarArray(this.start_date, this.end_date, this.current_date, switcher); array.forEach(function(d, i) { var classString = "dr-day"; if (d.fade) classString += " dr-fade"; if (d.start) classString += " dr-start"; if (d.end) classString += " dr-end"; if (d.current) classString += " dr-current"; if (d.selected) classString += " dr-selected"; if (d.outside) classString += " dr-outside"; $('.dr-day-list', self.element).append('<li class="'+ classString +'" data-date="'+ d.date +'">'+ d.str +'</li>'); }); } Calendar.prototype.calendarArray = function(start, end, current, switcher) { var self = this; current = current || start || end; var first_day = moment(switcher || current).startOf('month'); var last_day = moment(switcher || current).endOf('month'); var current_month = { start: { day: +first_day.format('d'), str: +first_day.format('D') }, end: { day: +last_day.format('d'), str: +last_day.format('D') } } // Beginning faded dates var d = undefined; var start_hidden = this.range(current_month.start.day).map(function() { if (d == undefined) { d = moment(first_day); } d = d.subtract(1, 'day'); return { str: +d.format('D'), start: d.isSame(start), end: d.isSame(end), current: d.isSame(current), selected: d.isBetween(start, end), date: d.toISOString(), outside: d.isBefore(self.earliest_date), fade: true } }).reverse(); // Leftover faded dates var leftover = (6 * 7) - (current_month.end.str + start_hidden.length); d = undefined; var end_hidden = this.range(leftover).map(function() { if (d == undefined) { d = moment(last_day); } d = d.add(1, 'day').startOf('day'); return { str: +d.format('D'), start: d.isSame(start), end: d.isSame(end), current: d.isSame(current), selected: d.isBetween(start, end), date: d.toISOString(), outside: d.isAfter(self.latest_date), fade: true } }); // Actual visible dates d = undefined; var visible = this.range(current_month.end.str).map(function() { if (d == undefined) { d = moment(first_day); } else { d = d.add(1, 'day').startOf('day'); } return { str: +d.format('D'), start: d.isSame(start), end: d.isSame(end), current: d.isSame(current), selected: d.isBetween(start, end), date: d.toISOString(), outside: d.isBefore(self.earliest_date) || d.isAfter(self.latest_date), fade: false } }); return start_hidden.concat(visible, end_hidden); } Calendar.prototype.calendarHTML = function(type) { var ul_days_of_the_week = $('<ul class="dr-days-of-week-list"></ul>') var self = this; $.each(this.days_array || moment.weekdaysMin(), function(i, elem) { ul_days_of_the_week.append('<li class="dr-day-of-week">' + elem + '</li>'); }); if (type == "double") return this.element.append('<div class="dr-input">' + '<div class="dr-dates">' + '<div class="dr-date dr-date-start" contenteditable>'+ moment(this.start_date).format(this.format.input) +'</div>' + '<span class="dr-dates-dash">&ndash;</span>' + '<div class="dr-date dr-date-end" contenteditable>'+ moment(this.end_date).format(this.format.input) +'</div>' + '</div>' + '<div class="dr-presets">' + '<span class="dr-preset-bar"></span>' + '<span class="dr-preset-bar"></span>' + '<span class="dr-preset-bar"></span>' + '</div>' + '</div>' + '<div class="dr-selections">' + '<div class="dr-calendar" style="display: none;">' + '<div class="dr-range-switcher">' + '<div class="dr-switcher dr-month-switcher">' + '<i class="dr-left"></i>' + '<span>April</span>' + '<i class="dr-right"></i>' + '</div>' + '<div class="dr-switcher dr-year-switcher">' + '<i class="dr-left"></i>' + '<span>2015</span>' + '<i class="dr-right"></i>' + '</div>' + '</div>' + ul_days_of_the_week[0].outerHTML + '<ul class="dr-day-list"></ul>' + '</div>' + '<ul class="dr-preset-list" style="display: none;">' + '<li class="dr-list-item" data-months="days">最近30天 <span class="dr-item-aside"></span></li>' + '<li class="dr-list-item" data-months="1">最近1个月 <span class="dr-item-aside"></span></li>' + '<li class="dr-list-item" data-months="3">最近3个月 <span class="dr-item-aside"></span></li>' + '<li class="dr-list-item" data-months="6">最近6个月 <span class="dr-item-aside"></span></li>' + '<li class="dr-list-item" data-months="12">去年 <span class="dr-item-aside"></span></li>' + '<li class="dr-list-item" data-months="all">全部 <span class="dr-item-aside"></span></li>' + '</ul>' + '</div>'); return this.element.append('<div class="dr-input">' + '<div class="dr-dates">' + '<div class="dr-date" contenteditable>'+ moment(this.current_date).format(this.format.input) +'</div>' + '</div>' + '</div>' + '<div class="dr-selections">' + '<div class="dr-calendar" style="display: none;">' + '<div class="dr-range-switcher">' + '<div class="dr-switcher dr-month-switcher">' + '<i class="dr-left"></i>' + '<span></span>' + '<i class="dr-right"></i>' + '</div>' + '<div class="dr-switcher dr-year-switcher">' + '<i class="dr-left"></i>' + '<span></span>' + '<i class="dr-right"></i>' + '</div>' + '</div>' + ul_days_of_the_week[0].outerHTML + '<ul class="dr-day-list"></ul>' + '</div>' + '</div>'); } Calendar.prototype.range = function(length) { var range = new Array(length); for (var idx = 0; idx < length; idx++) { range[idx] = idx; } return range; } return Calendar; }));
import React from 'react'; const EventType = React.createClass({ propTypes: { weekendInfo: React.PropTypes.object }, getDefaultProps: function() { return { weekendInfo: {} } }, shouldComponentUpdate: function(nextProps, nextState) { return this.props.weekendInfo.EventType !== nextProps.weekendInfo.EventType; }, render: function() { const eventType = this.props.weekendInfo.EventType || 'Waiting'; return ( <div id="type"> {eventType} </div> ); } }); export default EventType;
'use strict'; var request = require('request'); var imgurwrapUtil = require('./imgurwrap.util.js'); var imgurwrapImage = require('./imgurwrap.image.js'); var imgurwrapAlbum = require('./imgurwrap.album.js'); var imgurwrap = module.exports; /** * URL parsing and testing */ var _imgurDomain = /.*\/\/((i|m)\.)?imgur.com\/.*$/; var _imgurAlbumTest = /.*\/a\/.*/; imgurwrap.isImgurURL = function(url) { return _imgurDomain.test(url); }; imgurwrap.isAlbumURL = function(url) { return _imgurDomain.test(url) && _imgurAlbumTest.test(url); }; imgurwrap.getRateLimitingData = function(callback) { var endpoint = imgurwrapUtil.getEndpoint('credits'); var params = imgurwrapUtil.getBaseRequestParams(endpoint); var err = imgurwrapUtil.validateRequestParams(params); if (err) { return callback(err); } return request.get(params, imgurwrapUtil.responseCallback(callback)); }; var _loadMultipleImages = function(idArr, callback) { var remaining = idArr.length; var images = []; idArr.forEach(function(myId) { imgurwrapImage.getImageData(myId, function(err, result) { if(err) { return callback(err); } else { images.push(result); if(--remaining === 0) { return callback(null, { images: images, model: 'images' }); } } }); }); }; /** * Given an Imgur URL for an image, images, or an album, it will determine the correct endpoint * to use and return the appropriate data. URL's of the following forms are handled: * * http://imgur.com/G80OxqS * http://i.imgur.com/G80OxqS.jpg * http://imgur.com/G80OxqS,PzWUu,PzWUu * http://imgur.com/a/PzWUu */ imgurwrap.getURLData = function(url, callback) { if(!imgurwrap.isImgurURL(url)) { return callback(new imgurwrapUtil.ImgurError(null, 'not an imgur url "' + url + '"')); } var idArr = imgurwrapUtil.parseImageIds(url); if(!idArr || idArr.length < 1) { return callback(new imgurwrapUtil.ImgurError(null, 'unable to extract imgur id from "' + url + '"')); } if(idArr.length === 1) { if(imgurwrap.isAlbumURL(url)) { return imgurwrapAlbum.getAlbumData(idArr[0], callback); } return imgurwrapImage.getImageData(idArr[0], callback); } return _loadMultipleImages(idArr, callback); };
'use strict'; var chai = require('chai'); chai.use(require('chai-things')); var expect = chai.expect; var universities = require('../universities.js'); describe('universities', function() { beforeEach(function(done) { universities.connectDb((err) => { if (err) { return done(err); } universities.removeAll(function(err) { if (err) { return done(err); } universities.add([{ "acronym": "intec", "name": "Instituto Tecnológico de Santo Domingo", "url": "http://www.intec.edu.do/", "country": "Dominican Republic", }, { "acronym": "APEC", "name": "Universidad Acción Pro Educación y Cultura", "url": "https://www.unapec.edu.do/", "country": "Dominican Republic" }, { "acronym": "PUCMM", "name": "Pontificia Universidad Católica Madre y Maestra", "url": "https://www.pucmm.edu.do/", "country": "Dominican Republic" }], done); }); }); // describe('#alluniversities()', function() { it('should return all universities', function(done) { universities.allUniversities((err, res) => { if (err) { return done(err); } expect(res).to.have.lengthOf(3); expect(res).to.contain.an.item.with.property('acronym', 'intec'); expect(res).to.contain.an.item.with.property('acronym', 'APEC'); expect(res).to.contain.an.item.with.property('acronym', 'PUCMM'); done(); }); }); }); // describe('#remove()', function() { it('should remove the university', function(done) { universities.remove('PUCMM', (err) => { if (err) { return done(err); } universities.allUniversities((err, res) => { if (err) { return done(err); } expect(res).to.have.lengthOf(2); expect(res).not.to.contain.an.item.with.property('acronym', 'PUCMM'); done(); }); }); }); }); }); });
const axios = require("axios"); const crypto = require("crypto"); const mongoose = require("mongoose"); const nodemailer = require("nodemailer"); const User = require("./user.model"); const { generateAccessToken, generateRefreshToken } = require("../../core/server/authorize.middleware"); function formatProfile(user) { const profile = { _id: user._id, name: user.displayName, isAdmin: user.role === "admin" }; if(user.local) { profile.local = { email: user.local.email }; } if(user.facebook) { profile.facebook = { email: user.facebook.email }; } if(user.google) { profile.google = { email: user.google.email }; } return profile; } async function register(req, res) { const { name, email, password } = req.body; try { const doc = await User.findOne({ $or: [ { "local.email": email }, { "facebook.email": email }, { "google.email": email } ]}); if(doc) { return res.status(400).send("This email address is already registered."); } const user = new User(); user._id = new mongoose.Types.ObjectId(); user.displayName = name; user.local.name = name; user.local.email = email; user.local.password = user.generateHash(password); user.local.refresh_token = generateRefreshToken(user); await user.save(); res.cookie("access_token", generateAccessToken(user), { httpOnly: true, sameSite: true }); res.cookie("refresh_token", user.local.refresh_token, { httpOnly: true, sameSite: true }); res.json({ name: name, isAdmin: false }); } catch(err) { res.sendStatus(500); } } async function login(req, res) { try { let doc; const { username, password, grant_type, recaptchaToken } = req.body; const response = await axios.post(`https://www.google.com/recaptcha/api/siteverify?secret=${process.env.RECAPTCHA_SECRET_KEY}&response=${recaptchaToken}`); if(!response.data.success) return res.status(401).send("reCAPTCHA validation failed! Please try again."); if(!grant_type) return res.status(401).send("Invalid credentials."); if(grant_type === "password") { doc = await User.findOne({ "local.email": username }); if(!doc || !doc.validPassword(password)) { return res.status(401).send("Invalid credentials."); } doc.local.refresh_token = generateRefreshToken(doc); await doc.save(); } res.cookie("access_token", generateAccessToken(doc), { httpOnly: true, sameSite: true }); res.cookie("refresh_token", doc.local.refresh_token, { httpOnly: true, sameSite: true }); res.json(formatProfile(doc.toJSON())); } catch (err) { res.sendStatus(500); } } function logout(req, res) { res.clearCookie("access_token"); res.clearCookie("refresh_token").redirect("/"); } async function changePassword(req, res) { try { const doc = await User.findOne({ _id: req.user._id }, "local"); if(!doc || !doc.validPassword(req.body.currentPassword)) { return res.status(400).send("Invalid password!"); } doc.local.password = doc.generateHash(req.body.newPassword); doc.save(); res.status(200).send("Password changed successfully."); } catch (err) { res.sendStatus(500); } } function forgotPassword(req, res) { User.findOne({ $or: [ { "facebook.email" : req.body.email }, { "google.email": req.body.email }, { "local.email": req.body.email } ]}, function(err, doc) { if(err) return res.sendStatus(500); if(!doc) return res.status(404).send("No account is associated with this email address."); const transporter = nodemailer.createTransport({ host: process.env.SMTP_HOST, auth: { user: process.env.MAILER_ADDRESS, pass: process.env.MAILER_PASSWORD } }); doc.local.resetPasswordToken = crypto.randomBytes(20).toString("hex"); doc.local.resetPasswordExpires = Date.now() + 3600000; doc.save().then(function() { res.render("password-reset.html", { url: `${req.headers.origin}/reset-password?token=${doc.local.resetPasswordToken}` }, function(err, html) { transporter.sendMail({ from: `"Gadget Catalog" <${process.env.MAILER_ADDRESS}>`, to: req.body.email, subject: "[Gadget Catalog] Password Reset Request", html: html }, function (err) { if(err) return res.sendStatus(500); res.sendStatus(200); }); }); }); }); } async function resetPassword(req, res) { try { const doc = User.findOne({ "local.resetPasswordToken": req.query.token, "local.resetPasswordExpires": { $gt: Date.now() } }); if(!doc) return res.status(401).send("Account doesn't exist or the token has expired."); if(req.body.newPassword !== req.body.confirmNewPassword) return res.sendStatus(400); doc.local.password = doc.generateHash(req.body.newPassword); doc.save(); res.sendStatus(200); } catch (err) { res.sendStatus(500); } } function getSignedInUserProfile(req, res) { res.json(formatProfile(req.user.toJSON())); } function disconnect(req, res) { if(!req.query.provider) return res.sendStatus(400); if(req.query.provider === "facebook") { axios.delete(`https://graph.facebook.com/${req.user.facebook.id}/permissions?access_token=${req.user.facebook.accessToken}`).then(() => { User.findOneAndUpdate({_id: req.user._id}, {$unset: {facebook: 1 }}, {new: true}, (err, doc) => res.json(formatProfile(doc.toJSON()))); }).catch(() => res.sendStatus(500)); } else { User.findOneAndUpdate({_id: req.user._id}, {$unset: {google: 1 }}, {new: true}, (err, doc) => res.json(formatProfile(doc.toJSON()))); } } exports.register = register; exports.login = login; exports.logout = logout; exports.changePassword = changePassword; exports.forgotPassword = forgotPassword; exports.resetPassword = resetPassword; exports.getSignedInUserProfile = getSignedInUserProfile; exports.disconnect = disconnect;
/** * 工具 */ var array = require('./array'); var object = require('./object'); /** * 将数字id转化为字符串 */ var intzip = exports.intzip = function(a, bit){ bit = bit || 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890'; if(typeof a=='number'){ if(a==0) return bit.charAt(0); for(var s=""; a; a=a/bit.length|0){ s = bit.charAt(a%bit.length)+s; } return s; }else if(typeof a=='string'){ for(var s= 0,i= 0,b = a.split(''); i<b.length; i++){ var ix = bit.indexOf(b[i]); if(ix==-1) return null; s += ix * Math.pow(bit.length,b.length-i-1); } return s; } return null; }; /** * 依赖关系排序算法,不可处理循环依赖 */ exports.sortDependence = function(deps,stuff){ return extend(); function extend(stu){ stu = stu || object.clone(stuff); var cpstu = object.clone(stu); //console.log(deps); //console.log(stu); var len = stu.length , is = 0; for(var s in stu){ var yl = deps[stu[s]]; //console.log(stu[s]+' yl '+yl); if(yl){ for (var y in yl) cpstu.splice(is, 0, yl[y]); is += yl.length; } is++; } cpstu = array.unique(cpstu); //去重 if(cpstu.length>len){ //下一层递归 return extend(cpstu); } return cpstu; } };
'use strict'; import abbreviateNumber from '../abbreviateNumber'; describe('abbreviateNumber', () => { it('always returns a string', () => { expect(abbreviateNumber(1, 0)).to.equal('1'); expect(abbreviateNumber(999, 1)).to.equal('999'); }); it('abbreviates numbers correctly', () => { expect(abbreviateNumber(0, 2)).to.equal('0'); expect(abbreviateNumber(12, 1)).to.equal('12'); expect(abbreviateNumber(1000, 1)).to.equal('1k'); expect(abbreviateNumber(1234, 0)).to.equal('1k'); expect(abbreviateNumber(34567, 2)).to.equal('34.57k'); expect(abbreviateNumber(918395, 1)).to.equal('918.4k'); expect(abbreviateNumber(2134124, 2)).to.equal('2.13m'); expect(abbreviateNumber(47475782130, 2)).to.equal('47.48b'); }); });
function js_beautify(js_source_text, indent_size, indent_character, indent_level) { var input, output, token_text, last_type, last_text, last_word, current_mode, modes, indent_string; var whitespace, wordchar, punct, parser_pos, line_starters, in_case; var prefix, token_type, do_block_just_closed, var_line, var_line_tainted; function trim_output() { while (output.length && (output[output.length - 1] === ' ' || output[output.length - 1] === indent_string)) { output.pop(); } } function print_newline(ignore_repeated) { ignore_repeated = typeof ignore_repeated === 'undefined' ? true: ignore_repeated; trim_output(); if (!output.length) { return; // no newline on start of file } if (output[output.length - 1] !== "\n" || !ignore_repeated) { output.push("\n"); } for (var i = 0; i < indent_level; i++) { output.push(indent_string); } } function print_space() { var last_output = output.length ? output[output.length - 1] : ' '; if (last_output !== ' ' && last_output !== '\n' && last_output !== indent_string) { // prevent occassional duplicate space output.push(' '); } } function print_token() { output.push(token_text); } function indent() { indent_level++; } function unindent() { if (indent_level) { indent_level--; } } function remove_indent() { if (output.length && output[output.length - 1] === indent_string) { output.pop(); } } function set_mode(mode) { modes.push(current_mode); current_mode = mode; } function restore_mode() { do_block_just_closed = current_mode === 'DO_BLOCK'; current_mode = modes.pop(); } function in_array(what, arr) { for (var i = 0; i < arr.length; i++) { if (arr[i] === what) { return true; } } return false; } function get_next_token() { var n_newlines = 0; var c = ''; do { if (parser_pos >= input.length) { return ['', 'TK_EOF']; } c = input.charAt(parser_pos); parser_pos += 1; if (c === "\n") { n_newlines += 1; } } while ( in_array ( c , whitespace )); if (n_newlines > 1) { for (var i = 0; i < 2; i++) { print_newline(i === 0); } } var wanted_newline = (n_newlines === 1); if (in_array(c, wordchar)) { if (parser_pos < input.length) { while (in_array(input.charAt(parser_pos), wordchar)) { c += input.charAt(parser_pos); parser_pos += 1; if (parser_pos === input.length) { break; } } } // small and surprisingly unugly hack for 1E-10 representation if (parser_pos !== input.length && c.match(/^[0-9]+[Ee]$/) && input.charAt(parser_pos) === '-') { parser_pos += 1; var t = get_next_token(parser_pos); c += '-' + t[0]; return [c, 'TK_WORD']; } if (c === 'in') { // hack for 'in' operator return [c, 'TK_OPERATOR']; } return [c, 'TK_WORD']; } if (c === '(' || c === '[') { return [c, 'TK_START_EXPR']; } if (c === ')' || c === ']') { return [c, 'TK_END_EXPR']; } if (c === '{') { return [c, 'TK_START_BLOCK']; } if (c === '}') { return [c, 'TK_END_BLOCK']; } if (c === ';') { return [c, 'TK_END_COMMAND']; } if (c === '/') { var comment = ''; // peek for comment /* ... */ if (input.charAt(parser_pos) === '*') { parser_pos += 1; if (parser_pos < input.length) { while (! (input.charAt(parser_pos) === '*' && input.charAt(parser_pos + 1) && input.charAt(parser_pos + 1) === '/') && parser_pos < input.length) { comment += input.charAt(parser_pos); parser_pos += 1; if (parser_pos >= input.length) { break; } } } parser_pos += 2; return ['/*' + comment + '*/', 'TK_BLOCK_COMMENT']; } // peek for comment // ... if (input.charAt(parser_pos) === '/') { comment = c; while (input.charAt(parser_pos) !== "\x0d" && input.charAt(parser_pos) !== "\x0a") { comment += input.charAt(parser_pos); parser_pos += 1; if (parser_pos >= input.length) { break; } } parser_pos += 1; if (wanted_newline) { print_newline(); } return [comment, 'TK_COMMENT']; } } if (c === "'" || // string c === '"' || // string (c === '/' && ((last_type === 'TK_WORD' && last_text === 'return') || (last_type === 'TK_START_EXPR' || last_type === 'TK_END_BLOCK' || last_type === 'TK_OPERATOR' || last_type === 'TK_EOF' || last_type === 'TK_END_COMMAND')))) { // regexp var sep = c; var esc = false; c = ''; if (parser_pos < input.length) { while (esc || input.charAt(parser_pos) !== sep) { c += input.charAt(parser_pos); if (!esc) { esc = input.charAt(parser_pos) === '\\'; } else { esc = false; } parser_pos += 1; if (parser_pos >= input.length) { break; } } } parser_pos += 1; if (last_type === 'TK_END_COMMAND') { print_newline(); } return [sep + c + sep, 'TK_STRING']; } if (in_array(c, punct)) { while (parser_pos < input.length && in_array(c + input.charAt(parser_pos), punct)) { c += input.charAt(parser_pos); parser_pos += 1; if (parser_pos >= input.length) { break; } } return [c, 'TK_OPERATOR']; } return [c, 'TK_UNKNOWN']; } //---------------------------------- indent_character = indent_character || ' '; indent_size = indent_size || 4; indent_string = ''; while (indent_size--) { indent_string += indent_character; } input = js_source_text; last_word = ''; // last 'TK_WORD' passed last_type = 'TK_START_EXPR'; // last token type last_text = ''; // last token text output = []; do_block_just_closed = false; var_line = false; var_line_tainted = false; whitespace = "\n\r\t ".split(''); wordchar = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$'.split(''); punct = '+ - * / % & ++ -- = += -= *= /= %= == === != !== > < >= <= >> << >>> >>>= >>= <<= && &= | || ! !! , : ? ^ ^= |='.split(' '); // words which should always start on new line. line_starters = 'continue,try,throw,return,var,if,switch,case,default,for,while,break,function'.split(','); // states showing if we are currently in expression (i.e. "if" case) - 'EXPRESSION', or in usual block (like, procedure), 'BLOCK'. // some formatting depends on that. current_mode = 'BLOCK'; modes = [current_mode]; indent_level = indent_level || 0; parser_pos = 0; // parser position in_case = false; // flag for parser that case/default has been processed, and next colon needs special attention while (true) { var t = get_next_token(parser_pos); token_text = t[0]; token_type = t[1]; if (token_type === 'TK_EOF') { break; } switch (token_type) { case 'TK_START_EXPR': var_line = false; set_mode('EXPRESSION'); if (last_type === 'TK_END_EXPR' || last_type === 'TK_START_EXPR') { // do nothing on (( and )( and ][ and ]( .. } else if (last_type !== 'TK_WORD' && last_type !== 'TK_OPERATOR') { print_space(); } else if (in_array(last_word, line_starters) && last_word !== 'function') { print_space(); } print_token(); break; case 'TK_END_EXPR': print_token(); restore_mode(); break; case 'TK_START_BLOCK': if (last_word === 'do') { set_mode('DO_BLOCK'); } else { set_mode('BLOCK'); } if (last_type !== 'TK_OPERATOR' && last_type !== 'TK_START_EXPR') { if (last_type === 'TK_START_BLOCK') { print_newline(); } else { print_space(); } } print_token(); indent(); break; case 'TK_END_BLOCK': if (last_type === 'TK_START_BLOCK') { // nothing trim_output(); unindent(); } else { unindent(); print_newline(); } print_token(); restore_mode(); break; case 'TK_WORD': if (do_block_just_closed) { print_space(); print_token(); print_space(); break; } if (token_text === 'case' || token_text === 'default') { if (last_text === ':') { // switch cases following one another remove_indent(); } else { // case statement starts in the same line where switch unindent(); print_newline(); indent(); } print_token(); in_case = true; break; } prefix = 'NONE'; if (last_type === 'TK_END_BLOCK') { if (!in_array(token_text.toLowerCase(), ['else', 'catch', 'finally'])) { prefix = 'NEWLINE'; } else { prefix = 'SPACE'; print_space(); } } else if (last_type === 'TK_END_COMMAND' && (current_mode === 'BLOCK' || current_mode === 'DO_BLOCK')) { prefix = 'NEWLINE'; } else if (last_type === 'TK_END_COMMAND' && current_mode === 'EXPRESSION') { prefix = 'SPACE'; } else if (last_type === 'TK_WORD') { prefix = 'SPACE'; } else if (last_type === 'TK_START_BLOCK') { prefix = 'NEWLINE'; } else if (last_type === 'TK_END_EXPR') { print_space(); prefix = 'NEWLINE'; } if (last_type !== 'TK_END_BLOCK' && in_array(token_text.toLowerCase(), ['else', 'catch', 'finally'])) { print_newline(); } else if (in_array(token_text, line_starters) || prefix === 'NEWLINE') { if (last_text === 'else') { // no need to force newline on else break print_space(); } else if ((last_type === 'TK_START_EXPR' || last_text === '=') && token_text === 'function') { // no need to force newline on 'function': (function // DONOTHING } else if (last_type === 'TK_WORD' && (last_text === 'return' || last_text === 'throw')) { // no newline between 'return nnn' print_space(); } else if (last_type !== 'TK_END_EXPR') { if ((last_type !== 'TK_START_EXPR' || token_text !== 'var') && last_text !== ':') { // no need to force newline on 'var': for (var x = 0...) if (token_text === 'if' && last_type === 'TK_WORD' && last_word === 'else') { // no newline for } else if { print_space(); } else { print_newline(); } } } else { if (in_array(token_text, line_starters) && last_text !== ')') { print_newline(); } } } else if (prefix === 'SPACE') { print_space(); } print_token(); last_word = token_text; if (token_text === 'var') { var_line = true; var_line_tainted = false; } break; case 'TK_END_COMMAND': print_token(); var_line = false; break; case 'TK_STRING': if (last_type === 'TK_START_BLOCK' || last_type === 'TK_END_BLOCK') { print_newline(); } else if (last_type === 'TK_WORD') { print_space(); } print_token(); break; case 'TK_OPERATOR': var start_delim = true; var end_delim = true; if (var_line && token_text !== ',') { var_line_tainted = true; if (token_text === ':') { var_line = false; } } if (token_text === ':' && in_case) { print_token(); // colon really asks for separate treatment print_newline(); break; } in_case = false; if (token_text === ',') { if (var_line) { if (var_line_tainted) { print_token(); print_newline(); var_line_tainted = false; } else { print_token(); print_space(); } } else if (last_type === 'TK_END_BLOCK') { print_token(); print_newline(); } else { if (current_mode === 'BLOCK') { print_token(); print_newline(); } else { // EXPR od DO_BLOCK print_token(); print_space(); } } break; } else if (token_text === '--' || token_text === '++') { // unary operators special case if (last_text === ';') { // space for (;; ++i) start_delim = true; end_delim = false; } else { start_delim = false; end_delim = false; } } else if (token_text === '!' && last_type === 'TK_START_EXPR') { // special case handling: if (!a) start_delim = false; end_delim = false; } else if (last_type === 'TK_OPERATOR') { start_delim = false; end_delim = false; } else if (last_type === 'TK_END_EXPR') { start_delim = true; end_delim = true; } else if (token_text === '.') { // decimal digits or object.property start_delim = false; end_delim = false; } else if (token_text === ':') { // zz: xx // can't differentiate ternary op, so for now it's a ? b: c; without space before colon if (last_text.match(/^\d+$/)) { // a little help for ternary a ? 1 : 0; start_delim = true; } else { start_delim = false; } } if (start_delim) { print_space(); } print_token(); if (end_delim) { print_space(); } break; case 'TK_BLOCK_COMMENT': print_newline(); print_token(); print_newline(); break; case 'TK_COMMENT': // print_newline(); print_space(); print_token(); print_newline(); break; case 'TK_UNKNOWN': print_token(); break; } last_type = token_type; last_text = token_text; } return output.join(''); }
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S10.1.5_A2.3_T2; * @section: 10.1.5, 15.1; * @assertion: Global object properties have attributes { DontEnum }; * @description: Global execution context - Function Properties; */ var evalStr = '//CHECK#1\n'+ 'for (var x in this) {\n'+ ' if ( x === \'eval\' ) {\n'+ ' $ERROR("#1: \'eval\' have attribute DontEnum");\n'+ ' } else if ( x === \'parseInt\' ) {\n'+ ' $ERROR("#1: \'parseInt\' have attribute DontEnum");\n'+ ' } else if ( x === \'parseFloat\' ) {\n'+ ' $ERROR("#1: \'parseFloat\' have attribute DontEnum");\n'+ ' } else if ( x === \'isNaN\' ) {\n'+ ' $ERROR("#1: \'isNaN\' have attribute DontEnum");\n'+ ' } else if ( x === \'isFinite\' ) {\n'+ ' $ERROR("#1: \'isFinite\' have attribute DontEnum");\n'+ ' } else if ( x === \'decodeURI\' ) {\n'+ ' $ERROR("#1: \'decodeURI\' have attribute DontEnum");\n'+ ' } else if ( x === \'decodeURIComponent\' ) {\n'+ ' $ERROR("#1: \'decodeURIComponent\' have attribute DontEnum");\n'+ ' } else if ( x === \'encodeURI\' ) {\n'+ ' $ERROR("#1: \'encodeURI\' have attribute DontEnum");\n'+ ' } else if ( x === \'encodeURIComponent\' ) {\n'+ ' $ERROR("#1: \'encodeURIComponent\' have attribute DontEnum");\n'+ ' }\n'+ '}\n'; eval(evalStr);
var Surface = require('@src/traces/surface'); var Lib = require('@src/lib'); describe('Test surface', function() { 'use strict'; describe('supplyDefaults', function() { var supplyDefaults = Surface.supplyDefaults; var defaultColor = '#444', layout = {}; 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 fill \'x\' and \'y\' if not provided', function() { traceIn = { z: [[1, 2, 3], [2, 1, 2]] }; supplyDefaults(traceIn, traceOut, defaultColor, layout); expect(traceOut.x).toEqual([0, 1, 2]); expect(traceOut.y).toEqual([0, 1]); }); 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]], zauto: false, zmin: 0, zmax: 10, cauto: true, cmin: -10, cmax: 20 }; supplyDefaults(traceIn, traceOut, defaultColor, layout); expect(traceOut.cauto).toEqual(true); 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, {calendar: 'islamic'}); // 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'); }); }); });
import About from "./about.json"; import CongratsModal from "./congrats-modal.json"; import Home from "./home.json"; import MainMenu from "./menu.json"; import Map from "./map.json"; import NewEventModal from "./new-event-modal.json"; import Team from "./team.json"; import Partners from "./partners.json"; import Faq from "./faq.json"; import Admin from "./admin.json"; import Whitepaper from "./whitepaper"; import Categories from "./categories.json"; import Video from "./video.json"; export default { About, CongratsModal, Home, MainMenu, Map, NewEventModal, Team, Partners, Faq, Admin, Whitepaper, Categories, Video };
/** * Terminus.js * Copyright © 2012 Ramón Lamana */ define(function(require) { 'use strict'; var Promise = require('core/promise'); var Events = require('core/events'); /** * @class */ var InputStream = function() { this.events = new Events(); this._buffer = []; // Default reader function this.reader = function(promise) { var data = this._buffer.join(''); this._buffer = []; promise.done(data); }; }; InputStream.prototype = { events: null, /** * @return {Promise} */ read: function() { var promise = new Promise(); // Call reader function this._reader.call(this, promise); this.events.emit('read'); return promise; }, /** * Set reader function. * This function receives promise. * function(promise){} */ set reader(func) { this._reader = func; }, get reader() { return this._reader; }, /** * Connects an output stream with this input stream */ pipe: function(outputstream) { var self = this; outputstream.writer = function(data) { self._buffer.push(data); }; return this; } }; return InputStream; });
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; const common = require('../common'); if (!common.hasCrypto) common.skip('missing crypto'); const assert = require('assert'); const tls = require('tls'); const fs = require('fs'); const util = require('util'); const join = require('path').join; const options = { key: fs.readFileSync(join(common.fixturesDir, 'keys', 'agent5-key.pem')), cert: fs.readFileSync(join(common.fixturesDir, 'keys', 'agent5-cert.pem')), ca: [ fs.readFileSync(join(common.fixturesDir, 'keys', 'ca2-cert.pem')) ] }; const server = tls.createServer(options, function(cleartext) { cleartext.end('World'); }); server.listen(0, common.mustCall(function() { const socket = tls.connect({ port: this.address().port, rejectUnauthorized: false }, common.mustCall(function() { const peerCert = socket.getPeerCertificate(); console.error(util.inspect(peerCert)); assert.strictEqual(peerCert.subject.CN, 'Ádám Lippai'); server.close(); })); socket.end('Hello'); }));
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S12.6.1_A5; * @section: 12.6.1; * @assertion: After "do-while" is broken, (normal, V, empty) is returned; * @description: Using eval; */ __evaluated = eval("do {__in__do__before__break=1; break; __in__do__after__break=2;} while(0)"); ////////////////////////////////////////////////////////////////////////////// //CHECK#1 if (__in__do__before__break !== 1) { $ERROR('#1: __in__do__before__break === 1. Actual: __in__do__before__break ==='+ __in__do__before__break ); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#2 if (typeof __in__do__after__break !== "undefined") { $ERROR('#2: typeof __in__do__after__break === "undefined". Actual: typeof __in__do__after__break ==='+ typeof __in__do__after__break ); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#3 if (__evaluated !== 1) { $ERROR('#3: __evaluated === 1. Actual: __evaluated ==='+ __evaluated ); } // //////////////////////////////////////////////////////////////////////////////
/** * Copyright 2015 Telerik AD * * 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. */ (function(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["es-PE"] = { name: "es-PE", numberFormat: { pattern: ["-n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], percent: { pattern: ["-n %","n %"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "%" }, currency: { pattern: ["$ -n","$ n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "S/." } }, calendars: { standard: { days: { names: ["domingo","lunes","martes","miércoles","jueves","viernes","sábado"], namesAbbr: ["dom","lun","mar","mié","jue","vie","sáb"], namesShort: ["do","lu","ma","mi","ju","vi","sá"] }, months: { names: ["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre",""], namesAbbr: ["ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic",""] }, AM: ["a.m.","a.m.","A.M."], PM: ["p.m.","p.m.","P.M."], patterns: { d: "dd/MM/yyyy", D: "dddd, dd' de 'MMMM' de 'yyyy", F: "dddd, dd' de 'MMMM' de 'yyyy hh:mm:ss tt", g: "dd/MM/yyyy hh:mm tt", G: "dd/MM/yyyy hh:mm:ss tt", m: "d' de 'MMMM", M: "d' de 'MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "hh:mm tt", T: "hh:mm:ss tt", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM' de 'yyyy", Y: "MMMM' de 'yyyy" }, "/": "/", ":": ":", firstDay: 1 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
import Immutable, { Map, List, is } from 'immutable' import { Reactor, Store } from '../src/main' import { getOption } from '../src/reactor/fns' import { toImmutable } from '../src/immutable-helpers' import { PROD_OPTIONS, DEBUG_OPTIONS } from '../src/reactor/records' import { NoopLogger, ConsoleGroupLogger } from '../src/logging' describe('Reactor', () => { it('should construct without \'new\'', () => { var reactor = Reactor() expect(reactor instanceof Reactor).toBe(true) }) describe('debug and options flags', () => { it('should create a reactor with PROD_OPTIONS', () => { var reactor = new Reactor() expect(reactor.reactorState.get('debug')).toBe(false) expect(is(reactor.reactorState.get('options'), PROD_OPTIONS)).toBe(true) }) it('should create a reactor with DEBUG_OPTIONS', () => { var reactor = new Reactor({ debug: true, }) expect(reactor.reactorState.get('debug')).toBe(true) expect(is(reactor.reactorState.get('options'), DEBUG_OPTIONS)).toBe(true) }) it('should override PROD options', () => { var reactor = new Reactor({ options: { logDispatches: true, }, }) expect(getOption(reactor.reactorState, 'logDispatches')).toBe(true) expect(getOption(reactor.reactorState, 'logAppState')).toBe(false) expect(getOption(reactor.reactorState, 'logDirtyStores')).toBe(false) expect(getOption(reactor.reactorState, 'throwOnUndefinedActionType')).toBe(false) expect(getOption(reactor.reactorState, 'throwOnUndefinedStoreReturnValue')).toBe(false) expect(getOption(reactor.reactorState, 'throwOnNonImmutableStore')).toBe(false) expect(getOption(reactor.reactorState, 'throwOnDispatchInDispatch')).toBe(false) }) it('should override DEBUG options', () => { var reactor = new Reactor({ debug: true, options: { logDispatches: false, throwOnDispatchInDispatch: false, }, }) expect(getOption(reactor.reactorState, 'logDispatches')).toBe(false) expect(getOption(reactor.reactorState, 'logAppState')).toBe(true) expect(getOption(reactor.reactorState, 'logDirtyStores')).toBe(true) expect(getOption(reactor.reactorState, 'throwOnUndefinedActionType')).toBe(true) expect(getOption(reactor.reactorState, 'throwOnUndefinedStoreReturnValue')).toBe(true) expect(getOption(reactor.reactorState, 'throwOnNonImmutableStore')).toBe(true) expect(getOption(reactor.reactorState, 'throwOnDispatchInDispatch')).toBe(false) }) describe('custom logging', () => { var handler beforeEach(() => { handler = { dispatchStart() {}, dispatchError() {}, dispatchEnd() {}, } spyOn(handler, 'dispatchStart') spyOn(handler, 'dispatchError') spyOn(handler, 'dispatchEnd') }) afterEach(() => { handler = null }) it('should use dispatchStart on the provided logging handler if defined', () => { var reactor = new Reactor({ debug: true, logger: handler, }) reactor.dispatch('setTax', 5) expect(handler.dispatchStart).toHaveBeenCalled() }) it('should use dispatchEnd on the provided logging handler if defined', () => { var reactor = new Reactor({ debug: true, logger: handler, }) reactor.dispatch('setTax', 5) expect(handler.dispatchEnd).toHaveBeenCalled() }) it('should use dispatchError on the provided logging handler if defined', () => { var reactor = new Reactor({ debug: true, logger: handler, options: { throwOnUndefinedActionType: false, }, }) try { reactor.dispatch(undefined) } catch (e) { expect(handler.dispatchError).toHaveBeenCalled() } }) it('should noop when a logging function is not defined on the custom implementation', () => { var reactor = new Reactor({ debug: true, logger: { dispatchStart() {}, }, options: { throwOnUndefinedActionType: false, }, }) expect(() => { reactor.dispatch('setTax', 5) }).not.toThrow() }) it('should properly bind context to the logging function', () => { const loggerSpy = jasmine.createSpy() function Logger() { } Logger.prototype.log = function() { loggerSpy() } Logger.prototype.dispatchStart = function() { this.log() } var reactor = new Reactor({ debug: true, logger: new Logger(), }) reactor.dispatch('setTax', 5) expect(loggerSpy).toHaveBeenCalled() }) }) }) describe('options', () => { describe('throwOnUndefinedActionType', () => { it('should NOT throw when `false`', () => { var reactor = new Reactor({ options: { throwOnUndefinedActionType: false, }, }) expect(() => { reactor.dispatch(undefined) }).not.toThrow() }) it('should throw when `true`', () => { var reactor = new Reactor({ options: { throwOnUndefinedActionType: true, }, }) expect(() => { reactor.dispatch(undefined) }).toThrow() }) }) describe('throwOnUndefinedStoreReturnValue', () => { it('should NOT throw during `registerStores`, `dispatch` or `reset` when `false`', () => { var reactor = new Reactor({ options: { throwOnUndefinedStoreReturnValue: false, }, }) expect(() => { reactor.registerStores({ store: Store({ getInitialState() { return undefined }, initialize() { this.on('action', () => undefined) }, }), }) reactor.dispatch('action') reactor.reset() }).not.toThrow() }) it('should throw during `registerStores` when `true`', () => { var reactor = new Reactor({ options: { throwOnUndefinedStoreReturnValue: true, }, }) expect(() => { reactor.registerStores({ store: Store({ getInitialState() { return undefined }, initialize() { this.on('action', () => undefined) }, }), }) }).toThrow() }) it('should throw during `dispatch` when `true`', () => { var reactor = new Reactor({ options: { throwOnUndefinedStoreReturnValue: true, }, }) expect(() => { reactor.registerStores({ store: Store({ getInitialState() { return undefined }, initialize() { this.on('action', () => undefined) }, }), }) }).toThrow() }) it('should throw during `reset` when `true`', () => { var reactor = new Reactor({ options: { throwOnUndefinedStoreReturnValue: true, }, }) expect(() => { reactor.registerStores({ store: Store({ getInitialState() { return 1 }, handleReset() { return undefined }, }), }) reactor.reset() }).toThrow() }) }) describe('throwOnNonImmutableStore', () => { it('should NOT throw during `registerStores` or `reset` when `false`', () => { var reactor = new Reactor({ options: { throwOnNonImmutableStore: false, }, }) expect(() => { reactor.registerStores({ store: Store({ getInitialState() { return { foo: 'bar' } }, handleReset() { return { foo: 'baz' } }, }), }) reactor.reset() }).not.toThrow() }) it('should throw during `registerStores` when `true`', () => { var reactor = new Reactor({ options: { throwOnNonImmutableStore: true, }, }) expect(() => { reactor.registerStores({ store: Store({ getInitialState() { return { foo: 'bar' } }, }), }) }).toThrow() }) it('should throw during `reset` when `true`', () => { var reactor = new Reactor({ options: { throwOnNonImmutableStore: true, }, }) expect(() => { reactor.registerStores({ store: Store({ getInitialState() { return 123 }, handleReset() { return { foo: 'baz' } }, }), }) reactor.reset() }).toThrow() }) }) describe('throwOnDispatchInDispatch', () => { it('should NOT throw when `false`', () => { var reactor = new Reactor({ options: { throwOnDispatchInDispatch: false, }, }) expect(() => { reactor.registerStores({ count: Store({ getInitialState() { return 1 }, initialize() { this.on('increment', curr => curr + 1) }, }), }) reactor.observe(['count'], (val) => { if (val % 2 === 0) { reactor.dispatch('increment') } }) reactor.dispatch('increment') expect(reactor.evaluate(['count'])).toBe(3) }).not.toThrow() }) it('should throw when `true`', () => { var reactor = new Reactor({ options: { throwOnDispatchInDispatch: true, }, }) expect(() => { reactor.registerStores({ count: Store({ getInitialState() { return 1 }, initialize() { this.on('increment', curr => curr + 1) }, }), }) reactor.observe(['count'], (val) => { if (val % 2 === 0) { reactor.dispatch('increment') } }) reactor.dispatch('increment') }).toThrow() }) }) }) describe('Reactor with no initial state', () => { var checkoutActions var reactor var subtotalGetter var taxGetter var totalGetter beforeEach(() => { var itemStore = Store({ getInitialState() { return toImmutable({ all: [], }) }, initialize() { this.on('storeError', (state, payload) => { throw new Error('Store Error') }) this.on('addItem', (state, payload) => { return state.update('all', items => { return items.push(Map({ name: payload.name, price: payload.price, })) }) }) }, }) var taxPercentStore = Store({ getInitialState() { return 0 }, initialize() { this.on('setTax', (state, payload) => { return payload }) }, }) reactor = new Reactor({ debug: true, }) reactor.registerStores({ 'items': itemStore, 'taxPercent': taxPercentStore, }) subtotalGetter = [ ['items', 'all'], (items) => { return items.reduce((total, item) => { return total + item.get('price') }, 0) }, ] taxGetter = [ subtotalGetter, ['taxPercent'], (subtotal, taxPercent) => { return (subtotal * (taxPercent / 100)) }, ] totalGetter = [ subtotalGetter, taxGetter, (subtotal, tax) => { return Math.round(subtotal + tax, 2) }, ] checkoutActions = { addItem(name, price) { reactor.dispatch('addItem', { name: name, price: price, }) }, setTaxPercent(percent) { reactor.dispatch('setTax', percent) }, } }) afterEach(() => { reactor.reset() }) describe('initialization', () => { it('should initialize with the core level computeds', () => { expect(reactor.evaluateToJS(['items', 'all'])).toEqual([]) expect(reactor.evaluate(['taxPercent'])).toEqual(0) }) it('should return the whole state when calling reactor.evaluate([])', () => { var state = reactor.evaluate([]) var expected = Map({ items: Map({ all: List(), }), taxPercent: 0, }) expect(Immutable.is(state, expected)).toBe(true) }) it('should return the whole state coerced to JS when calling reactor.evaluateToJS()', () => { var state = reactor.evaluateToJS([]) var expected = { items: { all: [], }, taxPercent: 0, } expect(state).toEqual(expected) }) }) describe('when dispatching a relevant action', () => { var item = { name: 'item 1', price: 10, } it('should update all state', () => { checkoutActions.addItem(item.name, item.price) expect(reactor.evaluateToJS(['items', 'all'])).toEqual([item]) expect(reactor.evaluate(['taxPercent'])).toEqual(0) expect(reactor.evaluate(taxGetter)).toEqual(0) expect(reactor.evaluate(totalGetter)).toEqual(10) }) it('should emit the state of the reactor to a handler registered with observe()', () => { var mockFn = jasmine.createSpy() reactor.observe(mockFn) checkoutActions.addItem(item.name, item.price) var expected = Immutable.fromJS({ items: { all: [ item, ], }, taxPercent: 0, }) var firstCallArg = mockFn.calls.argsFor(0)[0] expect(mockFn.calls.count()).toBe(1) expect(Immutable.is(firstCallArg, expected)).toBe(true) }) it('should not emit to the outputStream if state does not change after a dispatch', () => { var mockFn = jasmine.createSpy() reactor.observe(mockFn) reactor.dispatch('noop', {}) expect(mockFn.calls.count()).toEqual(0) }) it('should raise an error if already dispatching another action', () => { reactor.observe([], state => reactor.dispatch('noop', {})) expect(() => checkoutActions.setTaxPercent(5)).toThrow( new Error('Dispatch may not be called while a dispatch is in progress')) }) it('should keep working after it raised for dispatching while dispatching', () => { var unWatchFn = reactor.observe([], state => reactor.dispatch('noop', {})) expect(() => checkoutActions.setTaxPercent(5)).toThrow( new Error('Dispatch may not be called while a dispatch is in progress')) unWatchFn() expect(() => { checkoutActions.setTaxPercent(5) }).not.toThrow( new Error('Dispatch may not be called while a dispatch is in progress')) }) it('should allow subsequent dispatches if a store throws an error', () => { try { reactor.dispatch('storeError') } catch (e) {} // eslint-disable-line expect(() => reactor.dispatch('setTax', 5)).not.toThrow() }) it('should allow subsequent dispatches if a dispatched action doesnt cause state change', () => { reactor.dispatch('noop') expect(() => reactor.dispatch('setTax', 5)).not.toThrow() }) it('should allow subsequent dispatches if an observer throws an error', () => { var unWatchFn = reactor.observe([], state => { throw new Error('observer error') }) try { checkoutActions.setTaxPercent(1) } catch (e) {} // eslint-disable-line unWatchFn() expect(() => { checkoutActions.setTaxPercent(2) }).not.toThrow() }) }) // when dispatching a relevant action describe('#evaluate', () => { it('should evaluate the empty keyPath', () => { checkoutActions.setTaxPercent(5) var result = reactor.evaluate([]) var expected = Map({ taxPercent: 5, items: Map({ all: List(), }), }) expect(is(result, expected)).toBe(true) }) it('should evaluate a simple keyPath', () => { checkoutActions.setTaxPercent(5) var result = reactor.evaluate(['taxPercent']) expect(result).toBe(5) }) it('should evaluate a simple getter', () => { checkoutActions.setTaxPercent(5) var getter = [ ['taxPercent'], (percent) => percent * 2, ] var result = reactor.evaluate(getter) expect(result).toBe(10) }) it('should evaluate a complex getter', () => { checkoutActions.setTaxPercent(5) checkoutActions.addItem('pants', 100) var result = reactor.evaluate(totalGetter) expect(result).toBe(105) }) it('should evaluate and cache a getter if its underlying stores dont change', () => { var taxPercentSpy = jasmine.createSpy() var subtotalSpy = jasmine.createSpy() var taxPercentGetter = [ ['taxPercent'], t => { taxPercentSpy() return t }, ] subtotalGetter = [ ['items', 'all'], (items) => { subtotalSpy() return items.reduce((total, item) => { return total + item.get('price') }, 0) }, ] checkoutActions.setTaxPercent(5) checkoutActions.addItem('pants', 100) var result1 = reactor.evaluate(taxPercentGetter) var result2 = reactor.evaluate(subtotalGetter) expect(result1).toBe(5) expect(result2).toBe(100) expect(taxPercentSpy.calls.count()).toEqual(1) expect(subtotalSpy.calls.count()).toEqual(1) checkoutActions.setTaxPercent(6) var result3 = reactor.evaluate(taxPercentGetter) var result4 = reactor.evaluate(subtotalGetter) expect(result3).toBe(6) expect(result4).toBe(100) expect(taxPercentSpy.calls.count()).toEqual(2) expect(subtotalSpy.calls.count()).toEqual(1) }) it('should update cache with updated item after action', () => { const lastItemGetter = [['items', 'all'], (items) => items.last()] // ensure its in cache const lastItemBefore = reactor.evaluate(lastItemGetter) const cacheEntryBefore = reactor.reactorState.cache.lookup(lastItemGetter) expect(lastItemBefore === cacheEntryBefore.value).toBe(true) checkoutActions.addItem('potato', 0.80) const lastItemAfter = reactor.evaluate(lastItemGetter) const cacheEntryAfter = reactor.reactorState.cache.lookup(lastItemGetter) expect(lastItemAfter === cacheEntryAfter.value).toBe(true) // sanity check that lastItem actually changed for completeness expect(lastItemAfter !== lastItemBefore).toBe(true) }) }) describe('#observe', () => { it('should invoke a change handler if the specific keyPath changes', () => { var mockFn = jasmine.createSpy() reactor.observe(['taxPercent'], mockFn) checkoutActions.setTaxPercent(5) expect(mockFn.calls.count()).toEqual(1) expect(mockFn.calls.argsFor(0)).toEqual([5]) }) it('should not invoke a change handler if another keyPath changes', () => { var mockFn = jasmine.createSpy() reactor.observe(['taxPercent'], mockFn) checkoutActions.addItem('item', 1) expect(mockFn.calls.count()).toEqual(0) }) it('should invoke a change handler if a getter value changes', () => { var mockFn = jasmine.createSpy() checkoutActions.addItem('item', 100) reactor.observe(totalGetter, mockFn) checkoutActions.setTaxPercent(5) expect(mockFn.calls.count()).toEqual(1) expect(mockFn.calls.argsFor(0)).toEqual([105]) }) it('should only invoke a handler once if multiple underlying stores update ', () => { var mockFn = jasmine.createSpy() reactor.observe(totalGetter, mockFn) reactor.batch(() => { checkoutActions.addItem('item', 100) checkoutActions.setTaxPercent(5) }) expect(mockFn.calls.count()).toEqual(1) expect(mockFn.calls.argsFor(0)).toEqual([105]) }) it('should allow multiple getter observation without interference', () => { var subtotalSpy = jasmine.createSpy() var taxPercentSpy = jasmine.createSpy() var taxPercentGetter = ['taxPercent'] reactor.observe(subtotalGetter, subtotalSpy) reactor.observe(taxPercentGetter, taxPercentSpy) checkoutActions.addItem('item', 100) expect(subtotalSpy.calls.count()).toEqual(1) expect(subtotalSpy.calls.argsFor(0)).toEqual([100]) checkoutActions.setTaxPercent(5) expect(taxPercentSpy.calls.count()).toEqual(1) expect(taxPercentSpy.calls.argsFor(0)).toEqual([5]) // subtotal spy didn't get called again expect(subtotalSpy.calls.count()).toEqual(1) }) it('should not invoke a change handler if a getters deps dont change', () => { var mockFn = jasmine.createSpy() reactor.observe(['taxPercent'], mockFn) checkoutActions.addItem('item', 100) expect(mockFn.calls.count()).toEqual(0) }) it('should return an unwatch function', () => { var mockFn = jasmine.createSpy() checkoutActions.addItem('item', 100) var unwatch = reactor.observe(totalGetter, mockFn) expect(mockFn.calls.count()).toEqual(0) unwatch() checkoutActions.setTaxPercent(5) expect(mockFn.calls.count()).toEqual(0) }) it('should trigger an observer for a late registered store', () => { var mockFn = jasmine.createSpy() var reactor = new Reactor() reactor.observe(['test'], mockFn) expect(mockFn.calls.count()).toEqual(0) reactor.registerStores({ test: Store({ getInitialState() { return 1 }, }), }) expect(mockFn.calls.count()).toEqual(1) expect(mockFn.calls.argsFor(0)).toEqual([1]) }) it('should trigger an observer for a late registered store for the identity getter', () => { var observedValue var expectedHandlerValue var mockFn = jasmine.createSpy() var reactor = new Reactor() reactor.observe([], mockFn) expect(mockFn.calls.count()).toEqual(0) reactor.registerStores({ test: Store({ getInitialState() { return 1 }, initialize() { this.on('increment', (state) => state + 1) }, }), }) // it should call the observer after the store has been registered expect(mockFn.calls.count()).toEqual(1) observedValue = mockFn.calls.argsFor(0)[0] expectedHandlerValue = Map({ test: 1, }) expect(is(observedValue, expectedHandlerValue)).toBe(true) // it should call the observer again when the store handles an action reactor.dispatch('increment') expect(mockFn.calls.count()).toEqual(2) observedValue = mockFn.calls.argsFor(1)[0] expectedHandlerValue = Map({ test: 2, }) expect(is(observedValue, expectedHandlerValue)).toBe(true) }) }) describe('#unobserve', () => { it('should unobserve an observer called with only a handle with the getter `[]`', () => { var mockFn = jasmine.createSpy() reactor.observe(mockFn) checkoutActions.setTaxPercent(5) expect(mockFn.calls.count()).toEqual(1) reactor.unobserve([]) checkoutActions.setTaxPercent(6) expect(mockFn.calls.count()).toEqual(1) }) it('should unobserve the identity getter by value', () => { var mockFn = jasmine.createSpy() reactor.observe([], mockFn) checkoutActions.setTaxPercent(5) expect(mockFn.calls.count()).toEqual(1) reactor.unobserve([]) checkoutActions.setTaxPercent(6) expect(mockFn.calls.count()).toEqual(1) }) it('should unobserve a keyPath by reference', () => { var mockFn = jasmine.createSpy() var keyPath = ['taxPercent'] reactor.observe(keyPath, mockFn) checkoutActions.setTaxPercent(5) expect(mockFn.calls.count()).toEqual(1) reactor.unobserve(keyPath) checkoutActions.setTaxPercent(6) expect(mockFn.calls.count()).toEqual(1) }) it('should unobserve a keyPath by value', () => { var mockFn = jasmine.createSpy() reactor.observe(['taxPercent'], mockFn) checkoutActions.setTaxPercent(5) expect(mockFn.calls.count()).toEqual(1) reactor.unobserve(['taxPercent']) checkoutActions.setTaxPercent(6) expect(mockFn.calls.count()).toEqual(1) }) it('should unobserve a keyPath, handler combination', () => { var mockFn1 = jasmine.createSpy() var mockFn2 = jasmine.createSpy() var keyPath = ['taxPercent'] reactor.observe(keyPath, mockFn1) reactor.observe(keyPath, mockFn2) checkoutActions.setTaxPercent(5) expect(mockFn1.calls.count()).toEqual(1) expect(mockFn2.calls.count()).toEqual(1) reactor.unobserve(keyPath, mockFn2) checkoutActions.setTaxPercent(6) expect(mockFn1.calls.count()).toEqual(2) }) it('should unobserve a getter by reference', () => { var mockFn = jasmine.createSpy() reactor.observe(subtotalGetter, mockFn) checkoutActions.addItem('foo', 5) expect(mockFn.calls.count()).toEqual(1) expect(mockFn.calls.argsFor(0)).toEqual([5]) reactor.unobserve(subtotalGetter) checkoutActions.addItem('bar', 10) expect(mockFn.calls.count()).toEqual(1) }) it('should unobserve a getter, handler combination', () => { var mockFn1 = jasmine.createSpy() var mockFn2 = jasmine.createSpy() reactor.observe(subtotalGetter, mockFn1) reactor.observe(subtotalGetter, mockFn2) checkoutActions.addItem('foo', 5) expect(mockFn1.calls.count()).toEqual(1) expect(mockFn2.calls.count()).toEqual(1) expect(mockFn1.calls.argsFor(0)).toEqual([5]) expect(mockFn2.calls.argsFor(0)).toEqual([5]) reactor.unobserve(subtotalGetter, mockFn2) checkoutActions.addItem('bar', 10) expect(mockFn1.calls.count()).toEqual(2) expect(mockFn2.calls.count()).toEqual(1) }) it('should allow a notify() after an unobserve during a handler', () => { var mockFn1 = jasmine.createSpy() var mockFn2 = jasmine.createSpy() var unwatchFn2 reactor.observe(subtotalGetter, (val) => { unwatchFn2() mockFn1(val) }) unwatchFn2 = reactor.observe(subtotalGetter, (val) => { mockFn2(val) }) expect(function() { checkoutActions.addItem('foo', 5) expect(mockFn1.calls.count()).toEqual(1) expect(mockFn2.calls.count()).toEqual(0) expect(mockFn1.calls.argsFor(0)).toEqual([5]) }).not.toThrow() }) }) }) // Reactor with no initial state describe('reactor#reset', () => { var reactor beforeEach(() => { var standardStore = Store({ getInitialState() { return toImmutable([]) }, initialize() { this.on('addItem', (state, item) => { return state.push(item) }) }, }) var persistentStore = Store({ getInitialState() { return toImmutable([]) }, initialize() { this.on('addItem', (state, item) => { return state.push(item) }) }, handleReset(state) { return state }, }) reactor = new Reactor({ debug: true, }) reactor.registerStores({ standard: standardStore, persistent: persistentStore, }) }) afterEach(() => { reactor.reset() }) it('should go back to initial state for normal stores', () => { var item = { foo: 'bar' } reactor.dispatch('addItem', item) expect(reactor.evaluateToJS(['standard'])).toEqual([item]) reactor.reset() expect(reactor.evaluateToJS(['standard'])).toEqual([]) }) it('should respect the handleReset method for stores that override it', () => { var item = { foo: 'bar' } reactor.dispatch('addItem', item) expect(reactor.evaluateToJS(['persistent'])).toEqual([item]) reactor.reset() expect(reactor.evaluateToJS(['persistent'])).toEqual([item]) }) it('should be able to reset and call an unwatch() function without erroring', () => { const spy = jasmine.createSpy() const unobserve = reactor.observe(['standard'], () => spy()) reactor.reset() expect(function() { unobserve() }).not.toThrow() }) }) describe('when a reactor is observing mutable values', () => { var reactor var observeSpy beforeEach(() => { observeSpy = jasmine.createSpy('observe') var mapStore = Store({ getInitialState() { return toImmutable({}) }, initialize() { this.on('set', (state, payload) => { return state.set(payload.key, payload.value) }) }, }) var keyStore = Store({ getInitialState() { return 'foo' }, initialize() { this.on('setKey', (state, payload) => { return payload }) }, }) reactor = new Reactor({ debug: true, }) reactor.registerStores({ mapStore: mapStore, keyStore: keyStore, }) }) afterEach(() => { reactor.reset() }) it('should go back to initial state for normal stores', () => { function Foo(val) { this.val = val } var item = new Foo('bar') var item2 = new Foo('baz') var getter = [ ['mapStore'], ['keyStore'], (map, key) => { return map.get(key) }, ] reactor.evaluate(getter) reactor.observe(getter, (fooValue) => { observeSpy(fooValue) }) reactor.dispatch('set', { key: 'foo', value: item, }) expect(observeSpy.calls.count()).toBe(1) reactor.dispatch('set', { key: 'foo', value: item2, }) expect(observeSpy.calls.count()).toBe(2) }) }) describe('a reactor with a store that has `null` as its initial state', () => { var reactor beforeEach(() => { var nullStateStore = new Store({ getInitialState() { return null }, initialize() { this.on('set', (_, val) => val) }, }) reactor = new Reactor({ debug: true, }) reactor.registerStores({ test: nullStateStore, }) }) afterEach(() => { reactor.reset() }) it('the store should respond to a registered action', () => { reactor.dispatch('set', 'foo') expect(reactor.evaluate(['test'])).toBe('foo') }) it('the store should have the same initial state for an action it doesnt handle', () => { reactor.dispatch('unknown', 'foo') expect(reactor.evaluate(['test'])).toBe(null) }) }) describe('when debug is true and a store has a handler for an action but returns undefined', () => { var reactor beforeEach(() => { var undefinedStore = new Store({ getInitialState() { return 1 }, initialize() { this.on('set', (_, val) => undefined) }, }) reactor = new Reactor({ debug: true, }) reactor.registerStores({ test: undefinedStore, }) }) afterEach(() => { reactor.reset() }) it('should throw an error', function() { expect(function() { reactor.dispatch('set', 'foo') }).toThrow() }) }) describe('when debug is true and a store has a handler for an action but throws', () => { var reactor beforeEach(() => { spyOn(ConsoleGroupLogger, 'dispatchError') var throwingStore = new Store({ getInitialState() { return 1 }, initialize() { this.on('set', (_, val) => {throw new Error('Error during action handling')}) }, }) reactor = new Reactor({ debug: true, }) reactor.registerStores({ test: throwingStore, }) }) afterEach(() => { reactor.reset() }) it('should log and throw an error', function() { expect(function() { reactor.dispatch('set', 'foo') }).toThrow(new Error('Error during action handling')) expect(ConsoleGroupLogger.dispatchError).toHaveBeenCalledWith(reactor.reactorState, 'Error during action handling') }) }) describe('#registerStores', () => { var reactor afterEach(() => { reactor.reset() }) describe('when another store is already registered for the same id', () => { var store1 var store2 beforeEach(() => { spyOn(console, 'warn') store1 = new Store() store2 = new Store() reactor = new Reactor({ debug: true, }) reactor.registerStores({ store1: store1, }) }) it('should warn', function() { reactor.registerStores({ store1: store2, }) /* eslint-disable no-console */ expect(console.warn).toHaveBeenCalled() /* eslint-enable no-console */ }) }) describe('when the stores getInitialState method returns a non immutable object', () => { var store1 beforeEach(() => { store1 = new Store({ getInitialState() { return { foo: 'bar', } }, }) reactor = new Reactor({ debug: true, }) }) it('should throw an error', function() { expect(function() { reactor.registerStores({ store1: store1, }) }).toThrow() }) }) describe('when calling registerStores with an observer', () => { var store1 var observeSpy beforeEach(() => { observeSpy = jasmine.createSpy() store1 = new Store({ getInitialState() { return 'foo' }, initialize() { this.on('set', (_, val) => val) }, }) reactor = new Reactor({ debug: true, }) reactor.observe(['test'], observeSpy) }) it('should notify observers immediately', function() { var notify = true reactor.registerStores({ test: store1, }, notify) expect(observeSpy.calls.count()).toEqual(1) expect(observeSpy).toHaveBeenCalledWith('foo') }) }) }) describe('#registerStore', () => { var reactor var store1 beforeEach(() => { store1 = new Store({ getInitialState() { return 'foo' }, }) reactor = new Reactor({ debug: true, }) }) afterEach(() => { reactor.reset() }) it('it should register a store by id', () => { reactor.registerStore('test', store1) expect(reactor.evaluate(['test'])).toBe('foo') }) }) describe('#reset', () => { var reactor describe('when a store doesnt define a handleReset method', () => { var store1 beforeEach(() => { store1 = new Store({ getInitialState() { return 'foo' }, initialize() { this.on('set', (_, val) => val) }, }) reactor = new Reactor({ debug: true, }) reactor.registerStores({ test: store1, }) }) it('should fallback to the getInitialState', () => { reactor.dispatch('set', 'bar') expect(reactor.evaluate(['test'])).toBe('bar') reactor.reset() expect(reactor.evaluate(['test'])).toBe('foo') }) it('should reset all observers as well', () => { var observeSpy = jasmine.createSpy() reactor.observe(['test'], observeSpy) reactor.dispatch('set', 2) expect(observeSpy.calls.count()).toBe(1) reactor.reset() reactor.dispatch('set', 3) expect(observeSpy.calls.count()).toBe(1) }) }) describe('when a store defines a handleReset method', () => { var store1 beforeEach(() => { store1 = new Store({ getInitialState() { return 'foo' }, initialize() { this.on('set', (_, val) => val) }, handleReset() { return 'reset' }, }) reactor = new Reactor({ debug: true, }) reactor.registerStores({ test: store1, }) }) it('should fallback to the getInitialState', () => { reactor.dispatch('set', 'bar') expect(reactor.evaluate(['test'])).toBe('bar') reactor.reset() expect(reactor.evaluate(['test'])).toBe('reset') }) }) describe('when the handleReset method returns undefined', () => { var store1 beforeEach(() => { store1 = new Store({ getInitialState() { return 'foo' }, initialize() { this.on('set', (_, val) => val) }, handleReset() { }, }) reactor = new Reactor({ debug: true, }) reactor.registerStores({ test: store1, }) }) it('should throw an error', () => { expect(function() { reactor.reset() }).toThrow() }) }) describe('when the handleReset method returns a non immutable object', () => { var store1 beforeEach(() => { store1 = new Store({ getInitialState() { return 'foo' }, initialize() { this.on('set', (_, val) => val) }, handleReset() { return { foo: 'bar', } }, }) reactor = new Reactor({ debug: true, }) reactor.registerStores({ test: store1, }) }) it('should throw an error', () => { expect(function() { reactor.reset() }).toThrow() }) }) }) describe('serialize/loadState', () => { var reactor var stores beforeEach(() => { reactor = new Reactor({ debug: true, }) stores = { mapStore: Store({ getInitialState() { return Immutable.Map([ [1, 'one'], [2, 'two'], ]) }, initialize() { this.on('clear', state => null) }, serialize(state) { if (!state) { return state } return state.entrySeq().toJS() }, deserialize(state) { return Immutable.Map(state) }, }), stringStore: Store({ getInitialState() { return 'foo' }, initialize() { this.on('clear', state => null) }, }), listStore: Store({ getInitialState() { return toImmutable([1, 2, 'three']) }, initialize() { this.on('clear', state => null) }, }), booleanStore: Store({ getInitialState() { return true }, initialize() { this.on('clear', state => null) }, }), } reactor.registerStores(stores) }) afterEach(() => { reactor.reset() }) it('should serialize -> loadState effectively', () => { var serialized = reactor.serialize() var reactor2 = new Reactor() reactor2.registerStores(stores) reactor2.dispatch('clear') expect(Immutable.is(reactor.evaluate([]), reactor2.evaluate([]))).toBe(false) reactor2.loadState(serialized) expect(Immutable.is(reactor.evaluate([]), reactor2.evaluate([]))).toBe(true) }) it('should allow loading of state from outside source', () => { reactor.loadState({ stringStore: 'bar', listStore: [4, 5, 6], }) expect(reactor.evaluateToJS([])).toEqual({ mapStore: { 1: 'one', 2: 'two', }, stringStore: 'bar', listStore: [4, 5, 6], booleanStore: true, }) }) it('should notify observer', () => { var mockFn = jasmine.createSpy() var serialized = reactor.serialize() var reactor2 = new Reactor() reactor2.registerStores(stores) reactor2.dispatch('clear') reactor2.observe(['stringStore'], mockFn) reactor2.loadState(serialized) var firstCallArg = mockFn.calls.argsFor(0) expect(mockFn.calls.count()).toBe(1) expect(Immutable.is(firstCallArg, 'foo')) }) describe('when extending Reactor#serialize and Reactor#loadState', () => { var loadStateSpy = jasmine.createSpy('loadState') var serializeSpy = jasmine.createSpy('serialize') it('should respect the extended methods', () => { class MyReactor extends Reactor { constructor() { super(arguments) } serialize(state) { serializeSpy(state) var serialized = super.serialize(state) return JSON.stringify(serialized) } loadState(state) { loadStateSpy(state) super.loadState(JSON.parse(state)) } } var reactor1 = new MyReactor() reactor1.registerStores(stores) var reactor2 = new MyReactor() reactor2.registerStores(stores) var serialized = reactor1.serialize() reactor2.dispatch('clear') expect(Immutable.is(reactor1.evaluate([]), reactor2.evaluate([]))).toBe(false) reactor2.loadState(serialized) expect(Immutable.is(reactor.evaluate([]), reactor2.evaluate([]))).toBe(true) expect(serializeSpy.calls.count()).toBe(1) expect(loadStateSpy.calls.count()).toBe(1) }) }) describe('when a store returns undefined from serialize/deserialize', () => { beforeEach(() => { reactor = new Reactor() reactor.registerStores({ serializableStore: Store({ getInitialState() { return 'real' }, }), ignoreStore: Store({ getInitialState() { return 'ignore' }, serialize() { return }, deserialize() { return }, }), }) }) it('should not have an entry in the serialized app state', () => { var serialized = reactor.serialize() expect(serialized).toEqual({ serializableStore: 'real', }) }) it('should not load state for a store where deserialize returns undefined', () => { var serialized = { serializableStore: 'changed', ignoreStore: 'changed', } reactor.loadState(serialized) expect(reactor.evaluateToJS([])).toEqual({ serializableStore: 'changed', ignoreStore: 'ignore', }) }) }) }) describe('#batch', () => { var reactor beforeEach(() => { reactor = new Reactor({ debug: true, }) reactor.registerStores({ listStore: Store({ getInitialState() { return toImmutable([]) }, initialize() { this.on('add', (state, item) => state.push(toImmutable(item))) this.on('error', (state, payload) => { throw new Error('store error') }) }, }), }) }) afterEach(() => { reactor.reset() }) it('should execute multiple dispatches within the queue function', () => { reactor.batch(() => { reactor.dispatch('add', 'one') reactor.dispatch('add', 'two') }) expect(reactor.evaluateToJS(['listStore'])).toEqual(['one', 'two']) }) it('should notify observers only once', () => { var observeSpy = jasmine.createSpy() reactor.observe(['listStore'], list => observeSpy(list.toJS())) reactor.batch(() => { reactor.dispatch('add', 'one') reactor.dispatch('add', 'two') }) expect(observeSpy.calls.count()).toBe(1) var firstCallArg = observeSpy.calls.argsFor(0)[0] expect(observeSpy.calls.count()).toBe(1) expect(firstCallArg).toEqual(['one', 'two']) }) it('should allow nested batches and only notify observers once', () => { var observeSpy = jasmine.createSpy() reactor.observe(['listStore'], list => observeSpy(list.toJS())) reactor.batch(() => { reactor.dispatch('add', 'one') reactor.batch(() => { reactor.dispatch('add', 'two') reactor.dispatch('add', 'three') }) }) expect(observeSpy.calls.count()).toBe(1) var firstCallArg = observeSpy.calls.argsFor(0)[0] expect(observeSpy.calls.count()).toBe(1) expect(firstCallArg).toEqual(['one', 'two', 'three']) }) it('should not allow dispatch to be called from an observer', () => { reactor.observe([], state => reactor.dispatch('noop', {})) expect(() => { reactor.batch(() => { reactor.dispatch('add', 'one') reactor.dispatch('add', 'two') }) }).toThrow( new Error('Dispatch may not be called while a dispatch is in progress')) }) it('should keep working after it raised for dispatching while dispatching', () => { var unWatchFn = reactor.observe([], state => reactor.dispatch('noop', {})) expect(() => { reactor.batch(() => { reactor.dispatch('add', 'one') reactor.dispatch('add', 'two') }) }).toThrow( new Error('Dispatch may not be called while a dispatch is in progress')) unWatchFn() expect(() => { reactor.batch(() => { reactor.dispatch('add', 'one') reactor.dispatch('add', 'two') }) }).not.toThrow( new Error('Dispatch may not be called while a dispatch is in progress')) }) it('should allow subsequent dispatches if an error is raised by a store handler', () => { expect(() => { reactor.batch(() => { reactor.dispatch('add', 'one') reactor.dispatch('error') }) }).toThrow(new Error('store error')) expect(() => { reactor.dispatch('add', 'three') }).not.toThrow() }) it('should allow subsequent dispatches if batched action doesnt cause state change', () => { reactor.batch(() => { reactor.dispatch('noop') }) expect(() => reactor.dispatch('add', 'one')).not.toThrow() }) it('should allow subsequent dispatches if an error is raised in an observer', () => { var unWatchFn = reactor.observe([], state => { throw new Error('observe error') }) expect(() => { reactor.batch(() => { reactor.dispatch('add', 'one') reactor.dispatch('add', 'two') }) }).toThrow( new Error('observe error')) unWatchFn() expect(() => { reactor.dispatch('add', 'three') }).not.toThrow() }) }) describe('issue #140 - change observer error case dealing with hashCode collisions', () => { it('observer should be called correctly', () => { var SET_YEAR_GROUP = 'SET_YEAR_GROUP' var LOADED = 'LOADED' var store = Store({ getInitialState: function() { return toImmutable({ yearGroup: 0, shouldLoaded: true, }) }, initialize: function() { this.on(SET_YEAR_GROUP, setYearGroup) this.on(LOADED, loaded) }, }) function setYearGroup(store, payload) { return store .set('yearGroup', payload.yearGroup) .set('shouldLoad', true) } function loaded(store) { return store.set('shouldLoad', false) } var reactor = new Reactor() reactor.registerStores({ uiStore: store }) var output = [] // Record changes to yearGroup reactor.observe(['uiStore', 'yearGroup'], function(y) { output.push(y) }) reactor.dispatch(SET_YEAR_GROUP, {yearGroup: 6}) reactor.dispatch(LOADED) reactor.dispatch(SET_YEAR_GROUP, {yearGroup: 5}) expect(output).toEqual([6, 5]) }) }) describe('#replaceStores', () => { let counter1Store let counter2Store let reactor beforeEach(() => { reactor = new Reactor() counter1Store = new Store({ getInitialState: () => 1, initialize() { this.on('increment1', (state) => state + 1) }, }) counter2Store = new Store({ getInitialState: () => 1, initialize() { this.on('increment2', (state) => state + 1) }, }) reactor.registerStores({ counter1: counter1Store, counter2: counter2Store, }) }) it('should replace the store implementation without mutating the value', () => { let newStore = new Store({ getInitialState: () => 1, initialize() { this.on('increment1', (state) => state + 10) }, }) expect(reactor.evaluate(['counter1'])).toBe(1) reactor.dispatch('increment1') expect(reactor.evaluate(['counter1'])).toBe(2) reactor.replaceStores({ counter1: newStore, }) expect(reactor.evaluate(['counter1'])).toBe(2) reactor.dispatch('increment1') expect(reactor.evaluate(['counter1'])).toBe(12) expect(reactor.evaluate(['counter2'])).toBe(1) }) it('should replace multiple stores', () => { let newStore1 = new Store({ getInitialState: () => 1, initialize() { this.on('increment1', (state) => state + 10) }, }) let newStore2 = new Store({ getInitialState: () => 1, initialize() { this.on('increment2', (state) => state + 20) }, }) expect(reactor.evaluate(['counter1'])).toBe(1) reactor.dispatch('increment1') expect(reactor.evaluate(['counter1'])).toBe(2) reactor.replaceStores({ counter1: newStore1, counter2: newStore2, }) expect(reactor.evaluate(['counter1'])).toBe(2) expect(reactor.evaluate(['counter2'])).toBe(1) reactor.dispatch('increment1') reactor.dispatch('increment2') expect(reactor.evaluate(['counter1'])).toBe(12) expect(reactor.evaluate(['counter2'])).toBe(21) }) }) })
/*global define*/ define([ './CubicRealPolynomial', './DeveloperError', './Math', './QuadraticRealPolynomial' ], function( CubicRealPolynomial, DeveloperError, CesiumMath, QuadraticRealPolynomial) { "use strict"; /** * Defines functions for 4th order polynomial functions of one variable with only real coefficients. * * @exports QuarticRealPolynomial */ var QuarticRealPolynomial = {}; /** * Provides the discriminant of the quartic equation from the supplied coefficients. * * @param {Number} a The coefficient of the 4th order monomial. * @param {Number} b The coefficient of the 3rd order monomial. * @param {Number} c The coefficient of the 2nd order monomial. * @param {Number} d The coefficient of the 1st order monomial. * @param {Number} e The coefficient of the 0th order monomial. * @returns {Number} The value of the discriminant. */ QuarticRealPolynomial.discriminant = function(a, b, c, d, e) { //>>includeStart('debug', pragmas.debug); if (typeof a !== 'number') { throw new DeveloperError('a is a required number.'); } if (typeof b !== 'number') { throw new DeveloperError('b is a required number.'); } if (typeof c !== 'number') { throw new DeveloperError('c is a required number.'); } if (typeof d !== 'number') { throw new DeveloperError('d is a required number.'); } if (typeof e !== 'number') { throw new DeveloperError('e is a required number.'); } //>>includeEnd('debug'); var a2 = a * a; var a3 = a2 * a; var b2 = b * b; var b3 = b2 * b; var c2 = c * c; var c3 = c2 * c; var d2 = d * d; var d3 = d2 * d; var e2 = e * e; var e3 = e2 * e; var discriminant = (b2 * c2 * d2 - 4.0 * b3 * d3 - 4.0 * a * c3 * d2 + 18 * a * b * c * d3 - 27.0 * a2 * d2 * d2 + 256.0 * a3 * e3) + e * (18.0 * b3 * c * d - 4.0 * b2 * c3 + 16.0 * a * c2 * c2 - 80.0 * a * b * c2 * d - 6.0 * a * b2 * d2 + 144.0 * a2 * c * d2) + e2 * (144.0 * a * b2 * c - 27.0 * b2 * b2 - 128.0 * a2 * c2 - 192.0 * a2 * b * d); return discriminant; }; function original(a3, a2, a1, a0) { var a3Squared = a3 * a3; var p = a2 - 3.0 * a3Squared / 8.0; var q = a1 - a2 * a3 / 2.0 + a3Squared * a3 / 8.0; var r = a0 - a1 * a3 / 4.0 + a2 * a3Squared / 16.0 - 3.0 * a3Squared * a3Squared / 256.0; // Find the roots of the cubic equations: h^6 + 2 p h^4 + (p^2 - 4 r) h^2 - q^2 = 0. var cubicRoots = CubicRealPolynomial.realRoots(1.0, 2.0 * p, p * p - 4.0 * r, -q * q); if (cubicRoots.length > 0) { var temp = -a3 / 4.0; // Use the largest positive root. var hSquared = cubicRoots[cubicRoots.length - 1]; if (Math.abs(hSquared) < CesiumMath.EPSILON14) { // y^4 + p y^2 + r = 0. var roots = QuadraticRealPolynomial.realRoots(1.0, p, r); if (roots.length === 2) { var root0 = roots[0]; var root1 = roots[1]; var y; if (root0 >= 0.0 && root1 >= 0.0) { var y0 = Math.sqrt(root0); var y1 = Math.sqrt(root1); return [temp - y1, temp - y0, temp + y0, temp + y1]; } else if (root0 >= 0.0 && root1 < 0.0) { y = Math.sqrt(root0); return [temp - y, temp + y]; } else if (root0 < 0.0 && root1 >= 0.0) { y = Math.sqrt(root1); return [temp - y, temp + y]; } } return []; } else if (hSquared > 0.0) { var h = Math.sqrt(hSquared); var m = (p + hSquared - q / h) / 2.0; var n = (p + hSquared + q / h) / 2.0; // Now solve the two quadratic factors: (y^2 + h y + m)(y^2 - h y + n); var roots1 = QuadraticRealPolynomial.realRoots(1.0, h, m); var roots2 = QuadraticRealPolynomial.realRoots(1.0, -h, n); if (roots1.length !== 0) { roots1[0] += temp; roots1[1] += temp; if (roots2.length !== 0) { roots2[0] += temp; roots2[1] += temp; if (roots1[1] <= roots2[0]) { return [roots1[0], roots1[1], roots2[0], roots2[1]]; } else if (roots2[1] <= roots1[0]) { return [roots2[0], roots2[1], roots1[0], roots1[1]]; } else if (roots1[0] >= roots2[0] && roots1[1] <= roots2[1]) { return [roots2[0], roots1[0], roots1[1], roots2[1]]; } else if (roots2[0] >= roots1[0] && roots2[1] <= roots1[1]) { return [roots1[0], roots2[0], roots2[1], roots1[1]]; } else if (roots1[0] > roots2[0] && roots1[0] < roots2[1]) { return [roots2[0], roots1[0], roots2[1], roots1[1]]; } return [roots1[0], roots2[0], roots1[1], roots2[1]]; } return roots1; } if (roots2.length !== 0) { roots2[0] += temp; roots2[1] += temp; return roots2; } return []; } } return []; } function neumark(a3, a2, a1, a0) { var a1Squared = a1 * a1; var a2Squared = a2 * a2; var a3Squared = a3 * a3; var p = -2.0 * a2; var q = a1 * a3 + a2Squared - 4.0 * a0; var r = a3Squared * a0 - a1 * a2 * a3 + a1Squared; var cubicRoots = CubicRealPolynomial.realRoots(1.0, p, q, r); if (cubicRoots.length > 0) { // Use the most positive root var y = cubicRoots[0]; var temp = (a2 - y); var tempSquared = temp * temp; var g1 = a3 / 2.0; var h1 = temp / 2.0; var m = tempSquared - 4.0 * a0; var mError = tempSquared + 4.0 * Math.abs(a0); var n = a3Squared - 4.0 * y; var nError = a3Squared + 4.0 * Math.abs(y); var g2; var h2; if (y < 0.0 || (m * nError < n * mError)) { var squareRootOfN = Math.sqrt(n); g2 = squareRootOfN / 2.0; h2 = squareRootOfN === 0.0 ? 0.0 : (a3 * h1 - a1) / squareRootOfN; } else { var squareRootOfM = Math.sqrt(m); g2 = squareRootOfM === 0.0 ? 0.0 : (a3 * h1 - a1) / squareRootOfM; h2 = squareRootOfM / 2.0; } var G; var g; if (g1 === 0.0 && g2 === 0.0) { G = 0.0; g = 0.0; } else if (CesiumMath.sign(g1) === CesiumMath.sign(g2)) { G = g1 + g2; g = y / G; } else { g = g1 - g2; G = y / g; } var H; var h; if (h1 === 0.0 && h2 === 0.0) { H = 0.0; h = 0.0; } else if (CesiumMath.sign(h1) === CesiumMath.sign(h2)) { H = h1 + h2; h = a0 / H; } else { h = h1 - h2; H = a0 / h; } // Now solve the two quadratic factors: (y^2 + G y + H)(y^2 + g y + h); var roots1 = QuadraticRealPolynomial.realRoots(1.0, G, H); var roots2 = QuadraticRealPolynomial.realRoots(1.0, g, h); if (roots1.length !== 0) { if (roots2.length !== 0) { if (roots1[1] <= roots2[0]) { return [roots1[0], roots1[1], roots2[0], roots2[1]]; } else if (roots2[1] <= roots1[0]) { return [roots2[0], roots2[1], roots1[0], roots1[1]]; } else if (roots1[0] >= roots2[0] && roots1[1] <= roots2[1]) { return [roots2[0], roots1[0], roots1[1], roots2[1]]; } else if (roots2[0] >= roots1[0] && roots2[1] <= roots1[1]) { return [roots1[0], roots2[0], roots2[1], roots1[1]]; } else if (roots1[0] > roots2[0] && roots1[0] < roots2[1]) { return [roots2[0], roots1[0], roots2[1], roots1[1]]; } else { return [roots1[0], roots2[0], roots1[1], roots2[1]]; } } return roots1; } if (roots2.length !== 0) { return roots2; } } return []; } /** * Provides the real valued roots of the quartic polynomial with the provided coefficients. * * @param {Number} a The coefficient of the 4th order monomial. * @param {Number} b The coefficient of the 3rd order monomial. * @param {Number} c The coefficient of the 2nd order monomial. * @param {Number} d The coefficient of the 1st order monomial. * @param {Number} e The coefficient of the 0th order monomial. * @returns {Number[]} The real valued roots. */ QuarticRealPolynomial.realRoots = function(a, b, c, d, e) { //>>includeStart('debug', pragmas.debug); if (typeof a !== 'number') { throw new DeveloperError('a is a required number.'); } if (typeof b !== 'number') { throw new DeveloperError('b is a required number.'); } if (typeof c !== 'number') { throw new DeveloperError('c is a required number.'); } if (typeof d !== 'number') { throw new DeveloperError('d is a required number.'); } if (typeof e !== 'number') { throw new DeveloperError('e is a required number.'); } //>>includeEnd('debug'); if (Math.abs(a) < CesiumMath.EPSILON15) { return CubicRealPolynomial.realRoots(b, c, d, e); } var a3 = b / a; var a2 = c / a; var a1 = d / a; var a0 = e / a; var k = (a3 < 0.0) ? 1 : 0; k += (a2 < 0.0) ? k + 1 : k; k += (a1 < 0.0) ? k + 1 : k; k += (a0 < 0.0) ? k + 1 : k; switch (k) { case 0: return original(a3, a2, a1, a0); case 1: return neumark(a3, a2, a1, a0); case 2: return neumark(a3, a2, a1, a0); case 3: return original(a3, a2, a1, a0); case 4: return original(a3, a2, a1, a0); case 5: return neumark(a3, a2, a1, a0); case 6: return original(a3, a2, a1, a0); case 7: return original(a3, a2, a1, a0); case 8: return neumark(a3, a2, a1, a0); case 9: return original(a3, a2, a1, a0); case 10: return original(a3, a2, a1, a0); case 11: return neumark(a3, a2, a1, a0); case 12: return original(a3, a2, a1, a0); case 13: return original(a3, a2, a1, a0); case 14: return original(a3, a2, a1, a0); case 15: return original(a3, a2, a1, a0); default: return undefined; } }; return QuarticRealPolynomial; });
const FOO = 1; const BAR = 2; const BAZ = 3; module.exports = { name: 'Enums', constants: { FOO, BAR, BAZ, }, attributes: { consts: { type: 'enum', valueType: 'number', values: ['FOO', 'BAR', BAZ, 4], constant: true, }, }, };
/** * Install plugin. */ import Util from './util'; import Fields, { Mixin } from './fields'; import { Validate } from './validate'; import { Validator, Filter, Directive } from './validator'; function plugin(Vue) { if (plugin.installed) { return; } Util(Vue); Vue.field = Fields; Vue.mixin(Mixin); Vue.validator = Validator; Vue.filter('valid', Filter); Vue.directive('validator', Directive); Vue.directive('validate', Validate); } if (typeof window !== 'undefined' && window.Vue) { window.Vue.use(plugin); } export default plugin;
// QUnit move the fixture out of the viewport area by setting its position: absolute; top: -10000px; left: -10000px; // This helper make it possible to show the fixture quickly for debugging purposes. function showFixture() { $('#qunit-fixture').css({ position: 'static' }); } function checkBbox(paper, el, x, y, w, h, msg) { var view = paper.findViewByModel(el); var bbox = view.getBBox(); // Extract coordinates and dimension only in case bbox is e.g. an SVGRect or some other object with // other properties. We need that to be able to use deepEqual() assertion and therefore generate just one assertion // instead of four for every position and dimension. var bboxObject = { x: bbox.x, y: bbox.y, width: bbox.width, height: bbox.height }; deepEqual(bboxObject, { x: x, y: y, width: w, height: h }, msg); } // Simulate user events. // --------------------- var simulate = { mouseevent: function(opt) { var evt = document.createEvent('MouseEvents'); evt.initMouseEvent( opt.type, /*canBubble*/ true, /*cancelable*/ true, /*view*/ window, /*click count*/1, opt.screenX || 0, opt.screenY || 0, opt.clientX || 0, opt.clientY || 0, /*ctrlKey*/ false, /*altKey*/ false, /*shiftKey*/ false, /*metaKey*/ false, opt.button || 0, /*relatedTarget*/ null ); if (opt.el) { opt.el.dispatchEvent(evt); } return evt; }, mousedown: function(opt) { opt.type = 'mousedown'; return this.mouseevent(opt); }, mousemove: function(opt) { opt.type = 'mousemove'; return this.mouseevent(opt); }, mouseup: function(opt) { opt.type = 'mouseup'; return this.mouseevent(opt); }, mouseover: function(opt) { opt.type = 'mouseover'; return this.mouseevent(opt); }, mouseout: function(opt) { opt.type = 'mouseout'; return this.mouseevent(opt); } };
import cx from 'classnames' import _ from 'lodash' import PropTypes from 'prop-types' import React from 'react' import { createShorthandFactory, customPropTypes, getElementType, getUnhandledProps, META, } from '../../lib' /** * An item can contain a description with a single or multiple paragraphs. */ function ItemDescription(props) { const { children, className, content } = props const classes = cx('description', className) const rest = getUnhandledProps(ItemDescription, props) const ElementType = getElementType(ItemDescription, props) return ( <ElementType {...rest} className={classes}> {_.isNil(children) ? content : children} </ElementType> ) } ItemDescription._meta = { name: 'ItemDescription', parent: 'Item', type: META.TYPES.VIEW, } ItemDescription.propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, /** Shorthand for primary content. */ content: customPropTypes.contentShorthand, } ItemDescription.create = createShorthandFactory(ItemDescription, content => ({ content })) export default ItemDescription
const config = require('configModule'); const noJquery = require('withoutJqueryModule'); const content = require('./templates/main.ejs'); const layout = require('layout-without-nav'); const dirsConfig = config.DIRS; const loginBoxHtml = require('./templates/login-box.ejs')({ constructInsideUrl: noJquery.constructInsideUrl, }); const forgetPasswordHtml = require('./templates/forget-password-box.html'); const renderData = Object.assign(dirsConfig, { loginBoxHtml, forgetPasswordHtml }); module.exports = layout.init({ pageTitle: '', }).run(content(renderData));
/** * $Id: JSON.js 920 2008-09-09 14:05:33Z spocke $ * * @author Moxiecode * @copyright Copyright © 2004-2006, Moxiecode Systems AB, All rights reserved. */ tinymce.create('static tinymce.util.JSONP', { callbacks : {}, count : 0, send : function(o) { var t = this, dom = tinymce.DOM, count = o.count !== undefined ? o.count : t.count, id = 'tinymce_jsonp_' + count; t.callbacks[count] = function(json) { dom.remove(id); delete t.callbacks[count]; o.callback(json); }; dom.add(dom.doc.body, 'script', {id : id , src : o.url, type : 'text/javascript'}); t.count++; } });
/** * * Returns a list of the currently active sessions. Each session will be returned * as a list of JSON objects with the following keys: * * | Key | Type | Description | * |--------------|--------|----------------| * | id | string | The session ID | * | capabilities | object | An object describing the [session capabilities](https://code.google.com/p/selenium/wiki/JsonWireProtocol#Actual_Capabilities) | * * @returns {Object[]} a list of the currently active sessions * @callbackParameter error, response * * @see https://code.google.com/p/selenium/wiki/JsonWireProtocol#/sessions * @type protocol * */ module.exports = function sessions () { var requestOptions = { path: '/sessions', method: 'GET', requiresSession: false }; this.requestHandler.create( requestOptions, {}, arguments[arguments.length - 1]); };
angular.module('portal') .factory('tokenCleaner', ['$injector', '$cookies', '$rootScope', '$q', function ($injector, $cookies, $rootScope, $q) { var interceptor = { responseError: function(response) { if (response.status === 401 && response.data) { if (response.data.detail === 'Invalid token.') { $cookies.remove('token'); $cookies.remove('user'); var http = $injector.get('$http'); delete http.defaults.headers.common.Authorization; $rootScope.$broadcast("djangoAuth.logged_out"); } } return $q.reject(response); } }; return interceptor; }]);
var common = require("./common") , odbc = require("../odbc.js") , db = new odbc.Database(); db.open(common.connectionString, function(err) { db.query("drop table test", function (err, data) { if (err) { console.error(err); process.exit(1); } console.error(data); }); });
describe('Iuchi Wayfinder', function() { integration(function() { describe('Iuchi Wayfinder ability', function() { beforeEach(function() { this.setupTest({ phase: 'conflict', player1: { hand: ['iuchi-wayfinder'] } }); this.shamefulDisplay1 = this.player2.findCardByName('shameful-display', 'province 1'); this.shamefulDisplay2 = this.player2.findCardByName('shameful-display', 'province 2'); this.shamefulDisplay2.facedown = false; }); it('should allow targeting only facedown provinces', function() { this.iuchiWayfinder = this.player1.playCharacterFromHand('iuchi-wayfinder'); expect(this.player1).toHavePrompt('Triggered Abilities'); this.player1.clickCard(this.iuchiWayfinder); expect(this.player1).toHavePrompt('Iuchi Wayfinder'); expect(this.player1).toBeAbleToSelect(this.shamefulDisplay1); expect(this.player1).not.toBeAbleToSelect(this.shamefulDisplay2); }); it('should display a message in chat when a province is chosen', function() { this.iuchiWayfinder = this.player1.playCharacterFromHand('iuchi-wayfinder'); this.player1.clickCard(this.iuchiWayfinder); this.player1.clickCard(this.shamefulDisplay1); expect(this.getChatLogs(1)).toContain('Iuchi Wayfinder sees Shameful Display in province 1'); }); }); }); });
export default (() => { let o; return Jymfony.Component.VarExporter.Internal.Hydrator.hydrate( o = [ (new ReflectionClass('Jymfony.Component.DateTime.Internal.RuleSet')).newInstanceWithoutConstructor(), (new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(), (new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(), (new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(), (new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(), (new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(), (new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(), (new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(), (new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(), (new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(), (new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(), (new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(), (new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(), (new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(), (new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(), (new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(), (new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(), ], null, { 'Jymfony.Component.DateTime.Internal.RuleSet': { ['_name']: { ['0']: undefined, }, ['_rules']: { ['0']: [ o[1], o[2], o[3], o[4], o[5], o[6], o[7], o[8], o[9], o[10], o[11], o[12], o[13], o[14], o[15], o[16], ], }, ['_cache']: { ['0']: { ['1945']: [ o[6], ], ['1946']: [ o[6], o[7], ], }, }, }, 'Jymfony.Component.DateTime.Internal.Rule': { ['_fromYear']: { ['1']: 1927, ['2']: 1928, ['3']: 1928, ['4']: 1929, ['5']: 1934, ['6']: 1934, ['7']: 1946, ['8']: 1974, ['9']: 1975, ['10']: 1975, ['11']: 1976, ['12']: 1989, ['13']: 1990, ['14']: 1990, ['15']: 2007, ['16']: 2008, }, ['_toYear']: { ['1']: 1927, ['2']: 1928, ['3']: 1933, ['4']: 1933, ['5']: 1940, ['6']: 1940, ['7']: 1946, ['8']: 1974, ['9']: 1975, ['10']: 1988, ['11']: 1989, ['12']: 1989, ['13']: 2006, ['14']: 2007, ['15']: Infinity, ['16']: Infinity, }, ['_inMonth']: { ['1']: 11, ['2']: 3, ['3']: 10, ['4']: 3, ['5']: 4, ['6']: 9, ['7']: 1, ['8']: 11, ['9']: 2, ['10']: 10, ['11']: 3, ['12']: 10, ['13']: 10, ['14']: 3, ['15']: 9, ['16']: 4, }, ['_on']: { ['1']: '6', ['2']: '4', ['3']: '8 %s this sun', ['4']: '15 %s this sun', ['5']: 'last sun %s', ['6']: 'last sun %s', ['7']: '1', ['8']: '1 %s this sun', ['9']: 'last sun %s', ['10']: 'last sun %s', ['11']: '1 %s this sun', ['12']: '8 %s this sun', ['13']: '1 %s this sun', ['14']: '15 %s this sun', ['15']: 'last sun %s', ['16']: '1 %s this sun', }, ['_at']: { ['1']: '2:00', ['2']: '2:00', ['3']: '2:00', ['4']: '2:00', ['5']: '2:00', ['6']: '2:00', ['7']: '0:00', ['8']: '2:00s', ['9']: '2:00s', ['10']: '2:00s', ['11']: '2:00s', ['12']: '2:00s', ['13']: '2:00s', ['14']: '2:00s', ['15']: '2:00s', ['16']: '2:00s', }, ['_save']: { ['1']: 3600, ['2']: 0, ['3']: 1800, ['4']: 0, ['5']: 0, ['6']: 1800, ['7']: 0, ['8']: 3600, ['9']: 0, ['10']: 3600, ['11']: 0, ['12']: 3600, ['13']: 3600, ['14']: 0, ['15']: 3600, ['16']: 0, }, ['_letters']: { ['1']: 'S', ['2']: 'M', ['3']: 'S', ['4']: 'M', ['5']: 'M', ['6']: 'S', ['7']: 'S', ['8']: 'D', ['9']: 'S', ['10']: 'D', ['11']: 'S', ['12']: 'D', ['13']: 'D', ['14']: 'S', ['15']: 'D', ['16']: 'S', }, ['_cache']: { ['1']: {}, ['2']: {}, ['3']: {}, ['4']: {}, ['5']: {}, ['6']: { ['1940']: [ '001940-09-29T02:00:00', '001940-09-29T02:30:00', ], }, ['7']: { ['1946']: [ '001946-01-01T00:00:00', '001946-01-01T00:00:00', ], }, ['8']: {}, ['9']: {}, ['10']: {}, ['11']: {}, ['12']: {}, ['13']: {}, ['14']: {}, ['15']: {}, ['16']: {}, }, }, }, [ { ['offset']: 41944, ['dst']: false, ['abbrev']: 'LMT', ['until']: -3192435544, ['format']: 'LMT', }, { ['until']: -757425600, ['ruleSet']: o[0], ['offset']: 41400, ['abbrev']: 'NZ%sT', }, { ['until']: Infinity, ['ruleSet']: o[0], ['offset']: 43200, ['abbrev']: 'NZ%sT', }, ], [ 0, ] ); })(); ;
import {SubsetCollection} from './SubsetCollection'; import {editor} from '../base'; import {orderedCollection} from './mixins/orderedCollection'; export const ChapterPagesCollection = SubsetCollection.extend({ mixins: [orderedCollection], constructor: function(options) { var chapter = options.chapter; SubsetCollection.prototype.constructor.call(this, { parent: options.pages, parentModel: chapter, filter: function(item) { return !chapter.isNew() && item.get('chapter_id') === chapter.id; }, comparator: function(item) { return item.get('position'); } }); this.each(function(page) { page.chapter = chapter; }); this.listenTo(this, 'add', function(model) { model.chapter = chapter; model.set('chapter_id', chapter.id); editor.trigger('add:page', model); }); this.listenTo(this, 'remove', function(model) { model.chapter = null; }); this.listenTo(chapter, 'destroy', function() { this.clear(); }); } });
/* global TrelloPowerUp */ var MAPROSOFT_ICON_WITH_TEXT_COLOR = './images/Maprosoft-logo-with-text-color.svg'; var MAPROSOFT_ICON_GRAY = './images/Maprosoft-logo-no-text-gray.svg'; var MAPROSOFT_ICON_COLOR = './images/Maprosoft-logo-no-text-color.svg'; var CACHED_SHARED_MAP_INFO_KEY = 'cached-shared-map-info'; var TEAM_NAME_KEY = 'maprosoft-team-name'; var TEAM_TOKEN_KEY = 'maprosoft-team-token'; var ORGANIZATION_SCOPE = 'organization'; var BOARD_SCOPE = 'board'; var SETTINGS_SCOPE = BOARD_SCOPE; var SETTINGS_VISIBILITY = 'shared'; var AUTO_HIDE_MAP_TOOLBAR = true; var MAPROSOFT_WEBSITE_URL = 'https://www.maprosoft.com'; var MAPROSOFT_APP_URL = MAPROSOFT_WEBSITE_URL + '/app'; var MAPROSOFT_SHARED_MAP_URL_BASE = MAPROSOFT_APP_URL + '/shared'; var MAPROSOFT_SHARED_MAPS_PAGE_URL_BASE = MAPROSOFT_APP_URL + '/shared-maps.html'; var MAPROSOFT_MAP_URL_BASE = MAPROSOFT_APP_URL + '/map'; var teamNameToKey = function(teamNameOrKey) { var key = teamNameOrKey; key = key.toLowerCase(); key = key.replace(' ', '-'); key = key.replace('\'', ''); key = key.replace('"', ''); key = key.replace('~', ''); key = key.replace('`', ''); key = key.replace('!', ''); key = key.replace('@', ''); key = key.replace('#', ''); key = key.replace('$', ''); key = key.replace('%', ''); key = key.replace('^', ''); key = key.replace('&', ''); key = key.replace('*', ''); key = key.replace('(', ''); key = key.replace(')', ''); key = key.replace('{', ''); key = key.replace('}', ''); key = key.replace('[', ''); key = key.replace(']', ''); key = key.replace(':', ''); key = key.replace(';', ''); key = key.replace('.', ''); key = key.replace('<', ''); key = key.replace('>', ''); key = key.replace('?', ''); key = key.replace('/', ''); key = key.replace('\\', ''); key = key.replace('|', ''); key = key.replace('+', ''); key = key.replace('=', ''); key = key.replace('_', ''); return key; }; var extractSharedMapNameFromUrl = function(url) { var sharedMapName = 'Maprosoft shared map'; if (url) { var decodedUrl = decodeURI(url); var urlParts = decodedUrl.split('/'); if (urlParts && urlParts.length) { sharedMapName = urlParts[urlParts.length - 1]; } } return sharedMapName; }; var buildSharedMapUrl = function(teamNameOrKey, sharedMapName) { var encodedSharedMapName = encodeURIComponent(sharedMapName); var encodedTeamNameOrKey = encodeURIComponent(teamNameOrKey); var sharedMapUrl = MAPROSOFT_SHARED_MAP_URL_BASE + '/' + encodedTeamNameOrKey + '/' + encodedSharedMapName; return sharedMapUrl; }; var buildGeneralMapUrl = function(teamNameOrKey) { var teamKey = teamNameToKey(teamNameOrKey); var mapUrl = MAPROSOFT_MAP_URL_BASE + '?team=' + teamKey + '&autoHideMapToolbar=yes'; mapUrl = appendAutoHideToolbarParameter(mapUrl); return mapUrl; }; var buildValidateTokenAndTeamUrl = function(token, team) { return MAPROSOFT_APP_URL + '/validate-token?team=' + team + '&token=' + token; }; var buildGeocodeAddressUrl = function(token, address) { var encodedAddress = encodeURIComponent(address); return MAPROSOFT_APP_URL + '/geocode?token=' + token + '&address=' + encodedAddress; }; var buildTeamSharedMapsUrl = function(teamNameOrKey) { var teamKey = teamNameToKey(teamNameOrKey); return MAPROSOFT_SHARED_MAPS_PAGE_URL_BASE + '?team=' + teamKey; }; var buildRetrieveSharedMapsUrl = function(teamNameOrKey, token) { var teamKey = teamNameToKey(teamNameOrKey); return MAPROSOFT_SHARED_MAP_URL_BASE + '?team=' + teamKey + '&getSharedMapNames=yes'; }; var buildUrlWithDropPin = function(teamNameOrKey, address, latitude, longitude) { var teamKey = teamNameToKey(teamNameOrKey); var mapUrl = MAPROSOFT_MAP_URL_BASE + '?team=' + teamKey; mapUrl = appendAddressParameters(mapUrl, address, latitude, longitude); mapUrl = appendAutoHideToolbarParameter(mapUrl); return mapUrl; }; var appendAddressParameters = function(mapUrl, address, latitude, longitude) { var nextSeparator = determineNextQuerySeparator(mapUrl); var encodedAddress = encodeURIComponent(address); return mapUrl + nextSeparator + 'dropPinTitle=' + encodedAddress + '&dropPinLatitude=' + latitude + '&dropPinLongitude=' + longitude + '&customLatitude=' + latitude + '&customLongitude=' + longitude + '&customZoom=16'; }; var appendAutoHideToolbarParameter = function(mapUrl) { var extraParam = 'autoHideMapToolbar=yes'; if (AUTO_HIDE_MAP_TOOLBAR && mapUrl.indexOf(extraParam) < 0) { var separator = determineNextQuerySeparator(mapUrl); return mapUrl + separator + extraParam; } else { return mapUrl; } }; var determineNextQuerySeparator = function(url) { var questionIndex = url.indexOf('?'); if (questionIndex < 0) { return '?'; } else { return '&'; } }; var doGet = function(url) { var getPromise = new Promise(function(resolve, reject) { var request = new XMLHttpRequest(); request.open('GET', url, true); request.onload = function() { try { if (request.status === 200) { var responseJson = JSON.parse(request.responseText); return resolve(responseJson); } else if (request.status === 404) { return reject(new Error("resource not found.")); } else { return reject(new Error("Unable to load locale, status: " + request.status)); } } catch(ex) { return reject(new Error(ex.message)); } }; request.send(); }); return getPromise; }; var geocodeAddress = function(token, address) { var retrieveSharedMapsUrl = buildGeocodeAddressUrl(token, address); return doGet(retrieveSharedMapsUrl); }; var getFreshMapInfo = function(teamName) { var token = null; var retrieveSharedMapsUrl = buildRetrieveSharedMapsUrl(teamName, token); return doGet(retrieveSharedMapsUrl); }; var isMapLinkAttachment = function(attachment) { return attachment.url.indexOf(MAPROSOFT_MAP_URL_BASE) === 0 || attachment.url.indexOf(MAPROSOFT_SHARED_MAP_URL_BASE) === 0; }; var showNoSettingsPopup = function(t) { return t.popup({ title: 'No settings', url: './no-settings.html', height: 130 }); }; var closeSettingsPopup = function(t) { //console.log('Closing settings...'); return t.closePopup(); }; var openSettingsPopup = function(t) { //console.log('Opening settings...'); return t.popup({ title: 'Settings', url: './settings.html', height: 184 }); }; var getData = function(t, key) { return t.set(ORGANIZATION_SCOPE, SETTINGS_VISIBILITY, 'dummy-key', 'dummy-data') .then(function(dummyData) { return t.get(ORGANIZATION_SCOPE, SETTINGS_VISIBILITY, key); }) .catch(function() { return t.get(BOARD_SCOPE, SETTINGS_VISIBILITY, key) }); }; var setData = function(t, key, data) { return t.set(ORGANIZATION_SCOPE, SETTINGS_VISIBILITY, key, data) .catch(function() { return t.set(BOARD_SCOPE, SETTINGS_VISIBILITY, key, data) }); }; // This example is from https://developer.mozilla.org/en-US/docs/Web/Events/resize: var optimizedResize = (function() { var callbacks = [], running = false; // fired on resize event function resize() { if (!running) { running = true; if (window.requestAnimationFrame) { window.requestAnimationFrame(runCallbacks); } else { setTimeout(runCallbacks, 66); } } } // run the actual callbacks function runCallbacks() { callbacks.forEach(function(callback) { callback(); }); running = false; } // adds callback to loop function addCallback(callback) { if (callback) { callbacks.push(callback); } } return { // public method to add additional callback addWindowResizeListener: function(callback) { if (!callbacks.length) { window.addEventListener('resize', resize); } addCallback(callback); } } }());
// @flow import { describe, it } from "flow-typed-test"; import { spawn } from "redux-saga/effects"; describe("spawn effect", () => { describe("structure", () => { const c = spawn(() => {}); it('type must be equal "FORK"', () => { (c.type: "FORK"); }); it("returned object must be read only", () => { // $FlowExpectedError: read-only property c.type = "anyType"; // $FlowExpectedError: read-only property c.payload = {}; }); it("returned object must be exact", () => { // $FlowExpectedError: exact type c.abc = 69; }); }); describe("spawn(fn, ...args)", () => { function nfn0(): number { return 1; } function nfn1(a: string): number { return 1; } function nfn2(a: string, b: number): number { return 1; } function nfn3(a: string, b: number, c: boolean): number { return 1; } function nfn4(a: string, b: number, c: boolean, d: string): number { return 1; } function nfn5(a: string, b: number, c: boolean, d: string, e: number): number { return 1; } function nfn6(a: string, b: number, c: boolean, d: string, e: number, f: boolean): number { return 1; } function nfn7( a: string, b: number, c: boolean, d: string, e: number, f: boolean, g: string ): number { return 1; } function nfn8( a: string, b: number, c: boolean, d: string, e: number, f: boolean, g: string, h: number ): number { return 1; } const c0 = spawn(nfn0); const c1 = spawn(nfn1, "1"); const c2 = spawn(nfn2, "1", 2); const c3 = spawn(nfn3, "1", 2, true); const c4 = spawn(nfn4, "1", 2, true, "4"); const c5 = spawn(nfn5, "1", 2, true, "4", 5); const c6 = spawn(nfn6, "1", 2, true, "4", 5, false); const c7 = spawn(nfn7, "1", 2, true, "4", 5, false, "7"); const c8 = spawn(nfn8, "1", 2, true, "4", 5, false, "7", 8); describe("arguments tests", () => { it("must passes when used properly", () => { (c0.payload.args: []); (c1.payload.args: [string]); (c2.payload.args: [string, number]); (c3.payload.args: [string, number, boolean]); (c4.payload.args: [string, number, boolean, string]); (c5.payload.args: [string, number, boolean, string, number]); (c6.payload.args: [string, number, boolean, string, number, boolean]); (c7.payload.args: [string, number, boolean, string, number, boolean, string]); (c8.payload.args: [string, number, boolean, string, number, boolean, string, number]); }); it("must raises an error when passed number but need string", () => { // $FlowExpectedError: First parameter is a string, not a number (c1.payload.args: [number]); }); it("must raises an error when passed too few arguments", () => { // $FlowExpectedError: Too few arguments spawn(nfn6, "1", 2, true, "4"); }); it("must raises an error when passed wrong argument types", () => { // $FlowExpectedError: Wrong argument types spawn(nfn1, 1); }); }); describe("function test", () => { it("must passes when used properly", () => { (c1.payload.fn: typeof nfn1); (c2.payload.fn: typeof nfn2); (c3.payload.fn: typeof nfn3); (c4.payload.fn: typeof nfn4); (c5.payload.fn: typeof nfn5); (c6.payload.fn: typeof nfn6); (c7.payload.fn: typeof nfn7); (c8.payload.fn: typeof nfn8); }); it("should actually fail, but apparently more parameter are fine", () => { (c1.payload.fn: typeof nfn6); }); it("must raises an error when Function return not string", () => { // $FlowExpectedError: fn returns a number not string (c1.payload.fn: (a: boolean) => string); }); it(`must raises an error when "a" argument isn't string`, () => { // $FlowExpectedError: 'a' is actually of type string (c1.payload.fn: (a: boolean) => number); // $FlowExpectedError: 'a' is actually of type string (c4.payload.fn: (a: number, b: number) => number); }); it("must raises an error when less parameter are noticed", () => { // $FlowExpectedError: Less parameter are noticed (c6.payload.fn: typeof nfn1); }); }); describe("context tests", () => { it("must haven't context", () => { (c1.payload.context: null); (c2.payload.context: null); (c3.payload.context: null); (c4.payload.context: null); (c5.payload.context: null); (c6.payload.context: null); (c7.payload.context: null); (c8.payload.context: null); }); it("must raises an error when lead context to Object", () => { // $FlowExpectedError (c1.payload.context: {...}); }); }); }); describe("spawn([context, fn], ...args)", () => { const context = { some: "contextObject" }; function nfn0(): number { return 1; } function nfn1(a: string): number { return 1; } function nfn2(a: string, b: number): number { return 1; } function nfn3(a: string, b: number, c: boolean): number { return 1; } function nfn4(a: string, b: number, c: boolean, d: string): number { return 1; } function nfn5(a: string, b: number, c: boolean, d: string, e: number): number { return 1; } function nfn6(a: string, b: number, c: boolean, d: string, e: number, f: boolean): number { return 1; } function nfn7( a: string, b: number, c: boolean, d: string, e: number, f: boolean, g: string ): number { return 1; } function nfn8( a: string, b: number, c: boolean, d: string, e: number, f: boolean, g: string, h: number ): number { return 1; } const f0 = spawn([context, nfn0]); const f1 = spawn([context, nfn1], "1"); const f2 = spawn([context, nfn2], "1", 2); const f3 = spawn([context, nfn3], "1", 2, true); const f4 = spawn([context, nfn4], "1", 2, true, "4"); const f5 = spawn([context, nfn5], "1", 2, true, "4", 5); const f6 = spawn([context, nfn6], "1", 2, true, "4", 5, false); const f7 = spawn([context, nfn7], "1", 2, true, "4", 5, false, "7"); const f8 = spawn([context, nfn8], "1", 2, true, "4", 5, false, "7", 8); describe("arguments tests", () => { it("must passes when used properly", () => { (f0.payload.args: []); (f1.payload.args: [string]); (f2.payload.args: [string, number]); (f3.payload.args: [string, number, boolean]); (f4.payload.args: [string, number, boolean, string]); (f5.payload.args: [string, number, boolean, string, number]); (f6.payload.args: [string, number, boolean, string, number, boolean]); (f7.payload.args: [string, number, boolean, string, number, boolean, string]); (f8.payload.args: [string, number, boolean, string, number, boolean, string, number]); }); it("must raises an error when passed number but need string", () => { // $FlowExpectedError: First parameter is a string, not a number (f1.payload.args: [number]); }); it("must raises an error when passed too few arguments", () => { // $FlowExpectedError: Too few arguments spawn([context, nfn6], "1", 2, true, "4"); }); it("must raises an error when passed wrong argument types", () => { // $FlowExpectedError: Wrong argument types spawn([context, nfn1], 1); }); }); describe("function test", () => { it("must passes when used properly", () => { (f1.payload.fn: typeof nfn1); (f2.payload.fn: typeof nfn2); (f3.payload.fn: typeof nfn3); (f4.payload.fn: typeof nfn4); (f5.payload.fn: typeof nfn5); (f6.payload.fn: typeof nfn6); (f7.payload.fn: typeof nfn7); (f8.payload.fn: typeof nfn8); }); it("should actually fail, but apparently more parameter are fine", () => { (f1.payload.fn: typeof nfn6); }); it("must raises an error when Function return not string", () => { // $FlowExpectedError: fn returns a number not string (f1.payload.fn: (a: boolean) => string); }); it(`must raises an error when "a" argument isn't string`, () => { // $FlowExpectedError: 'a' is actually of type string (f1.payload.fn: (a: boolean) => number); // $FlowExpectedError: 'a' is actually of type string (f4.payload.fn: (a: number, b: number) => number); }); it("must raises an error when less parameter are noticed", () => { // $FlowExpectedError: Less parameter are noticed (f6.payload.fn: typeof nfn1); }); }); describe("context tests", () => { it("must have context", () => { (f1.payload.context: typeof context); (f2.payload.context: typeof context); (f3.payload.context: typeof context); (f4.payload.context: typeof context); (f5.payload.context: typeof context); (f6.payload.context: typeof context); (f7.payload.context: typeof context); (f8.payload.context: typeof context); }); it("must raises an error when lead context to null", () => { // $FlowExpectedError (f1.payload.context: null); }); }); }); });
// This file is generated automatically by `scripts/build/fp.js`. Please, don't change it. import fn from '../../setDay/index.js' import convertToFP from '../_lib/convertToFP/index.js' var setDay = convertToFP(fn, 2) export default setDay
import { moduleForModel, test } from 'ember-qunit'; moduleForModel('driver', { // Specify the other units that are required for this test. needs: [] }); test('it exists', function(assert) { var model = this.subject(); // var store = this.store(); assert.ok(!!model); });
module.exports = function(api) { api.add({ 'ul, ol': { mar: '30px 0 30px 22px', pad: 0, list: 'c', li: { mar: 0, pad: 0 } } }) }
$(function(){ var shrinkHeader = 300; $(window).scroll(function() { var scroll = getCurrentScroll(); if ( scroll >= shrinkHeader ) { $('.header').addClass('shrink'); } else { $('.header').removeClass('shrink'); } }); function getCurrentScroll() { return window.pageYOffset || document.documentElement.scrollTop; } });
/* * This file is part of Arduino * * 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. * * Copyright 2015 Arduino Srl (http://www.arduino.org/) * * authors: arduino.org team - support@arduino.org * */ (function () { "use strict"; var cp = require("copy-paste"); var domainManager; var domainName = "org-arduino-ide-domain-copypaste"; function forumCopy(userSelection) { //console.log("PRE COPY"); cp.copy("[code]\n"+userSelection+"\n[/code]\n"); //console.log("POST COPY"); }; function init(domainManager) { if(!domainManager.hasDomain(domainName)){ domainManager.registerDomain(domainName, {major: 0, minor: 1}); } domainManager.registerCommand( domainName, "forumCopy", forumCopy, false, "Copy current selection for forum" ); } exports.init = init; }());
// ====================== // StereoAudioRecorder.js // source code from: http://typedarray.org/wp-content/projects/WebAudioRecorder/script.js function StereoAudioRecorder(mediaStream, root) { // variables var leftchannel = []; var rightchannel = []; var scriptprocessornode; var recording = false; var recordingLength = 0; var volume; var audioInput; var sampleRate = 44100; var audioContext; var context; this.record = function() { recording = true; // reset the buffers for the new recording leftchannel.length = rightchannel.length = 0; recordingLength = 0; }; this.requestData = function() { if(recordingLength == 0) { requestDataInvoked = false; return; } requestDataInvoked = true; // clone stuff var internal_leftchannel = leftchannel.slice(0); var internal_rightchannel = rightchannel.slice(0); var internal_recordingLength = recordingLength; // reset the buffers for the new recording leftchannel.length = rightchannel.length = []; recordingLength = 0; requestDataInvoked = false; // we flat the left and right channels down var leftBuffer = mergeBuffers(internal_leftchannel, internal_recordingLength); var rightBuffer = mergeBuffers(internal_leftchannel, internal_recordingLength); // we interleave both channels together var interleaved = interleave(leftBuffer, rightBuffer); // we create our wav file var buffer = new ArrayBuffer(44 + interleaved.length * 2); var view = new DataView(buffer); // RIFF chunk descriptor writeUTFBytes(view, 0, 'RIFF'); view.setUint32(4, 44 + interleaved.length * 2, true); writeUTFBytes(view, 8, 'WAVE'); // FMT sub-chunk writeUTFBytes(view, 12, 'fmt '); view.setUint32(16, 16, true); view.setUint16(20, 1, true); // stereo (2 channels) view.setUint16(22, 2, true); view.setUint32(24, sampleRate, true); view.setUint32(28, sampleRate * 4, true); view.setUint16(32, 4, true); view.setUint16(34, 16, true); // data sub-chunk writeUTFBytes(view, 36, 'data'); view.setUint32(40, interleaved.length * 2, true); // write the PCM samples var lng = interleaved.length; var index = 44; var volume = 1; for (var i = 0; i < lng; i++) { view.setInt16(index, interleaved[i] * (0x7FFF * volume), true); index += 2; } // our final binary blob var blob = new Blob([view], { type: 'audio/wav' }); root.ondataavailable(blob); }; this.stop = function() { // we stop recording recording = false; this.requestData(); }; function interleave(leftChannel, rightChannel) { var length = leftChannel.length + rightChannel.length; var result = new Float32Array(length); var inputIndex = 0; for (var index = 0; index < length;) { result[index++] = leftChannel[inputIndex]; result[index++] = rightChannel[inputIndex]; inputIndex++; } return result; } function mergeBuffers(channelBuffer, recordingLength) { var result = new Float32Array(recordingLength); var offset = 0; var lng = channelBuffer.length; for (var i = 0; i < lng; i++) { var buffer = channelBuffer[i]; result.set(buffer, offset); offset += buffer.length; } return result; } function writeUTFBytes(view, offset, string) { var lng = string.length; for (var i = 0; i < lng; i++) { view.setUint8(offset + i, string.charCodeAt(i)); } } // creates the audio context // creates the audio context var audioContext = ObjectStore.AudioContext; if (!ObjectStore.AudioContextConstructor) ObjectStore.AudioContextConstructor = new audioContext(); var context = ObjectStore.AudioContextConstructor; // creates a gain node if (!ObjectStore.VolumeGainNode) ObjectStore.VolumeGainNode = context.createGain(); var volume = ObjectStore.VolumeGainNode; // creates an audio node from the microphone incoming stream if (!ObjectStore.AudioInput) ObjectStore.AudioInput = context.createMediaStreamSource(mediaStream); // creates an audio node from the microphone incoming stream var audioInput = ObjectStore.AudioInput; // connect the stream to the gain node audioInput.connect(volume); /* From the spec: This value controls how frequently the audioprocess event is dispatched and how many sample-frames need to be processed each call. Lower values for buffer size will result in a lower (better) latency. Higher values will be necessary to avoid audio breakup and glitches Legal values are 256, 512, 1024, 2048, 4096, 8192, and 16384.*/ var bufferSize = 2048; if (context.createJavaScriptNode) { scriptprocessornode = context.createJavaScriptNode(bufferSize, 2, 2); } else if (context.createScriptProcessor) { scriptprocessornode = context.createScriptProcessor(bufferSize, 2, 2); } else { throw 'WebAudio API has no support on this browser.'; } var requestDataInvoked = false; // sometimes "scriptprocessornode" disconnects from he destination-node // and there is no exception thrown in this case. // and obviously no further "ondataavailable" events will be emitted. // below global-scope variable is added to debug such unexpected but "rare" cases. window.scriptprocessornode = scriptprocessornode; // http://webaudio.github.io/web-audio-api/#the-scriptprocessornode-interface scriptprocessornode.onaudioprocess = function(e) { if (!recording || requestDataInvoked) return; var left = e.inputBuffer.getChannelData(0); var right = e.inputBuffer.getChannelData(1); // we clone the samples leftchannel.push(new Float32Array(left)); rightchannel.push(new Float32Array(right)); recordingLength += bufferSize; }; volume.connect(scriptprocessornode); scriptprocessornode.connect(context.destination); }
var tistorekit = require('tistorekit') , loadingView = false , modal; var skhelper = { extend: function (obj) { for (var i = 1; i < arguments.length; i++) { for (var prop in arguments[i]) { if (arguments[i].hasOwnProperty(prop)) { obj[prop] = arguments[i][prop]; } } } return obj; }, showLoadingView: function (win, opts) { opts = opts || {}; if (loadingView === false) { loadingView = Ti.UI.createView({ width: 120, height: 60, backgroundColor: "#000", opcaity: 0.8, borderRadius: 10, top: ((420 - 20 - 44 - 44) / 2) - 30, left: ((320 / 2) - 60), zIndex: 1000 }); var act = Ti.UI.createActivityIndicator({ left: (120 / 2) - 20, width: 40, height: 40, top: 0, style: Ti.UI.iPhone.ActivityIndicatorStyle.LIGHT }); var lbl = Ti.UI.createLabel({ bottom: 5, left: 0, height: 20, text: "Loading...", color: "#fff", textAlign: "center", font: { fontSize: 14, fontWeight: "bold" } }); loadingView.add(lbl); loadingView.add(act); act.show(); loadingView.visible = false; win.add(loadingView); } loadingView.children[0].text = opts.message || "Loading..."; loadingView.visible = true; }, hideLoadingView: function (opts) { loadingView.visible = false; loadingView = false; }, createProductTableViewRow: function (product, hasPurchased) { var row = Ti.UI.createTableViewRow({ hasChild: !hasPurchased ? true : false, hasCheck: hasPurchased ? true : false, height: 60 }); var title = Ti.UI.createLabel({ top: 5, left: 10, height: 30, text: product.title, color: "#000", font: { fontSize: 20, fontWeight: "bold" } }); row.add(title); var cost = Ti.UI.createLabel({ bottom: 5, left: 10, height: 25, text: product.price, color: "#222", font: { fontSize: 16 } }); row.add(cost); return row; }, createProductDetailWindow: function (product, opts) { var o = skhelper.extend({ uidebug: true }, opts || {}); var newWin = Ti.UI.createWindow({ title: product.title, backgroundColor: "#fff" }); var container = Ti.UI.createScrollView({ contentHeight: "auto", showVerticalScrollIndicator: true, backgroundColor: "#fff" }); var icon = Ti.UI.createView({ top: 10, left: 10, width: 70, height: 70, borderRadius: 10, backgroundColor: "#222" }); container.add(icon); var title = Ti.UI.createLabel({ top: 10, left: 90, height: "auto", text: product.title, font: { fontSize: 22, fontWeight: "bold" } }); container.add(title); var buyButton = Ti.UI.createButton({ top: 50, right: 10, height: 35, width: 100, title: product.price }); buyButton.addEventListener("click", function (e) { skhelper.buyProduct(e, o, product, newWin); }); container.add(buyButton); var description = Ti.UI.createLabel({ top: 90, left: 10, right: 10, height: "auto", text: product.description, color: "#222", font: { fontSize: 18 } }); container.add(description); newWin.add(container); return newWin; }, buyProduct: function (e, o, product, newWin) { skhelper.showLoadingView(newWin, { message: "Purchasing..." }); if (!o.uidebug) { tistorekit.buyProduct({ identifier: product.identifier, success: function (e) { o.win(e.purchased, newWin); skhelper.hideLoadingView(); }, fail: function (e) { skhelper.hideLoadingView(); Ti.UI.createAlertDialog({ title: "Purchase Failed", message: "Unable to make purchase." }).show(); o.error({ product: product }); } }); } else { skhelper.hideLoadingView(); // Fake purchase callback. o.win({ purchased: [{ state: "PaymentTransactionStatePurchased", identifier: "com.yourproduct.id", receipt: "kdshfljdsnoivbnoifdslkfjdlksf", transactionIdentifier: "dsfdsfds" }] }, newWin); } }, hasPurchasedProduct: function (identifier, purchased) { purchased = purchased || []; for (var i = 0; i < purchased.length; i++) { if (purchased[i] === identifier) { return true; } } return false; }, createRestoreWindow: function (products, opts) { var o = skhelper.extend({ uidebug: true }, opts || {}); var newWin = Ti.UI.createWindow({ title: "Restore/Transfer Purchase", backgroundColor: "#fff" }); var text = Ti.UI.createLabel({// restoreDetails top: 10, left: 10, right: 10, height: "auto", text: opts.restoreDetails || "You should write some stuff about restoring purchases here.", color: "#222", font: { fontSize: 18 } }); newWin.add(text); var restoreBtn = skhelper.createRestoreCompletedTransactionsButton(o, newWin); newWin.add(restoreBtn); setTimeout(function () { restoreBtn.top = text.top + text.height + 20; }, 100); return newWin; }, createCancelWindow: function (products, opts) { var o = skhelper.extend({ uidebug: true }, opts || {}); var newWin = Ti.UI.createWindow({ title: "Cancel Subscriptions", backgroundColor: "#fff" }); var text = Ti.UI.createLabel({// restoreDetails top: 10, left: 10, right: 10, height: "auto", text: opts.cancelDetails || "If you would like to cancel any of your subscriptions you need to cancel them through iTunes.\n\nOpen iTunes on your computer and go to the account view, from there you can manage your subscriptions.", color: "#222", font: { fontSize: 18 } }); newWin.add(text); return newWin; }, createRestoreCompletedTransactionsButton: function (opts, theWin) { var o = skhelper.extend({ uidebug: true, top: 20, left: 20, right: 20, width: 280, height: 34, title: "Restore Previous Purchases" }, opts || {}); var restoreAll = Ti.UI.createButton(o); restoreAll.addEventListener("click", function () { //alert("now restore everything..."); if (!o.uidebug) { tistorekit.restoreTransactions({ success: function (e) { o.win(e.purchased, theWin); Ti.API.debug(e); } }); } else { Ti.API.debug("some stuff was restored?"); } }); return restoreAll; }, createStoreWindow: function (opts) { return Ti.UI.createWindow({ title: "Store" }); }, createStoreTableView: function () { return Ti.UI.createTableView({ data: [], style: Ti.UI.iPhone.TableViewStyle.GROUPED }); }, close: function () { if (typeof modal != "undefined") { modal.close(); } }, startCheckout: function (opts) { var o = skhelper.extend({ // Should we use the tistorekit module or just fake the data so we can test the UI quicker. uidebug: true, // Products that can be purchased, accepts string or array. identifiers: "com.my.product", // Default function to render restore window, is passed products array. createRestoreWindow: skhelper.createRestoreWindow, // Default function to render cancel window, is passed products array. createCancelWindow: skhelper.createCancelWindow, // Default function to render product detail window, is passed the product. createProductDetailWindow: skhelper.createProductDetailWindow, // Default window. createStoreWindow: skhelper.createStoreWindow, // Creates the row for each product. createProductTableViewRow: skhelper.createProductTableViewRow, // Tableview. createStoreTableView: skhelper.createStoreTableView, // Array of already purchased product identifiers. purchased: [], // Callback when a product is purchased. success: function () { }, // Callback when the checkout is closed. closed: function () { }, // Callback when there is an error. error: function () { } }, opts || {}); var products = false; modal = Ti.UI.createWindow({ navBarHidden: true }); var storeWin = o.createStoreWindow(); var tableView = o.createStoreTableView(); storeWin.add(tableView); var gotProducts = function (e) { var data = []; data[0] = Ti.UI.createTableViewSection({ headerTitle: "Products" }); data[1] = Ti.UI.createTableViewSection({ headerTitle: "Subscription Options" }); data[1].add(Ti.UI.createTableViewRow({ title: "Transfer/Restore Purchases", restore: true, hasChild: true })); data[1].add(Ti.UI.createTableViewRow({ title: "Cancel Subscriptions", cancel: true, hasChild: true })); if (typeof e.products != "undefined") { products = e.products; for (var i = 0; i < e.products.length; i++) { data[0].add(o.createProductTableViewRow(e.products[i], skhelper.hasPurchasedProduct(e.products[i].identifier, o.purchased))); } } tableView.setData(data); }; tableView.addEventListener("click", function (e) { if (e.rowData.restore === true) { var newWin = o.createRestoreWindow(products, o); nav.open(newWin); } else if (e.rowData.cancel === true) { var newWin = o.createCancelWindow(products, o); nav.open(newWin); } else if (e.row.hasChild === true) { var newWin = o.createProductDetailWindow(products[e.index], o); nav.open(newWin); } }); var done = Titanium.UI.createButton({ systemButton:Titanium.UI.iPhone.SystemButton.DONE }); storeWin.setRightNavButton(done); done.addEventListener("click", function (e) { modal.close(); o.closed(); }); var nav = Ti.UI.iPhone.createNavigationGroup({ window: storeWin }); modal.add(nav); modal.open({ modal: true }); skhelper.showLoadingView(storeWin, { message: "Retrieving..." }); if (!o.uidebug) { tistorekit.getProducts({ identifiers: o.identifiers, success: function (e) { gotProducts(e); skhelper.hideLoadingView(); retrieved = true; }, fail: function (e) { o.error({ code: 101, message: "Invalid product ID's specified.", products: e.failed }); } }); } else { gotProducts({ products: [{ identifier: "com.yourproduct.id", title: "Some stuff", description: "blah, blah, blah", price: "$1.99" }] }); skhelper.hideLoadingView(); } } }; module.exports = skhelper;
import React, { Component } from 'react' import S3Client from '/lib/s3'; export class S3Upload extends Component { constructor(props) { super(props); this.s3 = new S3Client(); this.setCredentials(props.credentials, props.configuration); this.inputRef = React.createRef(); } isReady(creds, config) { return ( !!creds && 'endpoint' in creds && 'accessKeyId' in creds && 'secretAccessKey' in creds && creds.endpoint !== '' && creds.accessKeyId !== '' && creds.secretAccessKey !== '' && !!config && 'currentBucket' in config && config.currentBucket !== '' ); } componentDidUpdate(prevProps) { const { props } = this; this.setCredentials(props.credentials, props.configuration); } setCredentials(credentials, configuration) { if (!this.isReady(credentials, configuration)) { return; } this.s3.setCredentials( credentials.endpoint, credentials.accessKeyId, credentials.secretAccessKey ); } getFileUrl(endpoint, filename) { return endpoint + '/' + filename; } onChange() { const { props } = this; if (!this.inputRef.current) { return; } let files = this.inputRef.current.files; if (files.length <= 0) { return; } let file = files.item(0); let bucket = props.configuration.currentBucket; this.s3.upload(bucket, file.name, file).then((data) => { if (!data || !('Location' in data)) { return; } this.props.uploadSuccess(data.Location); }).catch((err) => { console.error(err); this.props.uploadError(err); }); } onClick() { if (!this.inputRef.current) { return; } this.inputRef.current.click(); } render() { const { props } = this; if (!this.isReady(props.credentials, props.configuration)) { return <div></div>; } else { let classes = !!props.className ? "pointer " + props.className : "pointer"; return ( <div className={classes}> <input className="dn" type="file" id="fileElement" ref={this.inputRef} accept="image/*" onChange={this.onChange.bind(this)} /> <img className="invert-d" src="/~groups/img/ImageUpload.png" width="32" height="32" onClick={this.onClick.bind(this)} /> </div> ); } } }
"use strict"; //# sourceMappingURL=product.js.map
const AbstractHandler = require('./AbstractHandler'); class GuildSyncHandler extends AbstractHandler { handle(packet) { const client = this.packetManager.client; const data = packet.d; client.actions.GuildSync.handle(data); } } module.exports = GuildSyncHandler;
const { describe, it } = global; import { expect } from 'chai'; import { shallow } from 'enzyme'; import SignIn from '../sign_in'; describe('users.components.sign_in', () => { it('should do something'); });
var Calendar = require('./Calendar'); var CalendarToggleButton = require('./CalendarToggleButton'); var DateInput = require('./DateInput'); var React = require('react/addons'); var {InputWithPopup} = require('react-pick'); var {PureRenderMixin} = React.addons; var moment = require('moment'); var emptyFunction = require('react-pick/lib/helpers/emptyFunction'); var DateInput = React.createClass({ mixins: [PureRenderMixin], propTypes: { /** * Event handler fired when the value of the `<DateInput>` changes. * The called function is passed `value`. */ onChange: React.PropTypes.func.isRequired, /** * The current value of the `<DateInput>`, as a `moment` date. */ value: React.PropTypes.object, /** * Event handler fired when a new non-null value is selected and the * popup closed. The called function is passed `value`. */ onComplete: React.PropTypes.func, /** * The format of the date shown and parsed in the `<input> box. * Default is `'l'`. */ inputValueFormat: React.PropTypes.string, /** * The component to render for the calendar in the popup. * Default is `Calendar`. */ calendarComponent: React.PropTypes.func, /** * The component to render for the toggle button next to the input box. * Setting this to `null` hides the toggle button entirely. * Default is `CalendarToggleButton`. */ calendarToggleButtonComponent: React.PropTypes.func, /** * The locale to be used for the format of the date. If you absolutely need * to override the locale for some reason, use this. * Default is the browser's `window.navigator.language` value. */ locale: React.PropTypes.string }, getDefaultProps: function() { return { value: null, inputValueFormat: 'l', onComplete: emptyFunction, inputComponent: 'input', calendarComponent: Calendar, calendarToggleButtonComponent: CalendarToggleButton, locale: window.navigator.userLanguage || window.navigator.language }; }, getInitialState: function() { var {value, locale, inputValueFormat} = this.props; return { isOpen: false, popupMonth: value || moment().locale(locale), inputValue: (value !== null) ? value.format(inputValueFormat) : null }; }, componentWillReceiveProps: function(nextProps) { if (this.props.value !== nextProps.value && nextProps.value !== null) { this.setState({ inputValue: nextProps.value.format(nextProps.inputValueFormat), popupMonth: nextProps.value }); } }, handlePopupMonthChange: function(popupMonth) { this.setState({popupMonth}); }, handlePopupChange: function(value) { this.props.onChange(value); }, handlePopupComplete: function(value) { this.setState({isOpen: false}); this.props.onChange(value); this.props.onComplete(value); }, handlePopupCancel: function() { this.setState({isOpen: false}); }, handleInputChange: function(event) { var inputValue = event.target.value; var {locale, inputValueFormat} = this.props; this.setState({inputValue}); var parsedInputValue = moment(inputValue, inputValueFormat, locale, true); if (parsedInputValue.isValid()) { this.setState({popupMonth: parsedInputValue}); this.props.onChange(parsedInputValue); } else { this.props.onChange(null); } }, handleClick: function() { this.setState({isOpen: !this.state.isOpen}, () => { this.state.isOpen && this.refs['popup'].focusOnGrid(); }); }, render: function() { var CalendarComponent = this.props.calendarComponent; var CalendarToggleButtonComponent = this.props.calendarToggleButtonComponent; var {buttonComponent, value, ...otherProps} = this.props; return ( <div className="DateInput"> <InputWithPopup {...otherProps} isOpen={this.state.isOpen} value={this.state.inputValue} onFocus={this.handleInputFocus} onBlur={this.handleInputBlur} onChange={this.handleInputChange} onClick={this.handleClick}> <CalendarComponent buttonComponent={buttonComponent} month={this.state.popupMonth} onCancel={this.handlePopupCancel} onChange={this.handlePopupChange} onComplete={this.handlePopupComplete} onMonthChange={this.handlePopupMonthChange} ref="popup" value={value} /> </InputWithPopup> {CalendarToggleButtonComponent && <CalendarToggleButtonComponent aria-hidden="true" onClick={this.handleClick} />} </div> ); } }); module.exports = DateInput;
/* * jQuery Custom Forms Plugin 1.0 * www.ZURB.com * Copyright 2010, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ jQuery.foundation = jQuery.foundation || {}; jQuery.foundation.customForms = jQuery.foundation.customForms || {}; jQuery(document).ready(function ($) { $.foundation.customForms.appendCustomMarkup = function (options) { var defaults = { disable_class: "js-disable-custom" }; var options = $.extend(defaults, options); function appendCustomMarkup(idx, sel) { var $this = $(sel).hide(), type = $this.attr('type'), $span = $this.next('span.custom.' + type); if ($span.length === 0) { $span = $('<span class="custom ' + type + '"></span>').insertAfter($this); } $span.toggleClass('checked', $this.is(':checked')); $span.toggleClass('disabled', $this.is(':disabled')); } function appendCustomSelect(idx, sel) { var $this = $(sel), $customSelect = $this.next('div.custom.dropdown'), $options = $this.find('option'), $seloptions = $this.find('option:selected'), maxWidth = 0, $li; if ($this.hasClass('no-custom')) { return; } if ($customSelect.length === 0) { $customSelectSize = ''; if ($(sel).hasClass('small')) { $customSelectSize = 'small'; } else if ($(sel).hasClass('medium')) { $customSelectSize = 'medium'; } else if ($(sel).hasClass('large')) { $customSelectSize = 'large'; } else if ($(sel).hasClass('expand')) { $customSelectSize = 'expand'; } $customSelect = $('<div class="custom dropdown ' + $customSelectSize + '"><a href="#" class="selector"></a><ul></ul></div>"'); $options.each(function () { $li = $('<li>' + $(this).html() + '</li>'); $customSelect.find('ul').append($li); }); $customSelect.prepend('<a href="#" class="current">' + $seloptions.html() + '</a>'); $this.after($customSelect); $this.hide(); } else { // refresh the ul with options from the select in case the supplied markup doesn't match $customSelect.find('ul').html(''); $options.each(function () { $li = $('<li>' + $(this).html() + '</li>'); $customSelect.find('ul').append($li); }); } $customSelect.toggleClass('disabled', $this.is(':disabled')); $options.each(function (index) { if (this.selected) { $customSelect.find('li').eq(index).addClass('selected'); $customSelect.find('.current').html($(this).html()); } }); $customSelect.css('width', 'inherit'); $customSelect.find('ul').css('width', 'inherit'); $customSelect.find('li').each(function () { $customSelect.addClass('open'); if ($(this).outerWidth() > maxWidth) { maxWidth = $(this).outerWidth(); } $customSelect.removeClass('open'); }); if (!$customSelect.is('.small, .medium, .large, .expand')) { $customSelect.css('width', maxWidth + 18 + 'px'); $customSelect.find('ul').css('width', maxWidth + 16 + 'px'); } } $('form.custom input:radio[data-customforms!=disabled]').each(appendCustomMarkup); $('form.custom input:checkbox[data-customforms!=disabled]').each(appendCustomMarkup); $('form.custom select[data-customforms!=disabled]').each(appendCustomSelect); }; }); (function ($) { function refreshCustomSelect($select) { var maxWidth = 0, $customSelect = $select.next(); $options = $select.find('option'); $customSelect.find('ul').html(''); $options.each(function () { $li = $('<li>' + $(this).html() + '</li>'); $customSelect.find('ul').append($li); }); // re-populate $options.each(function (index) { if (this.selected) { $customSelect.find('li').eq(index).addClass('selected'); $customSelect.find('.current').html($(this).html()); } }); // fix width $customSelect.removeAttr('style') .find('ul').removeAttr('style'); $customSelect.find('li').each(function () { $customSelect.addClass('open'); if ($(this).outerWidth() > maxWidth) { maxWidth = $(this).outerWidth(); } $customSelect.removeClass('open'); }); $customSelect.css('width', maxWidth + 18 + 'px'); $customSelect.find('ul').css('width', maxWidth + 16 + 'px'); } function toggleCheckbox($element) { var $input = $element.prev(), input = $input[0]; if (false == $input.is(':disabled')) { input.checked = ((input.checked) ? false : true); $element.toggleClass('checked'); $input.trigger('change'); } } function toggleRadio($element) { var $input = $element.prev(), input = $input[0]; if (false == $input.is(':disabled')) { $('input:radio[name="' + $input.attr('name') + '"]').each(function () { $(this).next().removeClass('checked'); }); input.checked = ((input.checked) ? false : true); $element.toggleClass('checked'); $input.trigger('change'); } } $('form.custom span.custom.checkbox').live('click', function (event) { event.preventDefault(); event.stopPropagation(); toggleCheckbox($(this)); }); $('form.custom span.custom.radio').live('click', function (event) { event.preventDefault(); event.stopPropagation(); toggleRadio($(this)); }); $('form.custom select').live('change', function (event) { refreshCustomSelect($(this)); }); $('form.custom label').live('click', function (event) { var $associatedElement = $('#' + $(this).attr('for')), $customCheckbox, $customRadio; if ($associatedElement.length !== 0) { if ($associatedElement.attr('type') === 'checkbox') { event.preventDefault(); $customCheckbox = $(this).find('span.custom.checkbox'); toggleCheckbox($customCheckbox); } else if ($associatedElement.attr('type') === 'radio') { event.preventDefault(); $customRadio = $(this).find('span.custom.radio'); toggleRadio($customRadio); } } }); $('form.custom div.custom.dropdown a.current, form.custom div.custom.dropdown a.selector').live('click', function (event) { var $this = $(this), $dropdown = $this.closest('div.custom.dropdown'), $select = $dropdown.prev(); event.preventDefault(); if (false == $select.is(':disabled')) { $dropdown.toggleClass('open'); if ($dropdown.hasClass('open')) { $(document).bind('click.customdropdown', function (event) { $dropdown.removeClass('open'); $(document).unbind('.customdropdown'); }); } else { $(document).unbind('.customdropdown'); } return false; } }); $('form.custom div.custom.dropdown li').live('click', function (event) { var $this = $(this), $customDropdown = $this.closest('div.custom.dropdown'), $select = $customDropdown.prev(), selectedIndex = 0; event.preventDefault(); event.stopPropagation(); $this .closest('ul') .find('li') .removeClass('selected'); $this.addClass('selected'); $customDropdown .removeClass('open') .find('a.current') .html($this.html()); $this.closest('ul').find('li').each(function (index) { if ($this[0] == this) { selectedIndex = index; } }); $select[0].selectedIndex = selectedIndex; $select.trigger('change'); }); })(jQuery);
// Copyright 2012 Mark Cavage, Inc. All rights reserved. var EventEmitter = require('events').EventEmitter; var http = require('http'); var https = require('https'); var url = require('url'); var util = require('util'); var assert = require('assert-plus'); var clone = require('clone'); var mime = require('mime'); var once = require('once'); var spdy = require('spdy'); var dtrace = require('./dtrace'); var errors = require('./errors'); var formatters = require('./formatters'); // Ensure these are loaded require('./request'); require('./response'); ///--- Globals var sprintf = util.format; var BadMethodError = errors.BadMethodError; var InvalidVersionError = errors.InvalidVersionError; var ResourceNotFoundError = errors.ResourceNotFoundError; var PROXY_EVENTS = [ 'clientError', 'close', 'connection', 'error', 'listening', 'secureConnection', 'upgrade' ]; ///--- Helpers function argumentsToChain(args, start) { assert.ok(args); args = Array.prototype.slice.call(args, start); if (args.length < 0) throw new TypeError('handler (function) required'); var chain = []; function process(handlers) { for (var i = 0; i < handlers.length; i++) { if (Array.isArray(handlers[i])) { process(handlers[i], 0); } else { assert.func(handlers[i], 'handler'); chain.push(handlers[i]); } } return (chain); } return (process(args)); } ///--- API function Server(options) { assert.object(options, 'options'); assert.object(options.log, 'options.log'); assert.object(options.router, 'options.router'); var self = this; EventEmitter.call(this); this.acceptable = []; this.before = []; this.chain = []; this.formatters = {}; this.log = options.log; this.name = options.name || 'restify'; this.router = options.router; this.routes = {}; this.secure = false; this.version = options.version || null; if (options.formatters) { Object.keys(options.formatters).forEach(function (k) { assert.func(options.formatters[k], 'formatter'); if (k.indexOf('/') === -1) k = mime.lookup(k); self.formatters[k] = options.formatters[k]; if (self.acceptable.indexOf(k) === -1) self.acceptable.push(k); }); } Object.keys(formatters).forEach(function (k) { if (!self.formatters[k]) { self.formatters[k] = formatters[k]; if (self.acceptable.indexOf(k) === -1) self.acceptable.push(k); } }); if (options.spdy) { this.spdy = true; this.server = spdy.createServer(options.spdy); } else if ((options.cert || options.certificate) && options.key) { this.ca = options.ca; this.certificate = options.certificate || options.cert; this.key = options.key; this.secure = true; this.server = https.createServer({ ca: self.ca, cert: self.certificate, key: self.key, rejectUnauthorized: options.rejectUnauthorized, requestCert: options.requestCert }); } else { this.server = http.createServer(); } PROXY_EVENTS.forEach(function (e) { self.server.on(e, self.emit.bind(self, e)); }); // Now the things we can't blindly proxy this.server.on('checkContinue', function onCheckContinue(req, res) { if (self.listeners('checkContinue').length > 0) { self.emit('checkContinue', req, res); return; } if (!options.noWriteContinue) res.writeContinue(); self._setupRequest(req, res); self._handle(req, res, true); }); this.server.on('request', function onRequest(req, res) { /* JSSTYLED */ if (/^\/socket.io.*/.test(req.url) && self.listeners('request').length > 0) { self.emit('request', req, res); return; } self._setupRequest(req, res); self._handle(req, res); }); this.__defineGetter__('maxHeadersCount', function () { return (self.server.maxHeadersCount); }); this.__defineSetter__('maxHeadersCount', function (c) { self.server.maxHeadersCount = c; return (c); }); this.__defineGetter__('url', function () { if (self.socketPath) return ('http://' + self.socketPath); var addr = self.address(); var str = ''; if (self.spdy) { str += 'spdy://'; } else if (self.secure) { str += 'https://'; } else { str += 'http://'; } str += addr.address; str += ':'; str += addr.port; return (str); }); } util.inherits(Server, EventEmitter); module.exports = Server; Server.prototype.address = function address() { return (this.server.address()); }; /** * Gets the server up and listening. * * You can call like: * server.listen(80) * server.listen(80, '127.0.0.1') * server.listen('/tmp/server.sock') * * @param {Function} callback optionally get notified when listening. * @throws {TypeError} on bad input. */ Server.prototype.listen = function listen() { var args = Array.prototype.slice.call(arguments); return (this.server.listen.apply(this.server, args)); }; /** * Shuts down this server, and invokes callback (optionally) when done. * * @param {Function} callback optional callback to invoke when done. */ Server.prototype.close = function close(callback) { if (callback) assert.func(callback, 'callback'); this.server.once('close', function onClose() { return (callback ? callback() : false); }); return (this.server.close()); }; // Register all the routing methods /** * Mounts a chain on the given path against this HTTP verb * * @param {Object} options the URL to handle, at minimum. * @return {Route} the newly created route. */ [ 'del', 'get', 'head', 'opts', 'post', 'put', 'patch' ].forEach(function (method) { Server.prototype[method] = function (opts) { if (opts instanceof RegExp || typeof (opts) === 'string') { opts = { path: opts }; } else if (typeof (opts) === 'object') { opts = clone(opts); } else { throw new TypeError('path (string) required'); } if (arguments.length < 2) throw new TypeError('handler (function) required'); var chain = []; var route; var self = this; function addHandler(h) { assert.func(h, 'handler'); chain.push(h); } if (method === 'del') method = 'DELETE'; if (method === 'opts') method = 'OPTIONS'; opts.method = method.toUpperCase(); opts.version = opts.version || self.version; if (!Array.isArray(opts.version)) opts.version = [opts.version]; if (!opts.name) { opts.name = method + '-' + (opts.path || opts.url); if (opts.version) { opts.name += '-' + opts.version.join('--'); } } opts.name = opts.name.replace(/\W/g, '').toLowerCase(); if (!(route = this.router.mount(opts))) return (false); this.chain.forEach(addHandler); argumentsToChain(arguments, 1).forEach(addHandler); this.routes[route] = chain; return (route); }; }); /** * Minimal port of the functionality offered by Express.js Route Param * Pre-conditions * @link http://expressjs.com/guide.html#route-param%20pre-conditions * * This basically piggy-backs on the `server.use` method. It attaches a * new middleware function that only fires if the specified parameter exists * in req.params * * Exposes an API: * server.param("user", function (req, res, next) { * // load the user's information here, always making sure to call next() * }); * * @param {String} The name of the URL param to respond to * @param {Function} The middleware function to execute */ Server.prototype.param = function param(name, fn) { this.use(function _param(req, res, next) { if (req.params && req.params[name]) { fn.call(this, req, res, next, req.params[name], name); } else { next(); } }); return (this); }; /** * Removes a route from the server. * * You pass in the route 'blob' you got from a mount call. * * @param {String} name the route name. * @return {Boolean} true if route was removed, false if not. * @throws {TypeError} on bad input. */ Server.prototype.rm = function rm(route) { var r = this.router.unmount(route); if (r && this.routes[r]) delete this.routes[r]; return (r); }; /** * Installs a list of handlers to run _before_ the "normal" handlers of all * routes. * * You can pass in any combination of functions or array of functions. * * @throws {TypeError} on input error. */ Server.prototype.use = function use() { var self = this; (argumentsToChain(arguments) || []).forEach(function (h) { self.chain.push(h); }); return (this); }; /** * Gives you hooks to run _before_ any routes are located. This gives you * a chance to intercept the request and change headers, etc., that routing * depends on. Note that req.params will _not_ be set yet. */ Server.prototype.pre = function pre() { var self = this; argumentsToChain(arguments).forEach(function (h) { self.before.push(h); }); return (this); }; Server.prototype.toString = function toString() { var LINE_FMT = '\t%s: %s\n'; var SUB_LINE_FMT = '\t\t%s: %s\n'; var self = this; var str = ''; function handlersToString(arr) { var s = '[' + arr.map(function (b) { return (b.name || 'function'); }).join(', ') + ']'; return (s); } str += sprintf(LINE_FMT, 'Accepts', this.acceptable.join(', ')); str += sprintf(LINE_FMT, 'Name', this.name); str += sprintf(LINE_FMT, 'Pre', handlersToString(this.before)); str += sprintf(LINE_FMT, 'Router', this.router.toString()); str += sprintf(LINE_FMT, 'Routes:', ''); Object.keys(this.routes).forEach(function (k) { var handlers = handlersToString(self.routes[k]); str += sprintf(SUB_LINE_FMT, k, handlers); }); str += sprintf(LINE_FMT, 'Secure', this.secure); str += sprintf(LINE_FMT, 'Url', this.url); str += sprintf(LINE_FMT, 'Version', this.version); return (str); }; ///--- Private methods Server.prototype._handle = function _handle(req, res) { var log = this.log; var self = this; function _route() { if (log.trace()) { log.trace({ req: req, req_id: req.getId() }, 'checking for route'); } self.router.find(req, res, function (err, r, ctx) { if (err) { if (err.statusCode === 404 && req.method === 'OPTIONS' && req.url === '*') { res.send(200); } else { log.trace({ err: err, req: req }, 'router errored out'); res.send(err); } self.emit('after', req, res, null); } else if (!r || !self.routes[r]) { log.trace({req: res}, 'no route found'); res.send(404); self.emit('after', req, res, null); } else { if (log.trace()) { log.trace({ req_id: req.getId(), route: r }, 'route found'); } req.context = ctx; var chain = self.routes[r]; self._run(req, res, r, chain, function (e) { self.emit('after', req, res, r, e); }); } }); } // We need to check if should run the _pre_ chain first. if (this.before.length > 0) { if (log.trace()) log.trace({req: req}, 'running pre chain'); this._run(req, res, null, this.before, function (err) { if (err) { log.trace({ err: err }, 'pre chain errored out. Done.'); return (false); } return (_route()); }); return (false); } return (_route()); }; Server.prototype._run = function _run(req, res, route, chain, callback) { var i = -1; var log = this.log; var self = this; function next(err) { // The goofy checks here are to make sure we fire the DTrace // probes after an error might have been sent, as in a handler // return next(new Error) is basically shorthand for sending an // error via res.send(), so we do that before firing the dtrace // probe (namely so the status codes get updated in the // response). var done = false; if (err) { if (log.trace()) log.trace({err: err}, 'next(err=%s)', err.name || 'Error'); res.send(err); done = true; } // Callers can stop the chain from proceding if they do // return next(false); This is useful for non-errors, but where // a response was sent and you don't want the chain to keep // going if (err === false) done = true; // Fire DTrace done for the previous handler. if ((i + 1) > 0 && chain[i]) { dtrace._rstfy_probes['handler-done'].fire(function () { return ([ self.name, route !== null ? route : 'pre', chain[i].name || ('handler-' + i), req.connection.fd ]); }); } // Run the next handler up if (!done && chain[++i]) { if (log.trace()) log.trace('running %s', chain[i].name || '?'); dtrace._rstfy_probes['handler-start'].fire(function () { return ([ self.name, route !== null ? route : 'pre', chain[i].name || ('handler-' + i), req.connection.fd ]); }); try { return (chain[i].call(self, req, res, once(next))); } catch (e) { log.trace({err: e}, 'uncaughtException'); self.emit('uncaughtException', req, res, route, e); return (callback ? callback(e) : false); } } dtrace._rstfy_probes['route-done'].fire(function () { return ([ self.name, route !== null ? route : 'pre', req.connection.fd, res.statusCode || 200, JSON.stringify(res.headers()) ]); }); if (route === null) { self.emit('preDone', req, res); } else { self.emit('done', req, res, route); } return (callback ? callback(err) : true); } dtrace._rstfy_probes['route-start'].fire(function () { return ([ self.name, route !== null ? route : 'pre', req.connection.fd, req.method, req.href(), JSON.stringify(req.headers) ]); }); next(); }; Server.prototype._setupRequest = function _setupRequest(req, res) { req.log = res.log = this.log; req._time = res._time = Date.now(); res.acceptable = this.acceptable; res.formatters = this.formatters; res.req = req; res.serverName = this.name; res.version = this.router.version[this.router.version.length - 1]; // HTTP METHODS set for the current route: res.methods = this.router.reverse[Object.keys(this.router.reverse)[0]]; };
angular.module('vinibar.gift', [ 'ui.router', 'clientFactory', 'vinibar.gift.vinibar', 'ui.bootstrap', 'Resources', 'Mixpanel', 'settings' ]) .config(function config ($stateProvider) { $stateProvider .state('gift', { url: '/cadeau', abstract: true, views: { main: { templateUrl: 'gift/gift.tpl.html' } } }) .state('gift.choose', { url: '/type?test', templateUrl: 'gift/choose.tpl.html', controller: 'chooseGiftCtrl', data: { pageTitle: 'Cadeau' } }) .state('gift.pay', { url: '/paiement', templateUrl: 'gift/pay.tpl.html', controller: 'giftPayCtrl', data: { pageTitle: 'Cadeau' } }); }) .controller('chooseGiftCtrl', function ($stateParams, settings, Mixpanel, $rootScope, $scope, $state) { if ($stateParams.test) { settings.test = true; } Mixpanel.track('viewed cadeau/type'); $scope.goTo = function (state) { Mixpanel.track('Selected: ' + state); $state.go(state); }; }) .controller('giftPayCtrl', function giftPayCtrl (Mixpanel, $scope, $http, $state, $window, currentGift, currentGiftCard, params, toaster, settings, $modal, currentClient) { Stripe.setPublishableKey((settings.test) ? 'pk_test_sK21onMmCuKNuoY7pbml8z3Q' : 'pk_live_gNv4cCe8tsZpettPUsdQj25F'); $scope.gift = currentGift.current; console.log($scope.gift); $scope.test = settings.test; $scope.submit = function (status, response) { $scope.load = { spin: true }; if (response.error) { $scope.load = { spin: false }; toaster.pop('infos', 'Erreur', 'Merci de vérifier vos coordonnées bancaires.'); } else { $scope.gift.chargeGiftOrder(response.id, $scope.gift.receiver.gift_uuid, settings.test, $scope.gift.order.billing, $scope.gift.order.billing_address) .success(function (data, status, headers, config) { if ($scope.gift.order.delivery_mode === 'Point Relais') { $http.post(settings.apiEndPoint + '/orders/pickmremail/', { order_id: data.order }); } $scope.load = { spin: false }; currentClient.order = data; currentGiftCard.code = data.activation_code; currentGiftCard.credits = data.credits; if (settings.test) { $state.go('remerciement_gift', { print: ($scope.gift.order.gift_type === 'Print') ? true : false }); } else { var amount = Math.round((($scope.gift.final_price - $scope.gift.delivery_cost) / 1.2) * 100) / 100; $window.location = 'https://vinify.co/remerciement/cadeau.html' + '?id=' + $scope.gift.receiver.gift_uuid + '&amount=' + amount; Mixpanel.track('Sucessful payment'); } }) .error(function (data, status, headers, config) { $scope.load = { spin: false }; toaster.pop('error', 'Une erreur est survenue', 'Vous n\'avez pas été facturé. Merci de réessayer'); Mixpanel.track('Server failed to proceed payment'); }); } }; $scope.open = function (size) { $scope.address = {}; var modalInstance = $modal.open({ templateUrl: 'gift/address.tpl.html', controller: 'ModalInstanceCtrl', size: size }); modalInstance.result.then(function (address) { $scope.gift.order.billing = true; $scope.gift.order.billing_address = address; toaster.pop('success', 'Votre adresse a été ajoutée', 'Vous recevrez la facture par mail'); }, function () { }); }; }) .controller('ModalInstanceCtrl', function ($scope, $modalInstance) { $scope.ok = function () { $modalInstance.close($scope.address); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; });
import React, { Component } from 'react' export default class URL extends Component { constructor(props) { super(props) this.state = { formState: 'default', value: this.props.url, } } handleChange(evt) { this.setState({ value: evt.target.value, formState: 'default' }) } handleSubmit(evt) { evt.preventDefault() if (this.validURL(this.state.value)){ this.setState({formState: 'loading'}) var url = this.state.value.trim() this.props.onSubmit({url: url}) this.props.onHide() } else { this.setState({formState: 'fail'}) } } handleKeyPress(evt){ if (evt.keyCode == 13) { this.handleSubmit(evt) } } validURL(url){ return /^(.*[a-zA-Z0-9]+((\.|\:)[a-zA-Z0-9]+)+.*)$/.test(url) } componentDidMount(){ this.refs.weburl.focus() } render() { var loader; if (this.state.formState == 'default'){ loader = (<img src="./src/arrow.svg" className="arrow"/>) } else if (this.state.formState == 'loading'){ loader = (<img src="./src/loader.svg" className="rotator"/>) } else if (this.state.formState == 'fail'){ loader = (<img src="./src/fail.svg" className="arrow"/>) this.refs.weburl.focus() } return ( <div> <form onSubmit={this.handleSubmit.bind(this)}> <input ref="weburl" className={"weburl " + this.state.formState} type="text" placeholder="např. www.seznam.cz" onChange={this.handleChange.bind(this)} onKeyDown={this.handleKeyPress.bind(this)} value={this.state.value}/> <button type="submit" value="Post" className="addButton"> {loader} </button> </form> </div> ) } }
// Meta data used by the AngularJS docs app angular.module('versionsData', []) .value('NG_VERSION', { "raw": "v1.3.20", "major": 1, "minor": 3, "patch": 20, "prerelease": [], "build": [], "version": "1.3.20", "codeName": "shallow-translucence", "full": "1.3.20", "commitSHA": "2a65c3deb76566b8810807267788c8983f1a36d4" }) .value('NG_VERSIONS', [ { "raw": "v1.3.20", "major": 1, "minor": 3, "patch": 20, "prerelease": [], "build": [], "version": "1.3.20", "codeName": "shallow-translucence", "full": "1.3.20", "commitSHA": "2a65c3deb76566b8810807267788c8983f1a36d4" }, { "raw": "v1.5.0-beta.1", "major": 1, "minor": 5, "patch": 0, "prerelease": [ "beta", 1 ], "build": [], "version": "1.5.0-beta.1", "docsUrl": "http://code.angularjs.org/1.5.0-beta.1/docs" }, { "raw": "v1.5.0-beta.0", "major": 1, "minor": 5, "patch": 0, "prerelease": [ "beta", 0 ], "build": [], "version": "1.5.0-beta.0", "docsUrl": "http://code.angularjs.org/1.5.0-beta.0/docs" }, { "raw": "v1.4.6", "major": 1, "minor": 4, "patch": 6, "prerelease": [], "build": [], "version": "1.4.6", "docsUrl": "http://code.angularjs.org/1.4.6/docs" }, { "raw": "v1.4.5", "major": 1, "minor": 4, "patch": 5, "prerelease": [], "build": [], "version": "1.4.5", "docsUrl": "http://code.angularjs.org/1.4.5/docs" }, { "raw": "v1.4.4", "major": 1, "minor": 4, "patch": 4, "prerelease": [], "build": [], "version": "1.4.4", "docsUrl": "http://code.angularjs.org/1.4.4/docs" }, { "raw": "v1.4.3", "major": 1, "minor": 4, "patch": 3, "prerelease": [], "build": [], "version": "1.4.3", "docsUrl": "http://code.angularjs.org/1.4.3/docs" }, { "raw": "v1.4.2", "major": 1, "minor": 4, "patch": 2, "prerelease": [], "build": [], "version": "1.4.2", "docsUrl": "http://code.angularjs.org/1.4.2/docs" }, { "raw": "v1.4.1", "major": 1, "minor": 4, "patch": 1, "prerelease": [], "build": [], "version": "1.4.1", "docsUrl": "http://code.angularjs.org/1.4.1/docs" }, { "raw": "v1.4.0", "major": 1, "minor": 4, "patch": 0, "prerelease": [], "build": [], "version": "1.4.0", "docsUrl": "http://code.angularjs.org/1.4.0/docs" }, { "raw": "v1.4.0-rc.2", "major": 1, "minor": 4, "patch": 0, "prerelease": [ "rc", 2 ], "build": [], "version": "1.4.0-rc.2", "docsUrl": "http://code.angularjs.org/1.4.0-rc.2/docs" }, { "raw": "v1.4.0-rc.1", "major": 1, "minor": 4, "patch": 0, "prerelease": [ "rc", 1 ], "build": [], "version": "1.4.0-rc.1", "docsUrl": "http://code.angularjs.org/1.4.0-rc.1/docs" }, { "raw": "v1.4.0-rc.0", "major": 1, "minor": 4, "patch": 0, "prerelease": [ "rc", 0 ], "build": [], "version": "1.4.0-rc.0", "docsUrl": "http://code.angularjs.org/1.4.0-rc.0/docs" }, { "raw": "v1.4.0-beta.6", "major": 1, "minor": 4, "patch": 0, "prerelease": [ "beta", 6 ], "build": [], "version": "1.4.0-beta.6", "docsUrl": "http://code.angularjs.org/1.4.0-beta.6/docs" }, { "raw": "v1.4.0-beta.5", "major": 1, "minor": 4, "patch": 0, "prerelease": [ "beta", 5 ], "build": [], "version": "1.4.0-beta.5", "docsUrl": "http://code.angularjs.org/1.4.0-beta.5/docs" }, { "raw": "v1.4.0-beta.4", "major": 1, "minor": 4, "patch": 0, "prerelease": [ "beta", 4 ], "build": [], "version": "1.4.0-beta.4", "docsUrl": "http://code.angularjs.org/1.4.0-beta.4/docs" }, { "raw": "v1.4.0-beta.3", "major": 1, "minor": 4, "patch": 0, "prerelease": [ "beta", 3 ], "build": [], "version": "1.4.0-beta.3", "docsUrl": "http://code.angularjs.org/1.4.0-beta.3/docs" }, { "raw": "v1.4.0-beta.2", "major": 1, "minor": 4, "patch": 0, "prerelease": [ "beta", 2 ], "build": [], "version": "1.4.0-beta.2", "docsUrl": "http://code.angularjs.org/1.4.0-beta.2/docs" }, { "raw": "v1.4.0-beta.1", "major": 1, "minor": 4, "patch": 0, "prerelease": [ "beta", 1 ], "build": [], "version": "1.4.0-beta.1", "docsUrl": "http://code.angularjs.org/1.4.0-beta.1/docs" }, { "raw": "v1.4.0-beta.0", "major": 1, "minor": 4, "patch": 0, "prerelease": [ "beta", 0 ], "build": [], "version": "1.4.0-beta.0", "docsUrl": "http://code.angularjs.org/1.4.0-beta.0/docs" }, { "raw": "v1.3.19", "major": 1, "minor": 3, "patch": 19, "prerelease": [], "build": [], "version": "1.3.19", "docsUrl": "http://code.angularjs.org/1.3.19/docs" }, { "raw": "v1.3.18", "major": 1, "minor": 3, "patch": 18, "prerelease": [], "build": [], "version": "1.3.18", "docsUrl": "http://code.angularjs.org/1.3.18/docs" }, { "raw": "v1.3.17", "major": 1, "minor": 3, "patch": 17, "prerelease": [], "build": [], "version": "1.3.17", "docsUrl": "http://code.angularjs.org/1.3.17/docs" }, { "raw": "v1.3.16", "major": 1, "minor": 3, "patch": 16, "prerelease": [], "build": [], "version": "1.3.16", "docsUrl": "http://code.angularjs.org/1.3.16/docs" }, { "raw": "v1.3.15", "major": 1, "minor": 3, "patch": 15, "prerelease": [], "build": [], "version": "1.3.15", "docsUrl": "http://code.angularjs.org/1.3.15/docs" }, { "raw": "v1.3.14", "major": 1, "minor": 3, "patch": 14, "prerelease": [], "build": [], "version": "1.3.14", "docsUrl": "http://code.angularjs.org/1.3.14/docs" }, { "raw": "v1.3.13", "major": 1, "minor": 3, "patch": 13, "prerelease": [], "build": [], "version": "1.3.13", "docsUrl": "http://code.angularjs.org/1.3.13/docs" }, { "raw": "v1.3.12", "major": 1, "minor": 3, "patch": 12, "prerelease": [], "build": [], "version": "1.3.12", "docsUrl": "http://code.angularjs.org/1.3.12/docs" }, { "raw": "v1.3.11", "major": 1, "minor": 3, "patch": 11, "prerelease": [], "build": [], "version": "1.3.11", "docsUrl": "http://code.angularjs.org/1.3.11/docs" }, { "raw": "v1.3.10", "major": 1, "minor": 3, "patch": 10, "prerelease": [], "build": [], "version": "1.3.10", "docsUrl": "http://code.angularjs.org/1.3.10/docs" }, { "raw": "v1.3.9", "major": 1, "minor": 3, "patch": 9, "prerelease": [], "build": [], "version": "1.3.9", "docsUrl": "http://code.angularjs.org/1.3.9/docs" }, { "raw": "v1.3.8", "major": 1, "minor": 3, "patch": 8, "prerelease": [], "build": [], "version": "1.3.8", "docsUrl": "http://code.angularjs.org/1.3.8/docs" }, { "raw": "v1.3.7", "major": 1, "minor": 3, "patch": 7, "prerelease": [], "build": [], "version": "1.3.7", "docsUrl": "http://code.angularjs.org/1.3.7/docs" }, { "raw": "v1.3.6", "major": 1, "minor": 3, "patch": 6, "prerelease": [], "build": [], "version": "1.3.6", "docsUrl": "http://code.angularjs.org/1.3.6/docs" }, { "raw": "v1.3.5", "major": 1, "minor": 3, "patch": 5, "prerelease": [], "build": [], "version": "1.3.5", "docsUrl": "http://code.angularjs.org/1.3.5/docs" }, { "raw": "v1.3.4", "major": 1, "minor": 3, "patch": 4, "prerelease": [], "build": [], "version": "1.3.4", "docsUrl": "http://code.angularjs.org/1.3.4/docs" }, { "raw": "v1.3.3", "major": 1, "minor": 3, "patch": 3, "prerelease": [], "build": [], "version": "1.3.3", "docsUrl": "http://code.angularjs.org/1.3.3/docs" }, { "raw": "v1.3.2", "major": 1, "minor": 3, "patch": 2, "prerelease": [], "build": [], "version": "1.3.2", "docsUrl": "http://code.angularjs.org/1.3.2/docs" }, { "raw": "v1.3.1", "major": 1, "minor": 3, "patch": 1, "prerelease": [], "build": [], "version": "1.3.1", "docsUrl": "http://code.angularjs.org/1.3.1/docs" }, { "raw": "v1.3.0", "major": 1, "minor": 3, "patch": 0, "prerelease": [], "build": [], "version": "1.3.0", "docsUrl": "http://code.angularjs.org/1.3.0/docs" }, { "raw": "v1.3.0-rc.5", "major": 1, "minor": 3, "patch": 0, "prerelease": [ "rc", 5 ], "build": [], "version": "1.3.0-rc.5", "docsUrl": "http://code.angularjs.org/1.3.0-rc.5/docs" }, { "raw": "v1.3.0-rc.4", "major": 1, "minor": 3, "patch": 0, "prerelease": [ "rc", 4 ], "build": [], "version": "1.3.0-rc.4", "docsUrl": "http://code.angularjs.org/1.3.0-rc.4/docs" }, { "raw": "v1.3.0-rc.3", "major": 1, "minor": 3, "patch": 0, "prerelease": [ "rc", 3 ], "build": [], "version": "1.3.0-rc.3", "docsUrl": "http://code.angularjs.org/1.3.0-rc.3/docs" }, { "raw": "v1.3.0-rc.2", "major": 1, "minor": 3, "patch": 0, "prerelease": [ "rc", 2 ], "build": [], "version": "1.3.0-rc.2", "docsUrl": "http://code.angularjs.org/1.3.0-rc.2/docs" }, { "raw": "v1.3.0-rc.1", "major": 1, "minor": 3, "patch": 0, "prerelease": [ "rc", 1 ], "build": [], "version": "1.3.0-rc.1", "docsUrl": "http://code.angularjs.org/1.3.0-rc.1/docs" }, { "raw": "v1.3.0-rc.0", "major": 1, "minor": 3, "patch": 0, "prerelease": [ "rc", 0 ], "build": [], "version": "1.3.0-rc.0", "docsUrl": "http://code.angularjs.org/1.3.0-rc.0/docs" }, { "raw": "v1.3.0-beta.19", "major": 1, "minor": 3, "patch": 0, "prerelease": [ "beta", 19 ], "build": [], "version": "1.3.0-beta.19", "docsUrl": "http://code.angularjs.org/1.3.0-beta.19/docs" }, { "raw": "v1.3.0-beta.18", "major": 1, "minor": 3, "patch": 0, "prerelease": [ "beta", 18 ], "build": [], "version": "1.3.0-beta.18", "docsUrl": "http://code.angularjs.org/1.3.0-beta.18/docs" }, { "raw": "v1.3.0-beta.17", "major": 1, "minor": 3, "patch": 0, "prerelease": [ "beta", 17 ], "build": [], "version": "1.3.0-beta.17", "docsUrl": "http://code.angularjs.org/1.3.0-beta.17/docs" }, { "raw": "v1.3.0-beta.16", "major": 1, "minor": 3, "patch": 0, "prerelease": [ "beta", 16 ], "build": [], "version": "1.3.0-beta.16", "docsUrl": "http://code.angularjs.org/1.3.0-beta.16/docs" }, { "raw": "v1.3.0-beta.15", "major": 1, "minor": 3, "patch": 0, "prerelease": [ "beta", 15 ], "build": [], "version": "1.3.0-beta.15", "docsUrl": "http://code.angularjs.org/1.3.0-beta.15/docs" }, { "raw": "v1.3.0-beta.14", "major": 1, "minor": 3, "patch": 0, "prerelease": [ "beta", 14 ], "build": [], "version": "1.3.0-beta.14", "docsUrl": "http://code.angularjs.org/1.3.0-beta.14/docs" }, { "raw": "v1.3.0-beta.13", "major": 1, "minor": 3, "patch": 0, "prerelease": [ "beta", 13 ], "build": [], "version": "1.3.0-beta.13", "docsUrl": "http://code.angularjs.org/1.3.0-beta.13/docs" }, { "raw": "v1.3.0-beta.12", "major": 1, "minor": 3, "patch": 0, "prerelease": [ "beta", 12 ], "build": [], "version": "1.3.0-beta.12", "docsUrl": "http://code.angularjs.org/1.3.0-beta.12/docs" }, { "raw": "v1.3.0-beta.11", "major": 1, "minor": 3, "patch": 0, "prerelease": [ "beta", 11 ], "build": [], "version": "1.3.0-beta.11", "docsUrl": "http://code.angularjs.org/1.3.0-beta.11/docs" }, { "raw": "v1.3.0-beta.10", "major": 1, "minor": 3, "patch": 0, "prerelease": [ "beta", 10 ], "build": [], "version": "1.3.0-beta.10", "docsUrl": "http://code.angularjs.org/1.3.0-beta.10/docs" }, { "raw": "v1.3.0-beta.9", "major": 1, "minor": 3, "patch": 0, "prerelease": [ "beta", 9 ], "build": [], "version": "1.3.0-beta.9", "docsUrl": "http://code.angularjs.org/1.3.0-beta.9/docs" }, { "raw": "v1.3.0-beta.8", "major": 1, "minor": 3, "patch": 0, "prerelease": [ "beta", 8 ], "build": [], "version": "1.3.0-beta.8", "docsUrl": "http://code.angularjs.org/1.3.0-beta.8/docs" }, { "raw": "v1.3.0-beta.7", "major": 1, "minor": 3, "patch": 0, "prerelease": [ "beta", 7 ], "build": [], "version": "1.3.0-beta.7", "docsUrl": "http://code.angularjs.org/1.3.0-beta.7/docs" }, { "raw": "v1.3.0-beta.6", "major": 1, "minor": 3, "patch": 0, "prerelease": [ "beta", 6 ], "build": [], "version": "1.3.0-beta.6", "docsUrl": "http://code.angularjs.org/1.3.0-beta.6/docs" }, { "raw": "v1.3.0-beta.5", "major": 1, "minor": 3, "patch": 0, "prerelease": [ "beta", 5 ], "build": [], "version": "1.3.0-beta.5", "docsUrl": "http://code.angularjs.org/1.3.0-beta.5/docs" }, { "raw": "v1.3.0-beta.4", "major": 1, "minor": 3, "patch": 0, "prerelease": [ "beta", 4 ], "build": [], "version": "1.3.0-beta.4", "docsUrl": "http://code.angularjs.org/1.3.0-beta.4/docs" }, { "raw": "v1.3.0-beta.3", "major": 1, "minor": 3, "patch": 0, "prerelease": [ "beta", 3 ], "build": [], "version": "1.3.0-beta.3", "docsUrl": "http://code.angularjs.org/1.3.0-beta.3/docs" }, { "raw": "v1.3.0-beta.2", "major": 1, "minor": 3, "patch": 0, "prerelease": [ "beta", 2 ], "build": [], "version": "1.3.0-beta.2", "docsUrl": "http://code.angularjs.org/1.3.0-beta.2/docs" }, { "raw": "v1.3.0-beta.1", "major": 1, "minor": 3, "patch": 0, "prerelease": [ "beta", 1 ], "build": [], "version": "1.3.0-beta.1", "docsUrl": "http://code.angularjs.org/1.3.0-beta.1/docs" }, { "raw": "v1.2.29", "major": 1, "minor": 2, "patch": 29, "prerelease": [], "build": [], "version": "1.2.29", "docsUrl": "http://code.angularjs.org/1.2.29/docs" }, { "raw": "v1.2.28", "major": 1, "minor": 2, "patch": 28, "prerelease": [], "build": [], "version": "1.2.28", "docsUrl": "http://code.angularjs.org/1.2.28/docs" }, { "raw": "v1.2.27", "major": 1, "minor": 2, "patch": 27, "prerelease": [], "build": [], "version": "1.2.27", "docsUrl": "http://code.angularjs.org/1.2.27/docs" }, { "raw": "v1.2.26", "major": 1, "minor": 2, "patch": 26, "prerelease": [], "build": [], "version": "1.2.26", "docsUrl": "http://code.angularjs.org/1.2.26/docs" }, { "raw": "v1.2.25", "major": 1, "minor": 2, "patch": 25, "prerelease": [], "build": [], "version": "1.2.25", "docsUrl": "http://code.angularjs.org/1.2.25/docs" }, { "raw": "v1.2.24", "major": 1, "minor": 2, "patch": 24, "prerelease": [], "build": [], "version": "1.2.24", "docsUrl": "http://code.angularjs.org/1.2.24/docs" }, { "raw": "v1.2.23", "major": 1, "minor": 2, "patch": 23, "prerelease": [], "build": [], "version": "1.2.23", "docsUrl": "http://code.angularjs.org/1.2.23/docs" }, { "raw": "v1.2.22", "major": 1, "minor": 2, "patch": 22, "prerelease": [], "build": [], "version": "1.2.22", "docsUrl": "http://code.angularjs.org/1.2.22/docs" }, { "raw": "v1.2.21", "major": 1, "minor": 2, "patch": 21, "prerelease": [], "build": [], "version": "1.2.21", "docsUrl": "http://code.angularjs.org/1.2.21/docs" }, { "raw": "v1.2.20", "major": 1, "minor": 2, "patch": 20, "prerelease": [], "build": [], "version": "1.2.20", "docsUrl": "http://code.angularjs.org/1.2.20/docs" }, { "raw": "v1.2.19", "major": 1, "minor": 2, "patch": 19, "prerelease": [], "build": [], "version": "1.2.19", "docsUrl": "http://code.angularjs.org/1.2.19/docs" }, { "raw": "v1.2.18", "major": 1, "minor": 2, "patch": 18, "prerelease": [], "build": [], "version": "1.2.18", "docsUrl": "http://code.angularjs.org/1.2.18/docs" }, { "raw": "v1.2.17", "major": 1, "minor": 2, "patch": 17, "prerelease": [], "build": [], "version": "1.2.17", "docsUrl": "http://code.angularjs.org/1.2.17/docs" }, { "raw": "v1.2.16", "major": 1, "minor": 2, "patch": 16, "prerelease": [], "build": [], "version": "1.2.16", "docsUrl": "http://code.angularjs.org/1.2.16/docs" }, { "raw": "v1.2.15", "major": 1, "minor": 2, "patch": 15, "prerelease": [], "build": [], "version": "1.2.15", "docsUrl": "http://code.angularjs.org/1.2.15/docs" }, { "raw": "v1.2.14", "major": 1, "minor": 2, "patch": 14, "prerelease": [], "build": [], "version": "1.2.14", "docsUrl": "http://code.angularjs.org/1.2.14/docs" }, { "raw": "v1.2.13", "major": 1, "minor": 2, "patch": 13, "prerelease": [], "build": [], "version": "1.2.13", "docsUrl": "http://code.angularjs.org/1.2.13/docs" }, { "raw": "v1.2.12", "major": 1, "minor": 2, "patch": 12, "prerelease": [], "build": [], "version": "1.2.12", "docsUrl": "http://code.angularjs.org/1.2.12/docs" }, { "raw": "v1.2.11", "major": 1, "minor": 2, "patch": 11, "prerelease": [], "build": [], "version": "1.2.11", "docsUrl": "http://code.angularjs.org/1.2.11/docs" }, { "raw": "v1.2.10", "major": 1, "minor": 2, "patch": 10, "prerelease": [], "build": [], "version": "1.2.10", "docsUrl": "http://code.angularjs.org/1.2.10/docs" }, { "raw": "v1.2.9", "major": 1, "minor": 2, "patch": 9, "prerelease": [], "build": [], "version": "1.2.9", "docsUrl": "http://code.angularjs.org/1.2.9/docs" }, { "raw": "v1.2.8", "major": 1, "minor": 2, "patch": 8, "prerelease": [], "build": [], "version": "1.2.8", "docsUrl": "http://code.angularjs.org/1.2.8/docs" }, { "raw": "v1.2.7", "major": 1, "minor": 2, "patch": 7, "prerelease": [], "build": [], "version": "1.2.7", "docsUrl": "http://code.angularjs.org/1.2.7/docs" }, { "raw": "v1.2.6", "major": 1, "minor": 2, "patch": 6, "prerelease": [], "build": [], "version": "1.2.6", "docsUrl": "http://code.angularjs.org/1.2.6/docs" }, { "raw": "v1.2.5", "major": 1, "minor": 2, "patch": 5, "prerelease": [], "build": [], "version": "1.2.5", "docsUrl": "http://code.angularjs.org/1.2.5/docs" }, { "raw": "v1.2.4", "major": 1, "minor": 2, "patch": 4, "prerelease": [], "build": [], "version": "1.2.4", "docsUrl": "http://code.angularjs.org/1.2.4/docs" }, { "raw": "v1.2.3", "major": 1, "minor": 2, "patch": 3, "prerelease": [], "build": [], "version": "1.2.3", "docsUrl": "http://code.angularjs.org/1.2.3/docs" }, { "raw": "v1.2.2", "major": 1, "minor": 2, "patch": 2, "prerelease": [], "build": [], "version": "1.2.2", "docsUrl": "http://code.angularjs.org/1.2.2/docs" }, { "raw": "v1.2.1", "major": 1, "minor": 2, "patch": 1, "prerelease": [], "build": [], "version": "1.2.1", "docsUrl": "http://code.angularjs.org/1.2.1/docs" }, { "raw": "v1.2.0", "major": 1, "minor": 2, "patch": 0, "prerelease": [], "build": [], "version": "1.2.0", "docsUrl": "http://code.angularjs.org/1.2.0/docs" }, { "raw": "v1.2.0-rc.3", "major": 1, "minor": 2, "patch": 0, "prerelease": [ "rc", 3 ], "build": [], "version": "1.2.0-rc.3", "docsUrl": "http://code.angularjs.org/1.2.0-rc.3/docs" }, { "raw": "v1.2.0-rc.2", "major": 1, "minor": 2, "patch": 0, "prerelease": [ "rc", 2 ], "build": [], "version": "1.2.0-rc.2", "docsUrl": "http://code.angularjs.org/1.2.0-rc.2/docs" }, { "raw": "v1.1.5", "major": 1, "minor": 1, "patch": 5, "prerelease": [], "build": [], "version": "1.1.5", "docsUrl": "http://code.angularjs.org/1.1.5/docs" }, { "raw": "v1.1.4", "major": 1, "minor": 1, "patch": 4, "prerelease": [], "build": [], "version": "1.1.4", "docsUrl": "http://code.angularjs.org/1.1.4/docs" }, { "raw": "v1.1.3", "major": 1, "minor": 1, "patch": 3, "prerelease": [], "build": [], "version": "1.1.3", "docsUrl": "http://code.angularjs.org/1.1.3/docs" }, { "raw": "v1.1.2", "major": 1, "minor": 1, "patch": 2, "prerelease": [], "build": [], "version": "1.1.2", "docsUrl": "http://code.angularjs.org/1.1.2/docs" }, { "raw": "v1.1.1", "major": 1, "minor": 1, "patch": 1, "prerelease": [], "build": [], "version": "1.1.1", "docsUrl": "http://code.angularjs.org/1.1.1/docs" }, { "raw": "v1.1.0", "major": 1, "minor": 1, "patch": 0, "prerelease": [], "build": [], "version": "1.1.0", "docsUrl": "http://code.angularjs.org/1.1.0/docs" }, { "raw": "v1.0.8", "major": 1, "minor": 0, "patch": 8, "prerelease": [], "build": [], "version": "1.0.8", "docsUrl": "http://code.angularjs.org/1.0.8/docs" }, { "raw": "v1.0.7", "major": 1, "minor": 0, "patch": 7, "prerelease": [], "build": [], "version": "1.0.7", "docsUrl": "http://code.angularjs.org/1.0.7/docs" }, { "raw": "v1.0.6", "major": 1, "minor": 0, "patch": 6, "prerelease": [], "build": [], "version": "1.0.6", "docsUrl": "http://code.angularjs.org/1.0.6/docs" }, { "raw": "v1.0.5", "major": 1, "minor": 0, "patch": 5, "prerelease": [], "build": [], "version": "1.0.5", "docsUrl": "http://code.angularjs.org/1.0.5/docs" }, { "raw": "v1.0.4", "major": 1, "minor": 0, "patch": 4, "prerelease": [], "build": [], "version": "1.0.4", "docsUrl": "http://code.angularjs.org/1.0.4/docs" }, { "raw": "v1.0.3", "major": 1, "minor": 0, "patch": 3, "prerelease": [], "build": [], "version": "1.0.3", "docsUrl": "http://code.angularjs.org/1.0.3/docs" }, { "raw": "v1.0.2", "major": 1, "minor": 0, "patch": 2, "prerelease": [], "build": [], "version": "1.0.2", "docsUrl": "http://code.angularjs.org/1.0.2/docs" }, { "raw": "v1.0.1", "major": 1, "minor": 0, "patch": 1, "prerelease": [], "build": [], "version": "1.0.1", "docsUrl": "http://code.angularjs.org/1.0.1/docs-1.0.1", "isOldDocsUrl": true }, { "raw": "v1.0.0", "major": 1, "minor": 0, "patch": 0, "prerelease": [], "build": [], "version": "1.0.0", "docsUrl": "http://code.angularjs.org/1.0.0/docs-1.0.0", "isOldDocsUrl": true }, { "raw": "v1.0.0rc2", "major": 1, "minor": 0, "patch": 0, "prerelease": [ "rc2" ], "build": [], "version": "1.0.0rc2", "docsUrl": "http://code.angularjs.org/1.0.0rc2/docs-1.0.0rc2", "isOldDocsUrl": true } ]);
!function(){function t(t){return function(e,i){e=d3.hsl(e),i=d3.hsl(i);var r=(e.h+120)*a,h=(i.h+120)*a-r,s=e.s,l=i.s-s,o=e.l,u=i.l-o;return isNaN(l)&&(l=0,s=isNaN(s)?i.s:s),isNaN(h)&&(h=0,r=isNaN(r)?i.h:r),function(a){var e=r+h*a,i=Math.pow(o+u*a,t),c=(s+l*a)*i*(1-i);return"#"+n(i+c*(-.14861*Math.cos(e)+1.78277*Math.sin(e)))+n(i+c*(-.29227*Math.cos(e)-.90649*Math.sin(e)))+n(i+c*1.97294*Math.cos(e))}}}function n(t){var n=(t=0>=t?0:t>=1?255:0|255*t).toString(16);return 16>t?"0"+n:n}var a=Math.PI/180;d3.scale.cubehelix=function(){return d3.scale.linear().range([d3.hsl(300,.5,0),d3.hsl(-240,.5,1)]).interpolate(d3.interpolateCubehelix)},d3.interpolateCubehelix=t(1),d3.interpolateCubehelix.gamma=t}(); jQuery(function($) { "use strict"; var VerticalMarker = Rickshaw.Class.create({ initialize: function(args) { var graph = this.graph = args.graph; var element = this.element = document.createElement('div'); element.className = 'detail'; graph.element.appendChild(element); }, render: function(point) { var graph = this.graph; if (point) { this.element.innerHTML = ''; this.element.style.left = graph.x(point.x) + 'px'; } }, }); var Clrs = ["#fff7ec","#fc8d59","#ef6548","#d7301f","#b30000","#7f0000"]; Edgesense.Dashboard = function(){ var configuration = undefined, analytics = {track: function(){ console.log(['analytics.track', arguments]); }}, base_url = undefined, file = undefined, data = undefined, slider_date_format = function(date, from_time, to_time) { var _cache = {}; var from_ts = d3.round(from_time.getTime()/1000); var to_ts = d3.round(to_time.getTime()/1000); var ts_key = from_ts+" "+to_ts; if (!_cache[ts_key]) { _cache[ts_key] = d3.time.format.multi([ ["%B %e, %Y", function(d) { return from_time.getFullYear() != to_time.getFullYear(); }], ["%B %e", function(d) { return from_time.getMonth() != to_time.getMonth() || ((to_time.getTime() - from_time.getTime()) > 7*24*60*60*1000); }], ["%B %e - %H:%M", function(d) { return from_time.getDay() != to_time.getDay(); }], ["%H:%M", function(d) { return true; }] ]); } return _cache[ts_key](date); // d3.time.format('%B %d, %Y'); }, chart_date_format = function(date, from_time, to_time) { var _cache = {}; var from_ts = d3.round(from_time.getTime()/1000); var to_ts = d3.round(to_time.getTime()/1000); var ts_key = from_ts+" "+to_ts; if (!_cache[ts_key]) { _cache[ts_key] = d3.time.format.multi([ [" %e/%m", function(d) { return (from_time.getMonth() != to_time.getMonth()) || (from_time.getFullYear() != to_time.getFullYear()); }], [" %e/%m", function(d) { return ((to_time.getTime() - from_time.getTime()) > 2*24*60*60*1000); }], [" %H:%M", function(d) { return true; }] ]); } return _cache[ts_key](date); // d3.time.format(' %e/%m'); }, track_date_format = d3.time.format('%Y/%m/%d %H:%M'), color_scale = d3.scale.cubehelix() .domain([0, .5, 1]) .range([ d3.hsl(-100, 0.75, 0.35), d3.hsl( 80, 1.50, 0.80), d3.hsl( 260, 0.75, 0.35) ]), //d3.scale.category20(), generated = undefined, metrics_cf = undefined, metrics_bydate = undefined, nodes_cf = undefined, nodes_bydate = undefined, edges_cf = undefined, edges_bydate = undefined, from_date = undefined, to_date = undefined, graphs = {}, current_metrics = undefined, first_metrics = undefined, last_metrics = undefined, partitions_count = undefined, network_graph = undefined, nodes_map = {}, to_expose = undefined, network_lock = undefined, node_fill_transparent = 'rgba(204,204,204,0.1)', edge_transparent = 'rgba(204,204,204,0.1)', edge_min_opacity = 0.05, edge_max_opacity = 1, opacity_scale = d3.scale.linear(), null_opacity_scale = function(e){ return 1; }, max_age = undefined, show_undirected = false, color_by = undefined, node_border_default = 'rgb(15, 15, 15)', // Similar to the background color node_border_transparent = 'rgba(240, 240, 240, 0.1)', node_fill_isolated = 'rgba(160,160,160,0.2)', node_border_isolated = 'rgb(250,250,250)', node_fill_team = 'rgb(255, 255, 255)', degree_extent = [], degree_scale = d3.scale.linear().domain(d3.range(0, 1, 1.0 / (Clrs.length - 1))).range(Clrs), betweenness_extent = [], betweenness_scale = d3.scale.linear().domain(d3.range(0, 1, 1.0 / (Clrs.length - 1))).range(Clrs), selected_partitions = [], current_user_filter = '', show_moderators = true, show_datapackage = false, names_map = {}, mapped_name = function(name){ // map names if the names_map is defined if (_.isObject(names_map) && _.has(names_map, name)){ return names_map[name]; } return name; }, preprocess_data = function(d){ data = d; if (data['meta'] && data['meta']['generated']) { data['meta']['generated'] = new Date(data['meta']['generated']*1000); } _.each(data['metrics'], function(e){ e['date'] = new Date(e['ts']*1000); }); _.each(data['nodes'], function(e){ e['date'] = new Date(e['created_ts']*1000); e['name'] = mapped_name(e['name']); }); _.each(data['edges'], function(e){ e['date'] = new Date(e['ts']*1000); }); }, update_filter = function(i){ current_metrics = data['metrics'][i]; metrics_bydate.filter([0, current_metrics.date]); // Update each metrics _.each($('.metric'), update_metric); // Update the markers _.each(graphs, update_marker); // Update the graph if (!network_graph) { return; } // filter the edges and nodes nodes_bydate.filter([0, current_metrics.date]); edges_bydate.filter([0, current_metrics.date]); update_network_graph(); }, toggle_partition = function(b){ var shown = 0; if (_.indexOf(selected_partitions, b.data('partition'))>=0) { selected_partitions = _.without(selected_partitions, b.data('partition')) b.find('.fa').removeClass('fa-check-square-o').addClass('fa-square-o'); } else { selected_partitions.push(b.data('partition')) b.find('.fa').removeClass('fa-square-o').addClass('fa-check-square-o'); shown = 1; } update_network_graph(); analytics.track('filter', 'toggle_partition', 'part #'+b.data('partition'), shown); }, update_network_graph = function(){ close_node_popover(); network_graph.graph.clear(); network_graph.graph.read(filtered_graph()); update_hidden(); update_exposed(); network_graph.refresh(); }, update_hidden = function(){ _.each(network_graph.graph.nodes(), function(n){ var partition = last_metrics.partitions[n.id]; var to_hide = _.indexOf(selected_partitions, partition)<0 && !n.isolated; if (n.team) { to_hide = to_hide || !show_moderators; } n.hidden = to_hide; }); network_graph.refresh(); }, update_exposed = function(){ network_graph.graph.nodes().forEach(function(n) { if (!to_expose || to_expose[n.id]) { n.color = node_fill_color(n,opacity_scale(n.weight)); n.border_color = node_border_color(n,opacity_scale(n.weight)); } else { n.color = node_fill_transparent; n.border_color = node_border_transparent; } }); network_graph.graph.edges().forEach(function(e) { if (!to_expose) { e.color = edge_color(e,opacity_scale(e.weight)); } else if (to_expose[e.source] && to_expose[e.target]) { e.color = edge_color(e); } else { e.color = edge_transparent; } }); }, close_node_popover = function(){ $('#node-marker').hide(); $('#node-marker').popover('destroy'); }, open_node_popover = function(node){ var left = node['renderer1:x']; var top = node['renderer1:y']; $('#node-marker').popover('destroy'); $('#node-marker').show(); $('#node-marker').css('left', (left) + 'px'); $('#node-marker').css('top', (top) + 'px'); $('#node-marker').popover({ container: 'body', html: true, placement: 'auto right', content: node_popover_content(node) }); $('#node-marker').popover('show'); }, node_popover_content = function(node){ var in_degree = current_metrics[metric_name_prefixed('in_degree')][node.id]; var out_degree = current_metrics[metric_name_prefixed('out_degree')][node.id]; var betweenness = current_metrics[metric_name_prefixed('betweenness')][node.id]; var cont_div = $('<div class="node-hover-content"><div class="node-hover-title"></div><ul class="node-hover-data"></ul></div>'); if ( nodes_map[node.id].link ) { var nodelink = $('<a>'). attr('href', nodes_map[node.id].link). attr('target', "_blank"). html(node.name); cont_div.children('.node-hover-title').append(nodelink); } else { cont_div.children('.node-hover-title').html(node.name); } cont_div.children('ul').append('<li><span>In degree:</span> '+in_degree+'</li>'); cont_div.children('ul').append('<li><span>Out degree:</span> '+out_degree+'</li>'); cont_div.children('ul').append('<li><span>Betweenness:</span> '+d3.round(betweenness, 4)+'</li>'); return cont_div.html(); }, filtered_graph = function(){ // merge multiedges var node_weights = {}, edges_map = {}, edges_tss = _.map(edges_bydate.top(Infinity), function(e) { return e.ts; }), first_edge_ts = d3.min(edges_tss), last_edge_ts = d3.max(edges_tss), range_edge_ts = last_edge_ts - first_edge_ts; degree_extent = d3.extent(_.values(current_metrics[metric_name_prefixed('degree')])); degree_scale = d3.scale.linear().domain(d3.extent(degree_extent)); degree_scale.domain(d3.range(0, 1, 1.0 / (Clrs.length - 1)).map(degree_scale.invert)); degree_scale.range(Clrs); betweenness_extent = d3.extent(_.values(current_metrics[metric_name_prefixed('betweenness')])); betweenness_scale = d3.scale.linear().domain(d3.extent(betweenness_extent)); betweenness_scale.domain(d3.range(0, 1, 1.0 / (Clrs.length - 1)).map(betweenness_scale.invert)); betweenness_scale.range(Clrs); _.each(edges_bydate.top(Infinity), function(edge){ var edge_id = edge.source+"_"+edge.target; // Reverse edge id var merged_edge = edges_map[edge_id]; if (!merged_edge && show_undirected) { // Reverse and direct edges are equal if unidirected var rev_edge_id = edge.target+"_"+edge.source; // Reverse edge id merged_edge = edges_map[rev_edge_id]; // Reverse and direct edges are equal } if (edge.source != edge.target) { // Remove self edge if(!merged_edge) { merged_edge = { id: edge_id, source: edge.source, target: edge.target, weight: 0, type: 'curve' // No color, it depends to weight } edges_map[edge_id] = merged_edge; } if (max_age) { var age_edge = max_age+edge.ts-last_edge_ts; merged_edge['weight'] = d3.max([age_edge, merged_edge['weight']]); node_weights[edge.source] = d3.max([node_weights[edge.source]||0, merged_edge['weight']]); node_weights[edge.target] = d3.max([node_weights[edge.target]||0, merged_edge['weight']]); } } }); var edges_values = _.values(edges_map), // Array of edges objects edges_weights = _.map(edges_values, function(e) { return e.weight; }); // Array of edges weights opacity_scale = max_age ? d3.scale.linear().range([edge_min_opacity,edge_max_opacity]).domain(d3.extent(edges_weights)) : null_opacity_scale ; _.each(edges_values, function(e) { // Setting edges color e.color = edge_color(e,opacity_scale(e.weight)); }); var G = {}; G['nodes'] = _.map(nodes_bydate.top(Infinity), function(node){ var size = node.size ? node.size : 1; return { id: node.id, // label: "", name: node.name, // Display attributes: x: node.x, y: node.y, size: size, color: node_fill_color(node,opacity_scale(node_weights[node.id])), type: 'border', border_color: node_border_color(node,opacity_scale(node_weights[node.id])), team: node.team, isolated: node.isolated, weight: node_weights[node.id], ts: node.created_ts, date: node.date, link: node.link }; }); G['edges'] = _.sortBy(edges_values,'weight'); // From lighter to heavier edge (maybe useful for z-index) return G }, metric_name_prefixed = function(metric_name){ if (show_moderators) { return 'full:'+metric_name; } else { return 'user:'+metric_name; } }, update_metric = function(e){ var metric_name = metric_name_prefixed($(e).data('metric-name')); var rounding = $(e).data('metric-round'); if (!rounding) { rounding = 4; } var value = d3.round(current_metrics[metric_name], rounding); $(e).find('.value').html(value); var chart_obj = graphs[metric_name]; if (chart_obj) { // chart.series[0].data=metric_series(metric_name); chart_obj.chart.series[1].data=[{x:current_metrics['ts'],y:current_metrics[metric_name]}]; chart_obj.chart.update(); } }, update_marker = function(chart_obj) { if (chart_obj.marker) { chart_obj.marker.render({x:current_metrics['ts']}); } }, metric_series = function(metric_name){ var metric_values = _.map(metrics_bydate.top(Infinity), function(m){ return { x: m['ts'], y: m[metric_name] } }); metric_values = _.sortBy(metric_values, function(e){ return e.x; } ) return metric_values; }, build_graph = function(e){ var minichart = $(e).find('.minichart')[0]; if (!minichart) { return; } var metric_name = metric_name_prefixed($(e).data('metric-name')); var complete_metric = global_metric_series(metric_name); var max_metric_value = _.max(complete_metric, function(e){ return e.y!=undefined ? e.y : 0; } ).y; var min_metric_value = _.min(complete_metric, function(e){ return e.y!=undefined ? e.y : max_metric_value; } ).y; var chart = new Rickshaw.Graph( { element: minichart, renderer: 'multi', interpolation: 'linear', width: $(minichart).width(), height: 73, dotSize: 4, max: max_metric_value+(max_metric_value*0.05), min: min_metric_value-(min_metric_value*0.05), padding: { top: 0.06, right: 0.06, bottom: 0.06, left: 0.02 }, series: [{ color: metric_color(metric_name), data: global_metric_series(metric_name), renderer: 'line' },{ color: metric_color(metric_name), data: [{x:current_metrics['ts'],y:current_metrics[metric_name]}], renderer: 'scatterplot' }] }); chart.render(); var from_ts = from_date.getTime()/1000;//ts here are in mill var to_ts = to_date.getTime()/1000; var unit = { name: 'week', seconds: (to_ts-from_ts)/6, formatter: function(d) { return chart_date_format(d, from_date, to_date); } }; var axes = new Rickshaw.Graph.Axis.Time( { graph: chart, timeUnit: unit } ); axes.render(); graphs[metric_name] = {chart: chart}; }, metric_color = function(metric_name) { var regex = /(.+):(.+)/i; var match = regex.exec(metric_name); var color_map = { full:'rgb(255, 127, 0)', team:'rgb(30, 250, 255)', user:'rgb(255, 255, 51)', nodes_count: '#2ca02c', edges_count: '#d62728', avg_distance: '#aec7e8', louvain_modularity: '#e7ba52', ts_posts_share: '#ff7f00', ts_comments_share: '#377eb8', }; var color = undefined; if (!color){ color = color_map[match[2]]; } if (!color){ color = color_map[match[1]]; } if (!color){ color = color_map[metric_name]; } if (!color){ color = 'rgb(250, 250, 250)'; } return color; }, global_metric_series = function(metric_name){ var metric_values = _.map(data['metrics'], function(m){ return { x: m['ts'], y: m[metric_name] } }); metric_values = _.sortBy(metric_values, function(e){ return e.x; } ) return metric_values; }, build_multi_graph = function(e){ var metric_names = $(e).data('metric-name').split(","); var metric_labels = $(e).data('metric-legend').split(","); var metric_colors = [] if ($(e).data('metric-colors')) { metric_colors = $(e).data('metric-colors').split(",");} var series = []; _.each(metric_names, function(metric_name, idx){ var metric_series = global_metric_series(metric_name); var color = metric_colors[idx]||metric_color(metric_name); series.push({ color: color, data: metric_series, name: metric_labels[idx] }) }) var series_values = _.flatten(_.map(series, function(e){ return _.map(e.data, function(j){ return j.y; });})); var max_metric_value = _.max(series_values); var min_metric_value = _.min(series_values); var outer_container = $(e).find('.chart-cnt'); var base_size = (outer_container.width()*9.5/10.0)-20; outer_container.height(base_size).html('<div class="y_ax"></div><div class="chart"></div>'); var graph_container = outer_container.find('.chart').width(base_size-10).height(base_size)[0]; var y_axis_container = outer_container.find('.y_ax').width(30).height(base_size)[0]; var chart = new Rickshaw.Graph( { element: graph_container, renderer: 'line', height: base_size-18, max: max_metric_value+(max_metric_value*0.08), min: min_metric_value-(min_metric_value*0.08), padding: { top: 0.015, right: 0.015, bottom: 0.02, left: 0.015 }, interpolation: 'linear', series: series }); var x_axis = new Rickshaw.Graph.Axis.Time( { graph: chart, orientation: 'bottom' } ); var y_axis = new Rickshaw.Graph.Axis.Y( { graph: chart, orientation: 'left', tickFormat: Rickshaw.Fixtures.Number.formatKMBT, element: y_axis_container, } ); var legend = $(e).find('.chart-legend'); _.each(metric_names, function(metric_name, idx){ var color = metric_colors[idx]||metric_color(metric_name); legend.append('<span style="color:'+color+';"><i class="fa fa-circle"></i>&nbsp;'+metric_labels[idx]+'</span>') }) var marker = new VerticalMarker({ graph: chart }); chart.render(); marker.render({x:current_metrics['ts']}); graphs[$(e).data('metric-name')] = {chart:chart, marker:marker}; }, circularize = function(nodes) { var R = 2000, i = 0, L = nodes.length; _.each(nodes, function(n){ n.x = Math.cos(Math.PI*(i++)/L)*R; n.y = Math.sin(Math.PI*(i++)/L)*R; }) }, toggle_lock = function(event) { var mouse_enabled = network_graph.settings('mouseEnabled'); network_graph.settings('mouseEnabled', !mouse_enabled) var touch_enabled = network_graph.settings('touchEnabled'); network_graph.settings('touchEnabled', !touch_enabled); if (mouse_enabled) { network_lock.find('.fa').removeClass('fa-unlock').addClass('fa-lock'); } else { network_lock.find('.fa').removeClass('fa-lock').addClass('fa-unlock'); } analytics.track('control', 'toggle_lock', mouse_enabled); }, toggle_team = function(show){ show_moderators = show; // Update each metrics _.each($('.metric'), update_metric); // Update the network update_network_graph(); network_graph.refresh(); analytics.track('filter', 'toggle_team', show_moderators); }, is_isolated = function(node){ }, node_fill_color = function(node,opacity){ var com = last_metrics.partitions[node.id]/(partitions_count+1), // Category by partition exa = node.team ? node_fill_team : color_scale(com); // Category color in ex format (string, eg. #ffffff) if (node.isolated) { return node_fill_isolated; } if (color_by=='degree') { exa = degree_scale(current_metrics[metric_name_prefixed('degree')][node.id]); } if (color_by=='betweenness') { exa = betweenness_scale(current_metrics[metric_name_prefixed('betweenness')][node.id]); } var rgb = d3.rgb(exa); // Category color in rgb format (object) // If opacity, color is a string in rgba format, alse it's in ex format return opacity ? 'rgba('+rgb.r+','+rgb.g+','+rgb.b+','+opacity+')' : exa; }, node_border_color = function(node,opacity){ var rgb = d3.rgb(node_border_default); // color in rgb format (object) if (node.isolated) { return node_fill_isolated; } return opacity ? 'rgba('+rgb.r+','+rgb.g+','+rgb.b+','+opacity+')' : node_border_default; }, edge_color = function(edge,opacity){ var com = last_metrics.partitions[edge.source]/(partitions_count+1), // Category by partition exa = color_scale(com), // Category color in ex format (string, eg. #ffffff) rgb = d3.rgb(exa); // Category color in rgb format (object) if (color_by=='degree' || color_by=='betweenness') { return edge_transparent; } // If opacity, color is a string in rgba format, alse it's in ex format return opacity ? 'rgba('+rgb.r+','+rgb.g+','+rgb.b+','+opacity+')' : exa; }, search_node = function(node_id_or_name){ var re = RegExp("^"+node_id_or_name+"$", 'i'); return _.find( network_graph.graph.nodes(), function(n){ return n.id === node_id_or_name || n.name.match(re); }); }, expose_node = function(node){ to_expose = network_graph.graph.neighbors(node.id); to_expose[node.id] = node; update_exposed(); network_graph.refresh(); }, search_and_expose = function(node_id_or_name){ if (node_id_or_name!='') { var node = search_node(node_id_or_name); if (node) { zoom_to_node(node); expose_node(node); } } else { close_node_popover(); unexpose_node(); } }, unexpose_node = function(){ to_expose = undefined; $('#node-marker').hide(); $('#node-marker').popover('destroy'); reset_zoom(); update_exposed(); network_graph.refresh(); }, zoom_to_node = function(node) { close_node_popover(); sigma.misc.animation.camera( network_graph.camera, { x: node[network_graph.camera.readPrefix + 'x'], y: node[network_graph.camera.readPrefix + 'y'], ratio: 0.33 }, { duration: network_graph.settings('animationsTime') || 300, onComplete: function() { open_node_popover(node); } } ); }, reset_zoom = function() { close_node_popover(); sigma.misc.animation.camera( network_graph.camera, { x: 0, y: 0, ratio: 1 }, { duration: network_graph.settings('animationsTime') || 300 } ); }; function db(){ }; db.configuration = function(new_configuration){ if (!arguments.length) return configuration; configuration = new_configuration; return db; }; db.base = function(url){ if (!arguments.length) return base_url; base_url = url; return db; }; db.names_map = function(map) { if (!arguments.length) return names_map; names_map = map; return db; }; db.load = function(filename){ if (!arguments.length) return file; file = filename; $.ajax({ dataType: "json", async: false, url: base_url+"/"+file, success: preprocess_data }); return db; }; db.show_datapackage = function(do_show){ if (!arguments.length) return show_datapackage; show_datapackage = !!do_show; return db; }; db.slider_date_format = function(format){ if (_.isFunction(format)) { slider_date_format = format; } else { slider_date_format = d3.time.format(format); } return db; }; db.chart_date_format = function(format){ if (_.isFunction(format)) { chart_date_format = format; } else { chart_date_format = d3.time.format(format); } return db; }; db.track_date_format = function(format){ if (_.isFunction(format)) { track_date_format = format; } else { track_date_format = d3.time.format(format); } }; db.analytics = function(analytics_object){ if (!arguments.length) return analytics; analytics = analytics_object; return db; }; db.data = function(){ return data; }; db.network_graph = function(){ return network_graph; }; db.current_metrics = function(){ return current_metrics; }; db.close_node_popover = function(){ close_node_popover(); }; db.open_node_popover = function(){ open_node_popover(); }; db.search = function(node_id_or_name){ return search_node(node_id_or_name); }; db.expose = function(node){ expose_node(node); }; db.search_and_expose = function(node_id_or_name){ search_and_expose(node_id_or_name); }; db.toggle_team = function(show){ toggle_team(show); }; db.run = function(){ $('#dashboard-controls').fadeIn(); // Show the title var dashboard_name = configuration.get("dashboard_name"); if (dashboard_name) { $('#dashboard-title').html(dashboard_name); document.title = dashboard_name+" | dashboard" } // Show the date when it was generated if ( data && data['meta'] && data['meta']['generated']) { var format = d3.time.format('%B %d, %Y - %H:%M:%S'); $("#generated-ts").html(format(data['meta']['generated'])); // Check if the data is too old var now = new Date(); var diff = now.getTime() - data['meta']['generated'].getTime(); if (diff > 24*60*60*1000) { //at most it should be 1 day old $("body").prepend("<div id=\"max-age-message\">Attention: the data presented is older than 24 hours.</div>"); $("<a>"). on('click', function(){$('#max-age-message').hide();}). html('<i class="glyphicon glyphicon-remove-circle"></i>'). appendTo('#max-age-message'); } } // create the metrics crossfilter metrics_cf = crossfilter(data['metrics']); metrics_bydate = metrics_cf.dimension(function(m) { return m.date; }); from_date = metrics_bydate.bottom(1)[0].date; to_date = metrics_bydate.top(1)[0].date; var all_dates = _.map(data['metrics'], function(e){ return slider_date_format(e.date, from_date, to_date); }); $("#date_range").ionRangeSlider({ type: "single", values: all_dates, from: all_dates.length-1, hasGrid: true, onFinish: function(i){ update_filter(i.fromNumber); analytics.track('filter', 'date_range', track_date_format(current_metrics.date, from_date, to_date)); } //onChange }); update_filter(all_dates.length-1); _.each($('.metric'), build_graph); _.each($('.multi-metric'), build_multi_graph); // create the graph crossfilters nodes_cf = crossfilter(data['nodes']); nodes_bydate = nodes_cf.dimension(function(n) { return n.date; }); edges_cf = crossfilter(data['edges']); edges_bydate = edges_cf.dimension(function(e) { return e.date; }); // build the network graph last_metrics = metrics_bydate.top(1)[0]; selected_partitions = _.uniq(_.values(last_metrics.partitions)).sort(); partitions_count = _.max(_.values(last_metrics.partitions)); var filter = $('#network-filter'); _.each(selected_partitions, function(part){ filter .append('<button class="filter-btn btn btn-sm" style="background-color:'+color_scale(part/(partitions_count+1))+'" data-partition="'+part+'"><i class="fa fa-check-square-o"></button>'); }); $('#filter-button').on('click', function(){ _.each($('.filter-btn'), function(b){ b = $(b); if (_.indexOf(selected_partitions, b.data('partition'))>=0) { b.find('.fa').removeClass('fa-square-o').addClass('fa-check-square-o'); } else { b.find('.fa').removeClass('fa-check-square-o').addClass('fa-square-o'); } b.on('click', function(e){ var b = $(this); toggle_partition(b); }); }) _.each($('.filter-clear-btn'), function(b){ $(b).on('click', function(e){ _.each($(this).closest('.network-filter-cnt').find('.filter-btn'), function(b){ b = $(b); if (!(_.indexOf(selected_partitions, b.data('partition'))>=0)) { selected_partitions.push(b.data('partition')); b.find('.fa').removeClass('fa-square-o').addClass('fa-check-square-o'); } }) update_network_graph(); analytics.track('filter', 'toggle_partition', 'all part', 1); e.preventDefault(); }); }) }) // Setup datapackage save if (show_datapackage) { $('#datapackage-save').on('click', function(e){ try { window.location = base_url+'../../../datapackage.json'; } catch(exc){ console.log(exc); } e.preventDefault(); }) $('#gexf-save').on('click', function(e){ try { window.location = base_url+'/network.gexf'; } catch(exc){ console.log(exc); } e.preventDefault(); }) } else { $('#datapackage').html(''); } $('#params-button').on('click', function(e){ $(this).closest('.network-params').find('.unidirected-field').on('click', function(e){ $(this).iCheck('toggle'); }) _.each($('.apply-params-btn'), function(b){ $(b).on('click', function(e){ var max_age_filter = $(this).closest('.network-params').find('.max-age-field').val(); max_age = /^\d+$/.test(max_age_filter) ? (+max_age_filter)*24*60*60 : undefined; var undirected_filter = $(this).closest('.network-params').find('.unidirected-field').val(); show_undirected = undirected_filter=='yes'; color_by = $(this).closest('.network-params').find('.color-nodes-field').val(); // update network update_network_graph(); network_graph.refresh(); e.preventDefault(); }); }) _.each($('.apply-params-clear-btn'), function(b){ $(b).on('click', function(e){ $(this).closest('.network-params').find('.max-age-field').val(''); max_age = undefined; $(this).closest('.network-params').find('.unidirected-field').val(''); show_undirected = false; $(this).closest('.network-params').find('.color-nodes-field').val(''); color_by = undefined; // update network update_network_graph(); network_graph.refresh(); e.preventDefault(); }); }) }); $('#search-button').on('click', function(e){ $('.user-search').find('input').val(current_user_filter); _.each($('.user-search-btn'), function(b){ $(b).on('click', function(e){ current_user_filter = $(this).closest('.user-search').find('input').val(); if (search_and_expose(current_user_filter)) { $(".ac-users .ac-helper span").html(''); } else { $(".ac-users .ac-helper span").html('No search results.'); } e.preventDefault(); }); }) _.each($('.user-search-clear-btn'), function(b){ $(b).on('click', function(e){ $(this).closest('.user-search').find('input').val(''); unexpose_node(); $(".ac-users .ac-helper span").html(''); e.preventDefault(); }); }) }); $('#search-button').on('shown.bs.popover', function() { $("body > .popover .user-search input").autocomplete({ source: _.map(data['nodes'], function(n) { return n['name']; }), minLength: 2, create: function(e,ui) { $('.ac-users .ac-content').html($('ul.ui-autocomplete').removeAttr('style')).show(); $('.ac-users .ac-helper').html($('span.ui-helper-hidden-accessible').removeAttr('style')).show(); }, open: function(e,ui) { $(".ac-users .ac-content ul").removeAttr('style'); $(".ac-users .ac-helper").removeAttr('style'); }, select: function(e,ui) { search_and_expose(ui.item.label); $(".ac-users .ac-helper span").html(''); } }); }); nodes_map = {} _.each(data['nodes'], function(node){ nodes_map[node.id] = node; }); var initial_graph = filtered_graph(); var isolated_nodes = _.where(initial_graph['nodes'], {isolated: true}); initial_graph['nodes'] = _.reject(initial_graph['nodes'], function(n){ return n.isolated }); circularize(_.sortBy(initial_graph['nodes'], function(node){ return last_metrics.partitions[node.id]; })); network_graph = new sigma({ graph: initial_graph, renderer: { container: document.getElementById('network'), type: 'canvas' } }); network_graph.settings({ sideMargin: 8, defaultLabelSize: 12, labelThreshold: 30, maxNodeSize: 3, defaultEdgeType:'curve', mouseEnabled: false, touchEnabled: false, doubleClickEnabled: false, labelHoverShadow: false }) network_graph.bind('doubleClickNode', function(e) { expose_node(e.data.node); }); network_graph.bind('doubleClickStage', function(e) { unexpose_node(); }); network_graph.bind('clickNode', function(e) { var offset = $(this).offset(); open_node_popover(e.data.node); }); network_graph.bind('clickStage', close_node_popover); network_graph.refresh(); $('#network').hide(); network_graph.startForceAtlas2({ linLogMode: false, outboundAttractionDistribution: false, adjustSize: false, adjustSizes: false, edgeWeightInfluence: 0, scalingRatio: 9000, strongGravityMode: false, gravity: 2000, slowDown: 1 }); setTimeout(function(){ network_graph.stopForceAtlas2(); // saving the computed positions _.each(network_graph.graph.nodes(), function(n){ var node = nodes_map[n.id]; if (node) { node.x = n.x; node.y = n.y; } }) // re-add the isolated nodes // we put them on the bottom side evenly distributed if (isolated_nodes) { // Find the max and min x & y of the nodes var max_x = _.max(network_graph.graph.nodes(), function(n){ return n.x; }).x; var max_y = _.max(network_graph.graph.nodes(), function(n){ return n.y; }).y; var min_x = _.min(network_graph.graph.nodes(), function(n){ return n.x; }).x; var min_y = _.min(network_graph.graph.nodes(), function(n){ return n.y; }).y; var origin_x = Math.floor(min_x); var origin_y = Math.floor(max_y*1.03); var step = Math.floor(Math.abs(max_x-min_x)/isolated_nodes.length+2); var index = 1 _.each(isolated_nodes, function(n){ var node = nodes_map[n.id]; if (node) { node.x = n.x = Math.floor(origin_x+(index*step)); node.y = n.y = origin_y; network_graph.graph.addNode(n); index += 1; } }); network_graph.refresh(); } $('#network-container .box-tools').show(); }, 10000); $('#network').fadeIn(); // setup network controls network_lock = $('#network-lock'); network_lock.click(toggle_lock); $('#moderators-check').on('ifChanged', function(e){ toggle_team($(this).prop('checked')); }); window.network_lock = network_lock; return db; }; return db; }; });
const commonConfig = require('./webpack.common.conf'); const webpackMerge = require('webpack-merge'); // used to merge webpack configs // tools const ip = require('ip').address(); const os = require('os'); const chalk = require('chalk'); const path = require('path'); const webpack = require('webpack'); const helper = require('./helper'); const config = require('./config'); console.log(`${chalk.green(`Package web project at ${chalk.bold(path.resolve('./release/web'))}!`)}`) /** * Webpack Plugins */ const UglifyJsparallelPlugin = require('webpack-uglify-parallel'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin'); /** * Generate multiple entrys * @param {Array} entry */ const generateMultipleEntrys = (entry) => { let entrys = Object.keys(entry); // exclude vendor entry. entrys = entrys.filter(entry => entry !== 'vendor' ); const htmlPlugin = entrys.map(name => { return new HtmlWebpackPlugin({ filename: name + '.html', template: helper.rootNode(`web/index.html`), isDevServer: true, chunksSortMode: 'dependency', inject: true, chunks: [name], // production minimize: true }) }) return htmlPlugin; } /** * Webpack configuration for web. */ const productionConfig = webpackMerge(commonConfig[0], { /** * Developer tool to enhance debugging * * See: http://webpack.github.io/docs/configuration.html#devtool * See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps */ devtool: config.prod.devtool, /** * Options affecting the output of the compilation. * * See: http://webpack.github.io/docs/configuration.html#output */ output: { /** * The output directory as absolute path (required). * * See: http://webpack.github.io/docs/configuration.html#output-path */ path: helper.rootNode('release/web'), /** * Specifies the name of each output file on disk. * IMPORTANT: You must not specify an absolute path here! * * See: http://webpack.github.io/docs/configuration.html#output-filename */ filename: '[name].[chunkhash].bundle.js', /** * The filename of the SourceMaps for the JavaScript files. * They are inside the output.path directory. * * See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename */ sourceMapFilename: '[name].[chunkhash].bundle.map', /** * The filename of non-entry chunks as relative path * inside the output.path directory. * * See: http://webpack.github.io/docs/configuration.html#output-chunkfilename */ chunkFilename: '[id].[chunkhash].chunk.js' }, /* * Add additional plugins to the compiler. * * See: http://webpack.github.io/docs/configuration.html#plugins */ plugins: [ /** * Plugin: webpack.DefinePlugin * Description: The DefinePlugin allows you to create global constants which can be configured at compile time. * * See: https://webpack.js.org/plugins/define-plugin/ */ new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': config.prod.env } }), /* * Plugin: UglifyJsPlugin * Description: Minimize all JavaScript output of chunks. * Loaders are switched into minimizing mode. * * See: https://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin */ ...generateMultipleEntrys(commonConfig[0].entry), /* * Plugin: HtmlWebpackPlugin * Description: Simplifies creation of HTML files to serve your webpack bundles. * This is especially useful for webpack bundles that include a hash in the filename * which changes every compilation. * * See: https://github.com/ampedandwired/html-webpack-plugin */ new HtmlWebpackPlugin({ template: 'web/index.html', chunksSortMode: 'dependency', inject: 'head' }), /* * Plugin: ScriptExtHtmlWebpackPlugin * Description: Enhances html-webpack-plugin functionality * with different deployment options for your scripts including: * * See: https://github.com/numical/script-ext-html-webpack-plugin */ new ScriptExtHtmlWebpackPlugin({ defaultAttribute: 'defer' }), /* * Plugin: UglifyJsparallelPlugin * Description: Identical to standard uglify webpack plugin * with an option to build multiple files in parallel * * See: https://www.npmjs.com/package/webpack-uglify-parallel */ new UglifyJsparallelPlugin({ workers: os.cpus().length, mangle: true, compressor: { warnings: false, drop_console: true, drop_debugger: true } }) ] }); /** * Webpack configuration for weex. */ const weexConfig = webpackMerge(commonConfig[1], { /** * Options affecting the output of the compilation. * * See: http://webpack.github.io/docs/configuration.html#output */ output: { /** * The output directory as absolute path (required). * * See: http://webpack.github.io/docs/configuration.html#output-path */ path: helper.rootNode('dist'), /** * Specifies the name of each output file on disk. * IMPORTANT: You must not specify an absolute path here! * * See: http://webpack.github.io/docs/configuration.html#output-filename */ filename: '[name].js' }, /* * Add additional plugins to the compiler. * * See: http://webpack.github.io/docs/configuration.html#plugins */ plugins: [ /* * Plugin: UglifyJsparallelPlugin * Description: Identical to standard uglify webpack plugin * with an option to build multiple files in parallel * * See: https://www.npmjs.com/package/webpack-uglify-parallel */ new UglifyJsparallelPlugin({ workers: os.cpus().length, mangle: true, compressor: { warnings: false, drop_console: true, drop_debugger: true } }) ] }) module.exports = productionConfig
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((e=e||self).ru={})}(this,function(e){"use strict";var n="undefined"!=typeof window&&void 0!==window.flatpickr?window.flatpickr:{l10ns:{}},t={weekdays:{shorthand:["Вс","Пн","Вт","Ср","Чт","Пт","Сб"],longhand:["Воскресенье","Понедельник","Вторник","Среда","Четверг","Пятница","Суббота"]},months:{shorthand:["Янв","Фев","Март","Апр","Май","Июнь","Июль","Авг","Сен","Окт","Ноя","Дек"],longhand:["Январь","Февраль","Март","Апрель","Май","Июнь","Июль","Август","Сентябрь","Октябрь","Ноябрь","Декабрь"]},firstDayOfWeek:1,ordinal:function(){return""},rangeSeparator:" — ",weekAbbreviation:"Нед.",scrollTitle:"Прокрутите для увеличения",toggleTitle:"Нажмите для переключения",amPM:["ДП","ПП"],yearAriaLabel:"Год",time_24hr:!0};n.l10ns.ru=t;var o=n.l10ns;e.Russian=t,e.default=o,Object.defineProperty(e,"__esModule",{value:!0})});
var test = require('tape'); var Random = require('random-js'); var random = new Random(Random.engines.mt19937().seed(0)); var ss = require('../'); function rng() { return random.real(0, 1); } test('shuffle', function(t) { var input = [1, 2, 3, 4, 5, 6]; t.deepEqual(ss.shuffle([], rng), []); t.deepEqual(ss.shuffle(input, rng), [1, 5, 3, 2, 4, 6]); t.deepEqual(input, [1, 2, 3, 4, 5, 6], 'does not change original array'); t.deepEqual(ss.shuffle(input, rng), [5, 4, 1, 3, 6, 2]); t.deepEqual(input, [1, 2, 3, 4, 5, 6], 'does not change original array'); t.end(); }); test('shuffle_in_place', function(t) { var input = [1, 2, 3, 4, 5, 6]; t.deepEqual(ss.shuffle_in_place([], rng), []); t.deepEqual(ss.shuffle_in_place(input, rng), [6, 1, 5, 2, 4, 3]); t.deepEqual(input, [6, 1, 5, 2, 4, 3], 'changes original array'); t.end(); }); test('shuffle_in_place truly random', function(t) { var input = [1, 2, 3, 4, 5, 6]; t.deepEqual(ss.shuffle_in_place([]), []); t.deepEqual(ss.shuffle_in_place(input).sort(), [1, 2, 3, 4, 5, 6]); t.end(); });
define([], function() { return { "PropertyPaneDescription": "Description", "BasicGroupName": "Group Name", "DescriptionFieldLabel": "Description Field", "TargetEmailFieldLabel": "Target Email", "SubjectFieldLabel": "Subject" } });
'use strict'; /* jshint -W030 */ /* jshint -W110 */ var chai = require('chai') , Sequelize = require('../../index') , expect = chai.expect , Support = require(__dirname + '/support') , DataTypes = require(__dirname + '/../../lib/data-types') , dialect = Support.getTestDialect() , sinon = require('sinon') , _ = require('lodash') , moment = require('moment') , Promise = require('bluebird') , current = Support.sequelize; describe(Support.getTestDialectTeaser('Model'), function() { before(function () { this.clock = sinon.useFakeTimers(); }); after(function () { this.clock.restore(); }); beforeEach(function() { this.User = this.sequelize.define('User', { username: DataTypes.STRING, secretValue: DataTypes.STRING, data: DataTypes.STRING, intVal: DataTypes.INTEGER, theDate: DataTypes.DATE, aBool: DataTypes.BOOLEAN }); return this.User.sync({ force: true }); }); describe('constructor', function() { it('uses the passed dao name as tablename if freezeTableName', function() { var User = this.sequelize.define('FrozenUser', {}, { freezeTableName: true }); expect(User.tableName).to.equal('FrozenUser'); }); it('uses the pluralized dao name as tablename unless freezeTableName', function() { var User = this.sequelize.define('SuperUser', {}, { freezeTableName: false }); expect(User.tableName).to.equal('SuperUsers'); }); it('uses checks to make sure dao factory isnt leaking on multiple define', function() { this.sequelize.define('SuperUser', {}, { freezeTableName: false }); var factorySize = this.sequelize.modelManager.all.length; this.sequelize.define('SuperUser', {}, { freezeTableName: false }); var factorySize2 = this.sequelize.modelManager.all.length; expect(factorySize).to.equal(factorySize2); }); it('allows us us to predefine the ID column with our own specs', function() { var User = this.sequelize.define('UserCol', { id: { type: Sequelize.STRING, defaultValue: 'User', primaryKey: true } }); return User.sync({ force: true }).then(function() { return expect(User.create({id: 'My own ID!'})).to.eventually.have.property('id', 'My own ID!'); }); }); it('throws an error if 2 autoIncrements are passed', function() { var self = this; expect(function() { self.sequelize.define('UserWithTwoAutoIncrements', { userid: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, userscore: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true } }); }).to.throw(Error, 'Invalid Instance definition. Only one autoincrement field allowed.'); }); it('throws an error if a custom model-wide validation is not a function', function() { var self = this; expect(function() { self.sequelize.define('Foo', { field: Sequelize.INTEGER }, { validate: { notFunction: 33 } }); }).to.throw(Error, 'Members of the validate option must be functions. Model: Foo, error with validate member notFunction'); }); it('throws an error if a custom model-wide validation has the same name as a field', function() { var self = this; expect(function() { self.sequelize.define('Foo', { field: Sequelize.INTEGER }, { validate: { field: function() {} } }); }).to.throw(Error, 'A model validator function must not have the same name as a field. Model: Foo, field/validation name: field'); }); it('should allow me to set a default value for createdAt and updatedAt', function() { var UserTable = this.sequelize.define('UserCol', { aNumber: Sequelize.INTEGER, createdAt: { type: Sequelize.DATE, defaultValue: moment('2012-01-01').toDate() }, updatedAt: { type: Sequelize.DATE, defaultValue: moment('2012-01-02').toDate() } }, { timestamps: true }); return UserTable.sync({ force: true }).then(function() { return UserTable.create({aNumber: 5}).then(function(user) { return UserTable.bulkCreate([ {aNumber: 10}, {aNumber: 12} ]).then(function() { return UserTable.findAll({where: {aNumber: { gte: 10 }}}).then(function(users) { expect(moment(user.createdAt).format('YYYY-MM-DD')).to.equal('2012-01-01'); expect(moment(user.updatedAt).format('YYYY-MM-DD')).to.equal('2012-01-02'); users.forEach(function(u) { expect(moment(u.createdAt).format('YYYY-MM-DD')).to.equal('2012-01-01'); expect(moment(u.updatedAt).format('YYYY-MM-DD')).to.equal('2012-01-02'); }); }); }); }); }); }); it('should allow me to set a function as default value', function() { var defaultFunction = sinon.stub().returns(5); var UserTable = this.sequelize.define('UserCol', { aNumber: { type: Sequelize.INTEGER, defaultValue: defaultFunction } }, { timestamps: true }); return UserTable.sync({ force: true }).then(function() { return UserTable.create().then(function(user) { return UserTable.create().then(function(user2) { expect(user.aNumber).to.equal(5); expect(user2.aNumber).to.equal(5); expect(defaultFunction.callCount).to.equal(2); }); }); }); }); it('should allow me to override updatedAt, createdAt, and deletedAt fields', function() { var UserTable = this.sequelize.define('UserCol', { aNumber: Sequelize.INTEGER }, { timestamps: true, updatedAt: 'updatedOn', createdAt: 'dateCreated', deletedAt: 'deletedAtThisTime', paranoid: true }); return UserTable.sync({force: true}).then(function() { return UserTable.create({aNumber: 4}).then(function(user) { expect(user.updatedOn).to.exist; expect(user.dateCreated).to.exist; return user.destroy().then(function() { return user.reload({ paranoid: false }).then(function() { expect(user.deletedAtThisTime).to.exist; }); }); }); }); }); it('should allow me to disable some of the timestamp fields', function() { var UpdatingUser = this.sequelize.define('UpdatingUser', { name: DataTypes.STRING }, { timestamps: true, updatedAt: false, createdAt: false, deletedAt: 'deletedAtThisTime', paranoid: true }); return UpdatingUser.sync({force: true}).then(function() { return UpdatingUser.create({ name: 'heyo' }).then(function(user) { expect(user.createdAt).not.to.exist; expect(user.false).not.to.exist; // because, you know we might accidentally add a field named 'false' user.name = 'heho'; return user.save().then(function(user) { expect(user.updatedAt).not.to.exist; return user.destroy().then(function() { return user.reload({ paranoid: false }).then(function() { expect(user.deletedAtThisTime).to.exist; }); }); }); }); }); }); it('returns proper defaultValues after save when setter is set', function() { var titleSetter = sinon.spy() , Task = this.sequelize.define('TaskBuild', { title: { type: Sequelize.STRING(50), allowNull: false, defaultValue: '' } }, { setterMethods: { title: titleSetter } }); return Task.sync({force: true}).then(function() { return Task.build().save().then(function(record) { expect(record.title).to.be.a('string'); expect(record.title).to.equal(''); expect(titleSetter.notCalled).to.be.ok; // The setter method should not be invoked for default values }); }); }); it('should work with both paranoid and underscored being true', function() { var UserTable = this.sequelize.define('UserCol', { aNumber: Sequelize.INTEGER }, { paranoid: true, underscored: true }); return UserTable.sync({force: true}).then(function() { return UserTable.create({aNumber: 30}).then(function() { return UserTable.count().then(function(c) { expect(c).to.equal(1); }); }); }); }); it('allows multiple column unique keys to be defined', function() { var User = this.sequelize.define('UserWithUniqueUsername', { username: { type: Sequelize.STRING, unique: 'user_and_email' }, email: { type: Sequelize.STRING, unique: 'user_and_email' }, aCol: { type: Sequelize.STRING, unique: 'a_and_b' }, bCol: { type: Sequelize.STRING, unique: 'a_and_b' } }); return User.sync({ force: true, logging: _.after(2, _.once(function(sql) { if (dialect === 'mssql') { expect(sql).to.match(/CONSTRAINT\s*([`"\[]?user_and_email[`"\]]?)?\s*UNIQUE\s*\([`"\[]?username[`"\]]?, [`"\[]?email[`"\]]?\)/); expect(sql).to.match(/CONSTRAINT\s*([`"\[]?a_and_b[`"\]]?)?\s*UNIQUE\s*\([`"\[]?aCol[`"\]]?, [`"\[]?bCol[`"\]]?\)/); } else { expect(sql).to.match(/UNIQUE\s*([`"]?user_and_email[`"]?)?\s*\([`"]?username[`"]?, [`"]?email[`"]?\)/); expect(sql).to.match(/UNIQUE\s*([`"]?a_and_b[`"]?)?\s*\([`"]?aCol[`"]?, [`"]?bCol[`"]?\)/); } }))}); }); it('allows unique on column with field aliases', function() { var User = this.sequelize.define('UserWithUniqueFieldAlias', { userName: { type: Sequelize.STRING, unique: 'user_name_unique', field: 'user_name' } }); return User.sync({ force: true }).bind(this).then(function() { return this.sequelize.queryInterface.showIndex(User.tableName).then(function(indexes) { var idxPrimary, idxUnique; if (dialect === 'sqlite') { expect(indexes).to.have.length(1); idxUnique = indexes[0]; expect(idxUnique.primary).to.equal(false); expect(idxUnique.unique).to.equal(true); expect(idxUnique.fields).to.deep.equal([{attribute: 'user_name', length: undefined, order: undefined}]); } else if (dialect === 'mysql') { expect(indexes).to.have.length(2); idxPrimary = indexes[0]; idxUnique = indexes[1]; expect(idxUnique.primary).to.equal(false); expect(idxUnique.unique).to.equal(true); expect(idxUnique.fields).to.deep.equal([{attribute: 'user_name', length: undefined, order: 'ASC'}]); expect(idxUnique.type).to.equal('BTREE'); } else if (dialect === 'postgres') { expect(indexes).to.have.length(2); idxPrimary = indexes[0]; idxUnique = indexes[1]; expect(idxUnique.primary).to.equal(false); expect(idxUnique.unique).to.equal(true); expect(idxUnique.fields).to.deep.equal([{attribute: 'user_name', collate: undefined, order: undefined, length: undefined}]); } else if (dialect === 'mssql') { expect(indexes).to.have.length(2); idxPrimary = indexes[0]; idxUnique = indexes[1]; expect(idxUnique.primary).to.equal(false); expect(idxUnique.unique).to.equal(true); expect(idxUnique.fields).to.deep.equal([{attribute: 'user_name', collate: undefined, length: undefined, order: 'ASC'}]); } }); }); }); it('allows us to customize the error message for unique constraint', function() { var self = this , User = this.sequelize.define('UserWithUniqueUsername', { username: { type: Sequelize.STRING, unique: { name: 'user_and_email', msg: 'User and email must be unique' }}, email: { type: Sequelize.STRING, unique: 'user_and_email' } }); return User.sync({ force: true }).bind(this).then(function() { return self.sequelize.Promise.all([ User.create({username: 'tobi', email: 'tobi@tobi.me'}), User.create({username: 'tobi', email: 'tobi@tobi.me'})]); }).catch (self.sequelize.UniqueConstraintError, function(err) { expect(err.message).to.equal('User and email must be unique'); }); }); // If you use migrations to create unique indexes that have explicit names and/or contain fields // that have underscore in their name. Then sequelize must use the index name to map the custom message to the error thrown from db. it('allows us to map the customized error message with unique constraint name', function() { // Fake migration style index creation with explicit index definition var self = this , User = this.sequelize.define('UserWithUniqueUsername', { user_id: { type: Sequelize.INTEGER}, email: { type: Sequelize.STRING} }, { indexes: [ { name: 'user_and_email_index', msg: 'User and email must be unique', unique: true, method: 'BTREE', fields: ['user_id', {attribute: 'email', collate: dialect === 'sqlite' ? 'RTRIM' : 'en_US', order: 'DESC', length: 5}] }] }); return User.sync({ force: true }).bind(this).then(function() { // Redefine the model to use the index in database and override error message User = self.sequelize.define('UserWithUniqueUsername', { user_id: { type: Sequelize.INTEGER, unique: { name: 'user_and_email_index', msg: 'User and email must be unique' }}, email: { type: Sequelize.STRING, unique: 'user_and_email_index'} }); return self.sequelize.Promise.all([ User.create({user_id: 1, email: 'tobi@tobi.me'}), User.create({user_id: 1, email: 'tobi@tobi.me'})]); }).catch (self.sequelize.UniqueConstraintError, function(err) { expect(err.message).to.equal('User and email must be unique'); }); }); it('should allow the user to specify indexes in options', function() { var indices = [{ name: 'a_b_uniq', unique: true, method: 'BTREE', fields: ['fieldB', {attribute: 'fieldA', collate: dialect === 'sqlite' ? 'RTRIM' : 'en_US', order: 'DESC', length: 5}] }]; if (dialect !== 'mssql') { indices.push({ type: 'FULLTEXT', fields: ['fieldC'], concurrently: true }); indices.push({ type: 'FULLTEXT', fields: ['fieldD'] }); } var Model = this.sequelize.define('model', { fieldA: Sequelize.STRING, fieldB: Sequelize.INTEGER, fieldC: Sequelize.STRING, fieldD: Sequelize.STRING }, { indexes: indices, engine: 'MyISAM' }); return this.sequelize.sync().bind(this).then(function() { return this.sequelize.sync(); // The second call should not try to create the indices again }).then(function() { return this.sequelize.queryInterface.showIndex(Model.tableName); }).spread(function() { var primary, idx1, idx2, idx3; if (dialect === 'sqlite') { // PRAGMA index_info does not return the primary index idx1 = arguments[0]; idx2 = arguments[1]; expect(idx1.fields).to.deep.equal([ { attribute: 'fieldB', length: undefined, order: undefined}, { attribute: 'fieldA', length: undefined, order: undefined} ]); expect(idx2.fields).to.deep.equal([ { attribute: 'fieldC', length: undefined, order: undefined} ]); } else if (dialect === 'mssql') { idx1 = arguments[0]; expect(idx1.fields).to.deep.equal([ { attribute: 'fieldB', length: undefined, order: 'ASC', collate: undefined}, { attribute: 'fieldA', length: undefined, order: 'DESC', collate: undefined} ]); } else if (dialect === 'postgres') { // Postgres returns indexes in alphabetical order primary = arguments[2]; idx1 = arguments[0]; idx2 = arguments[1]; idx3 = arguments[2]; expect(idx1.fields).to.deep.equal([ { attribute: 'fieldB', length: undefined, order: undefined, collate: undefined}, { attribute: 'fieldA', length: undefined, order: 'DESC', collate: 'en_US'} ]); expect(idx2.fields).to.deep.equal([ { attribute: 'fieldC', length: undefined, order: undefined, collate: undefined} ]); expect(idx3.fields).to.deep.equal([ { attribute: 'fieldD', length: undefined, order: undefined, collate: undefined} ]); } else { // And finally mysql returns the primary first, and then the rest in the order they were defined primary = arguments[0]; idx1 = arguments[1]; idx2 = arguments[2]; expect(primary.primary).to.be.ok; expect(idx1.type).to.equal('BTREE'); expect(idx2.type).to.equal('FULLTEXT'); expect(idx1.fields).to.deep.equal([ { attribute: 'fieldB', length: undefined, order: 'ASC'}, { attribute: 'fieldA', length: 5, order: 'ASC'} ]); expect(idx2.fields).to.deep.equal([ { attribute: 'fieldC', length: undefined, order: undefined} ]); } expect(idx1.name).to.equal('a_b_uniq'); expect(idx1.unique).to.be.ok; if (dialect !== 'mssql') { expect(idx2.name).to.equal('models_field_c'); expect(idx2.unique).not.to.be.ok; } }); }); }); describe('build', function() { it("doesn't create database entries", function() { this.User.build({ username: 'John Wayne' }); return this.User.findAll().then(function(users) { expect(users).to.have.length(0); }); }); it('fills the objects with default values', function() { var Task = this.sequelize.define('TaskBuild', { title: {type: Sequelize.STRING, defaultValue: 'a task!'}, foo: {type: Sequelize.INTEGER, defaultValue: 2}, bar: {type: Sequelize.DATE}, foobar: {type: Sequelize.TEXT, defaultValue: 'asd'}, flag: {type: Sequelize.BOOLEAN, defaultValue: false} }); expect(Task.build().title).to.equal('a task!'); expect(Task.build().foo).to.equal(2); expect(Task.build().bar).to.not.be.ok; expect(Task.build().foobar).to.equal('asd'); expect(Task.build().flag).to.be.false; }); it('fills the objects with default values', function() { var Task = this.sequelize.define('TaskBuild', { title: {type: Sequelize.STRING, defaultValue: 'a task!'}, foo: {type: Sequelize.INTEGER, defaultValue: 2}, bar: {type: Sequelize.DATE}, foobar: {type: Sequelize.TEXT, defaultValue: 'asd'}, flag: {type: Sequelize.BOOLEAN, defaultValue: false} }, { timestamps: false }); expect(Task.build().title).to.equal('a task!'); expect(Task.build().foo).to.equal(2); expect(Task.build().bar).to.not.be.ok; expect(Task.build().foobar).to.equal('asd'); expect(Task.build().flag).to.be.false; }); it('attaches getter and setter methods from attribute definition', function() { var Product = this.sequelize.define('ProductWithSettersAndGetters1', { price: { type: Sequelize.INTEGER, get: function() { return 'answer = ' + this.getDataValue('price'); }, set: function(v) { return this.setDataValue('price', v + 42); } } }); expect(Product.build({price: 42}).price).to.equal('answer = 84'); var p = Product.build({price: 1}); expect(p.price).to.equal('answer = 43'); p.price = 0; expect(p.price).to.equal('answer = 42'); }); it('attaches getter and setter methods from options', function() { var Product = this.sequelize.define('ProductWithSettersAndGetters2', { priceInCents: Sequelize.INTEGER },{ setterMethods: { price: function(value) { this.dataValues.priceInCents = value * 100; } }, getterMethods: { price: function() { return '$' + (this.getDataValue('priceInCents') / 100); }, priceInCents: function() { return this.dataValues.priceInCents; } } }); expect(Product.build({price: 20}).priceInCents).to.equal(20 * 100); expect(Product.build({priceInCents: 30 * 100}).price).to.equal('$' + 30); }); it('attaches getter and setter methods from options only if not defined in attribute', function() { var Product = this.sequelize.define('ProductWithSettersAndGetters3', { price1: { type: Sequelize.INTEGER, set: function(v) { this.setDataValue('price1', v * 10); } }, price2: { type: Sequelize.INTEGER, get: function() { return this.getDataValue('price2') * 10; } } },{ setterMethods: { price1: function(v) { this.setDataValue('price1', v * 100); } }, getterMethods: { price2: function() { return '$' + this.getDataValue('price2'); } } }); var p = Product.build({ price1: 1, price2: 2 }); expect(p.price1).to.equal(10); expect(p.price2).to.equal(20); }); describe('include', function() { it('should support basic includes', function() { var Product = this.sequelize.define('Product', { title: Sequelize.STRING }); var Tag = this.sequelize.define('Tag', { name: Sequelize.STRING }); var User = this.sequelize.define('User', { first_name: Sequelize.STRING, last_name: Sequelize.STRING }); Product.hasMany(Tag); Product.belongsTo(User); var product = Product.build({ id: 1, title: 'Chair', Tags: [ {id: 1, name: 'Alpha'}, {id: 2, name: 'Beta'} ], User: { id: 1, first_name: 'Mick', last_name: 'Hansen' } }, { include: [ User, Tag ] }); expect(product.Tags).to.be.ok; expect(product.Tags.length).to.equal(2); expect(product.Tags[0]).to.be.instanceof(Tag); expect(product.User).to.be.ok; expect(product.User).to.be.instanceof(User); }); it('should support includes with aliases', function() { var Product = this.sequelize.define('Product', { title: Sequelize.STRING }); var Tag = this.sequelize.define('Tag', { name: Sequelize.STRING }); var User = this.sequelize.define('User', { first_name: Sequelize.STRING, last_name: Sequelize.STRING }); Product.hasMany(Tag, {as: 'categories'}); Product.belongsToMany(User, {as: 'followers', through: 'product_followers'}); User.belongsToMany(Product, {as: 'following', through: 'product_followers'}); var product = Product.build({ id: 1, title: 'Chair', categories: [ {id: 1, name: 'Alpha'}, {id: 2, name: 'Beta'}, {id: 3, name: 'Charlie'}, {id: 4, name: 'Delta'} ], followers: [ { id: 1, first_name: 'Mick', last_name: 'Hansen' }, { id: 2, first_name: 'Jan', last_name: 'Meier' } ] }, { include: [ {model: User, as: 'followers'}, {model: Tag, as: 'categories'} ] }); expect(product.categories).to.be.ok; expect(product.categories.length).to.equal(4); expect(product.categories[0]).to.be.instanceof(Tag); expect(product.followers).to.be.ok; expect(product.followers.length).to.equal(2); expect(product.followers[0]).to.be.instanceof(User); }); }); }); describe('findOne', function() { if (current.dialect.supports.transactions) { it('supports the transaction option in the first parameter', function() { return Support.prepareTransactionTest(this.sequelize).bind({}).then(function(sequelize) { var User = sequelize.define('User', { username: Sequelize.STRING, foo: Sequelize.STRING }); return User.sync({ force: true }).then(function() { return sequelize.transaction().then(function(t) { return User.create({ username: 'foo' }, { transaction: t }).then(function() { return User.findOne({ where: { username: 'foo' }, transaction: t }).then(function(user) { expect(user).to.not.be.null; return t.rollback(); }); }); }); }); }); }); } it('should not fail if model is paranoid and where is an empty array', function() { var User = this.sequelize.define('User', { username: Sequelize.STRING }, { paranoid: true }); return User.sync({ force: true }) .then(function() { return User.create({ username: 'A fancy name' }); }) .then(function() { return User.findOne({ where: [] }); }) .then(function(u) { expect(u.username).to.equal('A fancy name'); }); }); }); describe('findOrInitialize', function() { if (current.dialect.supports.transactions) { it('supports transactions', function() { return Support.prepareTransactionTest(this.sequelize).bind({}).then(function(sequelize) { var User = sequelize.define('User', { username: Sequelize.STRING, foo: Sequelize.STRING }); return User.sync({ force: true }).then(function() { return sequelize.transaction().then(function(t) { return User.create({ username: 'foo' }, { transaction: t }).then(function() { return User.findOrInitialize({ where: {username: 'foo'} }).spread(function(user1) { return User.findOrInitialize({ where: {username: 'foo'}, transaction: t }).spread(function(user2) { return User.findOrInitialize({ where: {username: 'foo'}, defaults: { foo: 'asd' }, transaction: t }).spread(function(user3) { expect(user1.isNewRecord).to.be.true; expect(user2.isNewRecord).to.be.false; expect(user3.isNewRecord).to.be.false; return t.commit(); }); }); }); }); }); }); }); }); } describe('returns an instance if it already exists', function() { it('with a single find field', function() { var self = this; return this.User.create({ username: 'Username' }).then(function(user) { return self.User.findOrInitialize({ where: { username: user.username } }).spread(function(_user, initialized) { expect(_user.id).to.equal(user.id); expect(_user.username).to.equal('Username'); expect(initialized).to.be.false; }); }); }); it('with multiple find fields', function() { var self = this; return this.User.create({ username: 'Username', data: 'data' }).then(function(user) { return self.User.findOrInitialize({ where: { username: user.username, data: user.data }}).spread(function(_user, initialized) { expect(_user.id).to.equal(user.id); expect(_user.username).to.equal('Username'); expect(_user.data).to.equal('data'); expect(initialized).to.be.false; }); }); }); it('builds a new instance with default value.', function() { var data = { username: 'Username' }, default_values = { data: 'ThisIsData' }; return this.User.findOrInitialize({ where: data, defaults: default_values }).spread(function(user, initialized) { expect(user.id).to.be.null; expect(user.username).to.equal('Username'); expect(user.data).to.equal('ThisIsData'); expect(initialized).to.be.true; expect(user.isNewRecord).to.be.true; }); }); }); }); describe('update', function() { it('throws an error if no where clause is given', function() { var User = this.sequelize.define('User', { username: DataTypes.STRING }); return this.sequelize.sync({ force: true }).then(function() { return User.update(); }).then(function() { throw new Error('Update should throw an error if no where clause is given.'); }, function(err) { expect(err).to.be.an.instanceof(Error); expect(err.message).to.equal('Missing where attribute in the options parameter passed to update.'); }); }); if (current.dialect.supports.transactions) { it('supports transactions', function() { return Support.prepareTransactionTest(this.sequelize).bind({}).then(function(sequelize) { var User = sequelize.define('User', { username: Sequelize.STRING }); return User.sync({ force: true }).then(function() { return User.create({ username: 'foo' }).then(function() { return sequelize.transaction().then(function(t) { return User.update({ username: 'bar' }, {where: {username: 'foo'}, transaction: t }).then(function() { return User.findAll().then(function(users1) { return User.findAll({ transaction: t }).then(function(users2) { expect(users1[0].username).to.equal('foo'); expect(users2[0].username).to.equal('bar'); return t.rollback(); }); }); }); }); }); }); }); }); } it('updates the attributes that we select only without updating createdAt', function() { var User = this.sequelize.define('User1', { username: Sequelize.STRING, secretValue: Sequelize.STRING }, { paranoid: true }); var test = false; return User.sync({ force: true }).then(function() { return User.create({username: 'Peter', secretValue: '42'}).then(function(user) { return user.updateAttributes({ secretValue: '43' }, { fields: ['secretValue'], logging: function (sql) { test = true; if (dialect === 'mssql') { expect(sql).to.not.contain('createdAt'); } else { expect(sql).to.match(/UPDATE\s+[`"]+User1s[`"]+\s+SET\s+[`"]+secretValue[`"]='43',[`"]+updatedAt[`"]+='[^`",]+'\s+WHERE [`"]+id[`"]+\s=\s1/); } } }); }); }).then(function() { expect(test).to.be.true; }); }); it('allows sql logging of updated statements', function() { var User = this.sequelize.define('User', { name: Sequelize.STRING, bio: Sequelize.TEXT }, { paranoid: true }); var test = false; return User.sync({ force: true }).then(function() { return User.create({ name: 'meg', bio: 'none' }).then(function(u) { expect(u).to.exist; return u.updateAttributes({name: 'brian'}, { logging: function (sql) { test = true; expect(sql).to.exist; expect(sql.toUpperCase().indexOf('UPDATE')).to.be.above(-1); } }); }); }).then(function() { expect(test).to.be.true; }); }); it('updates only values that match filter', function() { var self = this , data = [{ username: 'Peter', secretValue: '42' }, { username: 'Paul', secretValue: '42' }, { username: 'Bob', secretValue: '43' }]; return this.User.bulkCreate(data).then(function() { return self.User.update({username: 'Bill'}, {where: {secretValue: '42'}}).then(function() { return self.User.findAll({order: 'id'}).then(function(users) { expect(users.length).to.equal(3); users.forEach(function(user) { if (user.secretValue === '42') { expect(user.username).to.equal('Bill'); } else { expect(user.username).to.equal('Bob'); } }); }); }); }); }); it('updates only values that match the allowed fields', function() { var self = this , data = [{ username: 'Peter', secretValue: '42' }]; return this.User.bulkCreate(data).then(function() { return self.User.update({username: 'Bill', secretValue: '43'}, {where: {secretValue: '42'}, fields: ['username']}).then(function() { return self.User.findAll({order: 'id'}).then(function(users) { expect(users.length).to.equal(1); var user = users[0]; expect(user.username).to.equal('Bill'); expect(user.secretValue).to.equal('42'); }); }); }); }); it('updates with casting', function() { var self = this; return this.User.create({ username: 'John' }).then(function() { return self.User.update({username: self.sequelize.cast('1', dialect === 'mssql' ? 'nvarchar' : 'char')}, {where: {username: 'John'}}).then(function() { return self.User.findAll().then(function(users) { expect(users[0].username).to.equal('1'); }); }); }); }); it('updates with function and column value', function() { var self = this; return this.User.create({ username: 'John' }).then(function() { return self.User.update({username: self.sequelize.fn('upper', self.sequelize.col('username'))}, {where: {username: 'John'}}).then(function() { return self.User.findAll().then(function(users) { expect(users[0].username).to.equal('JOHN'); }); }); }); }); it('does not update virtual attributes', function () { var User = this.sequelize.define('User', { username: Sequelize.STRING, virtual: Sequelize.VIRTUAL }); return User.create({ username: 'jan' }).then(function () { return User.update({ username: 'kurt', virtual: 'test' }, { where: { username: 'jan' } }); }).then(function () { return User.findAll(); }).spread(function (user) { expect(user.username).to.equal('kurt'); }); }); it('doesn\'t update attributes that are altered by virtual setters when option is enabled', function () { var User = this.sequelize.define('UserWithVirtualSetters', { username: Sequelize.STRING, illness_name: Sequelize.STRING, illness_pain: Sequelize.INTEGER, illness: { type: Sequelize.VIRTUAL, set: function (value) { this.set('illness_name', value.name); this.set('illness_pain', value.pain); } } }); return User.sync({ force: true }).then(function () { return User.create({ username: 'Jan', illness_name: 'Headache', illness_pain: 5 }); }).then(function () { return User.update({ illness: { pain: 10, name: 'Backache' } }, { where: { username: 'Jan' }, sideEffects: false }); }).then(function (user) { return User.findAll(); }).spread(function (user) { expect(user.illness_pain).to.be.equal(5); }); }); it('updates attributes that are altered by virtual setters', function () { var User = this.sequelize.define('UserWithVirtualSetters', { username: Sequelize.STRING, illness_name: Sequelize.STRING, illness_pain: Sequelize.INTEGER, illness: { type: Sequelize.VIRTUAL, set: function (value) { this.set('illness_name', value.name); this.set('illness_pain', value.pain); } } }); return User.sync({ force: true }).then(function () { return User.create({ username: 'Jan', illness_name: 'Headache', illness_pain: 5 }); }).then(function () { return User.update({ illness: { pain: 10, name: 'Backache' } }, { where: { username: 'Jan' } }); }).then(function (user) { return User.findAll(); }).spread(function (user) { expect(user.illness_pain).to.be.equal(10); }); }); it('should properly set data when individualHooks are true', function() { var self = this; self.User.beforeUpdate(function(instance) { instance.set('intVal', 1); }); return self.User.create({ username: 'Peter' }).then(function (user) { return self.User.update({ data: 'test' }, { where: { id: user.id }, individualHooks: true }).then(function () { return self.User.findById(user.id).then(function (userUpdated){ expect(userUpdated.intVal).to.be.equal(1); }); }); }); }); it('sets updatedAt to the current timestamp', function() { var data = [{ username: 'Peter', secretValue: '42' }, { username: 'Paul', secretValue: '42' }, { username: 'Bob', secretValue: '43' }]; return this.User.bulkCreate(data).bind(this).then(function() { return this.User.findAll({order: 'id'}); }).then(function(users) { this.updatedAt = users[0].updatedAt; expect(this.updatedAt).to.be.ok; expect(this.updatedAt).to.equalTime(users[2].updatedAt); // All users should have the same updatedAt // Pass the time so we can actually see a change this.clock.tick(1000); return this.User.update({username: 'Bill'}, {where: {secretValue: '42'}}); }).then(function() { return this.User.findAll({order: 'id'}); }).then(function(users) { expect(users[0].username).to.equal('Bill'); expect(users[1].username).to.equal('Bill'); expect(users[2].username).to.equal('Bob'); expect(users[0].updatedAt).to.be.afterTime(this.updatedAt); expect(users[2].updatedAt).to.equalTime(this.updatedAt); }); }); it('returns the number of affected rows', function() { var self = this , data = [{ username: 'Peter', secretValue: '42' }, { username: 'Paul', secretValue: '42' }, { username: 'Bob', secretValue: '43' }]; return this.User.bulkCreate(data).then(function() { return self.User.update({username: 'Bill'}, {where: {secretValue: '42'}}).spread(function(affectedRows) { expect(affectedRows).to.equal(2); }).then(function() { return self.User.update({username: 'Bill'}, {where: {secretValue: '44'}}).spread(function(affectedRows) { expect(affectedRows).to.equal(0); }); }); }); }); if (dialect === 'postgres') { it('returns the affected rows if `options.returning` is true', function() { var self = this , data = [{ username: 'Peter', secretValue: '42' }, { username: 'Paul', secretValue: '42' }, { username: 'Bob', secretValue: '43' }]; return this.User.bulkCreate(data).then(function() { return self.User.update({ username: 'Bill' }, { where: {secretValue: '42' }, returning: true }).spread(function(count, rows) { expect(count).to.equal(2); expect(rows).to.have.length(2); }).then(function() { return self.User.update({ username: 'Bill'}, { where: {secretValue: '44' }, returning: true }).spread(function(count, rows) { expect(count).to.equal(0); expect(rows).to.have.length(0); }); }); }); }); } if (dialect === 'mysql') { it('supports limit clause', function() { var self = this , data = [{ username: 'Peter', secretValue: '42' }, { username: 'Peter', secretValue: '42' }, { username: 'Peter', secretValue: '42' }]; return this.User.bulkCreate(data).then(function() { return self.User.update({secretValue: '43'}, {where: {username: 'Peter'}, limit: 1}).spread(function(affectedRows) { expect(affectedRows).to.equal(1); }); }); }); } }); describe('destroy', function() { it('convenient method `truncate` should clear the table', function() { var User = this.sequelize.define('User', { username: DataTypes.STRING }), data = [ { username: 'user1' }, { username: 'user2' } ]; return this.sequelize.sync({ force: true }).then(function() { return User.bulkCreate(data); }).then(function() { return User.truncate(); }).then(function() { return expect(User.findAll()).to.eventually.have.length(0); }); }); it('truncate should clear the table', function() { var User = this.sequelize.define('User', { username: DataTypes.STRING }), data = [ { username: 'user1' }, { username: 'user2' } ]; return this.sequelize.sync({ force: true }).then(function() { return User.bulkCreate(data); }).then(function() { return User.destroy({ truncate: true }); }).then(function() { return expect(User.findAll()).to.eventually.have.length(0); }); }); it('throws an error if no where clause is given', function() { var User = this.sequelize.define('User', { username: DataTypes.STRING }); return this.sequelize.sync({ force: true }).then(function() { return User.destroy(); }).then(function() { throw new Error('Destroy should throw an error if no where clause is given.'); }, function(err) { expect(err).to.be.an.instanceof(Error); expect(err.message).to.equal('Missing where or truncate attribute in the options parameter of model.destroy.'); }); }); it('deletes all instances when given an empty where object', function() { var User = this.sequelize.define('User', { username: DataTypes.STRING }), data = [ { username: 'user1' }, { username: 'user2' } ]; return this.sequelize.sync({ force: true }).then(function() { return User.bulkCreate(data); }).then(function() { return User.destroy({ where: {} }); }).then(function(affectedRows) { expect(affectedRows).to.equal(2); return User.findAll(); }).then(function(users) { expect(users).to.have.length(0); }); }); if (current.dialect.supports.transactions) { it('supports transactions', function() { return Support.prepareTransactionTest(this.sequelize).bind({}).then(function(sequelize) { var User = sequelize.define('User', { username: Sequelize.STRING }); return User.sync({ force: true }).then(function() { return User.create({ username: 'foo' }).then(function() { return sequelize.transaction().then(function(t) { return User.destroy({ where: {}, transaction: t }).then(function() { return User.count().then(function(count1) { return User.count({ transaction: t }).then(function(count2) { expect(count1).to.equal(1); expect(count2).to.equal(0); return t.rollback(); }); }); }); }); }); }); }); }); } it('deletes values that match filter', function() { var self = this , data = [{ username: 'Peter', secretValue: '42' }, { username: 'Paul', secretValue: '42' }, { username: 'Bob', secretValue: '43' }]; return this.User.bulkCreate(data).then(function() { return self.User.destroy({where: {secretValue: '42'}}) .then(function() { return self.User.findAll({order: 'id'}).then(function(users) { expect(users.length).to.equal(1); expect(users[0].username).to.equal('Bob'); }); }); }); }); it('works without a primary key', function() { var Log = this.sequelize.define('Log', { client_id: DataTypes.INTEGER, content: DataTypes.TEXT, timestamp: DataTypes.DATE }); Log.removeAttribute('id'); return Log.sync({force: true}).then(function() { return Log.create({ client_id: 13, content: 'Error!', timestamp: new Date() }); }).then(function() { return Log.destroy({ where: { client_id: 13 } }); }).then(function() { return Log.findAll().then(function(logs) { expect(logs.length).to.equal(0); }); }); }); it('supports .field', function() { var UserProject = this.sequelize.define('UserProject', { userId: { type: DataTypes.INTEGER, field: 'user_id' } }); return UserProject.sync({force: true}).then(function() { return UserProject.create({ userId: 10 }); }).then(function() { return UserProject.destroy({ where: { userId: 10 } }); }).then(function() { return UserProject.findAll(); }).then(function(userProjects) { expect(userProjects.length).to.equal(0); }); }); it('sets deletedAt to the current timestamp if paranoid is true', function() { var self = this , qi = this.sequelize.queryInterface.QueryGenerator.quoteIdentifier.bind(this.sequelize.queryInterface.QueryGenerator) , ParanoidUser = self.sequelize.define('ParanoidUser', { username: Sequelize.STRING, secretValue: Sequelize.STRING, data: Sequelize.STRING, intVal: { type: Sequelize.INTEGER, defaultValue: 1} }, { paranoid: true }) , data = [{ username: 'Peter', secretValue: '42' }, { username: 'Paul', secretValue: '42' }, { username: 'Bob', secretValue: '43' }]; return ParanoidUser.sync({ force: true }).then(function() { return ParanoidUser.bulkCreate(data); }).bind({}).then(function() { // since we save in UTC, let's format to UTC time this.date = moment().utc().format('YYYY-MM-DD h:mm'); return ParanoidUser.destroy({where: {secretValue: '42'}}); }).then(function() { return ParanoidUser.findAll({order: 'id'}); }).then(function(users) { expect(users.length).to.equal(1); expect(users[0].username).to.equal('Bob'); return self.sequelize.query('SELECT * FROM ' + qi('ParanoidUsers') + ' WHERE ' + qi('deletedAt') + ' IS NOT NULL ORDER BY ' + qi('id')); }).spread(function(users) { expect(users[0].username).to.equal('Peter'); expect(users[1].username).to.equal('Paul'); expect(moment(new Date(users[0].deletedAt)).utc().format('YYYY-MM-DD h:mm')).to.equal(this.date); expect(moment(new Date(users[1].deletedAt)).utc().format('YYYY-MM-DD h:mm')).to.equal(this.date); }); }); it('does not set deletedAt for previously destroyed instances if paranoid is true', function() { var User = this.sequelize.define('UserCol', { secretValue: Sequelize.STRING, username: Sequelize.STRING }, { paranoid: true }); return User.sync({ force: true }).then(function() { return User.bulkCreate([ { username: 'Toni', secretValue: '42' }, { username: 'Tobi', secretValue: '42' }, { username: 'Max', secretValue: '42' } ]).then(function() { return User.findById(1).then(function(user) { return user.destroy().then(function() { return user.reload({ paranoid: false }).then(function() { var deletedAt = user.deletedAt; return User.destroy({ where: { secretValue: '42' } }).then(function() { return user.reload({ paranoid: false }).then(function() { expect(user.deletedAt).to.eql(deletedAt); }); }); }); }); }); }); }); }); describe("can't find records marked as deleted with paranoid being true", function() { it('with the DAOFactory', function() { var User = this.sequelize.define('UserCol', { username: Sequelize.STRING }, { paranoid: true }); return User.sync({ force: true }).then(function() { return User.bulkCreate([ {username: 'Toni'}, {username: 'Tobi'}, {username: 'Max'} ]).then(function() { return User.findById(1).then(function(user) { return user.destroy().then(function() { return User.findById(1).then(function(user) { expect(user).to.be.null; return User.count().then(function(cnt) { expect(cnt).to.equal(2); return User.findAll().then(function(users) { expect(users).to.have.length(2); }); }); }); }); }); }); }); }); }); describe('can find paranoid records if paranoid is marked as false in query', function() { it('with the DAOFactory', function() { var User = this.sequelize.define('UserCol', { username: Sequelize.STRING }, { paranoid: true }); return User.sync({ force: true }) .then(function() { return User.bulkCreate([ {username: 'Toni'}, {username: 'Tobi'}, {username: 'Max'} ]); }) .then(function() { return User.findById(1); }) .then(function(user) { return user.destroy(); }) .then(function() { return User.find({ where: 1, paranoid: false }); }) .then(function(user) { expect(user).to.exist; return User.findById(1); }) .then(function(user) { expect(user).to.be.null; return [User.count(), User.count({ paranoid: false })]; }) .spread(function(cnt, cntWithDeleted) { expect(cnt).to.equal(2); expect(cntWithDeleted).to.equal(3); }); }); }); it('should include deleted associated records if include has paranoid marked as false', function() { var User = this.sequelize.define('User', { username: Sequelize.STRING }, { paranoid: true }); var Pet = this.sequelize.define('Pet', { name: Sequelize.STRING, UserId: Sequelize.INTEGER }, { paranoid: true }); User.hasMany(Pet); Pet.belongsTo(User); var user; return User.sync({ force: true }) .then(function() { return Pet.sync({ force: true }); }) .then(function() { return User.create({ username: 'Joe' }); }) .then(function(_user) { user = _user; return Pet.bulkCreate([ { name: 'Fido', UserId: user.id }, { name: 'Fifi', UserId: user.id } ]); }) .then(function() { return Pet.findById(1); }) .then(function(pet) { return pet.destroy(); }) .then(function() { return [ User.find({ where: {id: user.id}, include: Pet }), User.find({ where: {id: user.id}, include: [{ model: Pet, paranoid: false }] }) ]; }) .spread(function(user, userWithDeletedPets) { expect(user).to.exist; expect(user.Pets).to.have.length(1); expect(userWithDeletedPets).to.exist; expect(userWithDeletedPets.Pets).to.have.length(2); }); }); it('should delete a paranoid record if I set force to true', function() { var self = this; var User = this.sequelize.define('paranoiduser', { username: Sequelize.STRING }, { paranoid: true }); return User.sync({ force: true }).then(function() { return User.bulkCreate([ {username: 'Bob'}, {username: 'Tobi'}, {username: 'Max'}, {username: 'Tony'} ]); }).then(function() { return User.find({where: {username: 'Bob'}}); }).then(function(user) { return user.destroy({force: true}); }).then(function() { return expect(User.find({where: {username: 'Bob'}})).to.eventually.be.null; }).then(function() { return User.find({where: {username: 'Tobi'}}); }).then(function(tobi) { return tobi.destroy(); }).then(function() { return self.sequelize.query('SELECT * FROM paranoidusers WHERE username=\'Tobi\'', { plain: true}); }).then(function(result) { expect(result.username).to.equal('Tobi'); return User.destroy({where: {username: 'Tony'}}); }).then(function() { return self.sequelize.query('SELECT * FROM paranoidusers WHERE username=\'Tony\'', { plain: true}); }).then(function(result) { expect(result.username).to.equal('Tony'); return User.destroy({where: {username: ['Tony', 'Max']}, force: true}); }).then(function() { return self.sequelize.query('SELECT * FROM paranoidusers', {raw: true}); }).spread(function(users) { expect(users).to.have.length(1); expect(users[0].username).to.equal('Tobi'); }); }); it('returns the number of affected rows', function() { var self = this , data = [{ username: 'Peter', secretValue: '42' }, { username: 'Paul', secretValue: '42' }, { username: 'Bob', secretValue: '43' }]; return this.User.bulkCreate(data).then(function() { return self.User.destroy({where: {secretValue: '42'}}).then(function(affectedRows) { expect(affectedRows).to.equal(2); }); }).then(function() { return self.User.destroy({where: {secretValue: '44'}}).then(function(affectedRows) { expect(affectedRows).to.equal(0); }); }); }); it('supports table schema/prefix', function() { var self = this , data = [{ username: 'Peter', secretValue: '42' }, { username: 'Paul', secretValue: '42' }, { username: 'Bob', secretValue: '43' }] , prefixUser = self.User.schema('prefix'); var run = function() { return prefixUser.sync({ force: true }).then(function() { return prefixUser.bulkCreate(data).then(function() { return prefixUser.destroy({where: {secretValue: '42'}}).then(function() { return prefixUser.findAll({order: 'id'}).then(function(users) { expect(users.length).to.equal(1); expect(users[0].username).to.equal('Bob'); }); }); }); }); }; return this.sequelize.queryInterface.dropAllSchemas().then(function() { return self.sequelize.queryInterface.createSchema('prefix').then(function() { return run.call(self); }); }); }); }); describe('restore', function() { it('returns an error if the model is not paranoid', function() { var self = this; return this.User.create({username: 'Peter', secretValue: '42'}) .then(function() { expect(function() {self.User.restore({where: {secretValue: '42'}});}).to.throw(Error, 'Model is not paranoid'); }); }); it('restores a previously deleted model', function() { var self = this , ParanoidUser = self.sequelize.define('ParanoidUser', { username: Sequelize.STRING, secretValue: Sequelize.STRING, data: Sequelize.STRING, intVal: { type: Sequelize.INTEGER, defaultValue: 1} }, { paranoid: true }) , data = [{ username: 'Peter', secretValue: '42' }, { username: 'Paul', secretValue: '43' }, { username: 'Bob', secretValue: '44' }]; return ParanoidUser.sync({ force: true }).then(function() { return ParanoidUser.bulkCreate(data); }).then(function() { return ParanoidUser.destroy({where: {secretValue: '42'}}); }).then(function() { return ParanoidUser.restore({where: {secretValue: '42'}}); }).then(function() { return ParanoidUser.find({where: {secretValue: '42'}}); }).then(function(user) { expect(user).to.be.ok; expect(user.username).to.equal('Peter'); }); }); }); describe('equals', function() { it('correctly determines equality of objects', function() { return this.User.create({username: 'hallo', data: 'welt'}).then(function(u) { expect(u.equals(u)).to.be.ok; }); }); // sqlite can't handle multiple primary keys if (dialect !== 'sqlite') { it('correctly determines equality with multiple primary keys', function() { var userKeys = this.sequelize.define('userkeys', { foo: {type: Sequelize.STRING, primaryKey: true}, bar: {type: Sequelize.STRING, primaryKey: true}, name: Sequelize.STRING, bio: Sequelize.TEXT }); return userKeys.sync({ force: true }).then(function() { return userKeys.create({foo: '1', bar: '2', name: 'hallo', bio: 'welt'}).then(function(u) { expect(u.equals(u)).to.be.ok; }); }); }); } }); describe('equalsOneOf', function() { // sqlite can't handle multiple primary keys if (dialect !== 'sqlite') { beforeEach(function() { this.userKey = this.sequelize.define('userKeys', { foo: {type: Sequelize.STRING, primaryKey: true}, bar: {type: Sequelize.STRING, primaryKey: true}, name: Sequelize.STRING, bio: Sequelize.TEXT }); return this.userKey.sync({ force: true }); }); it('determines equality if one is matching', function() { return this.userKey.create({foo: '1', bar: '2', name: 'hallo', bio: 'welt'}).then(function(u) { expect(u.equalsOneOf([u, {a: 1}])).to.be.ok; }); }); it("doesn't determine equality if none is matching", function() { return this.userKey.create({foo: '1', bar: '2', name: 'hallo', bio: 'welt'}).then(function(u) { expect(u.equalsOneOf([{b: 2}, {a: 1}])).to.not.be.ok; }); }); } }); describe('count', function() { if (current.dialect.supports.transactions) { it('supports transactions', function() { return Support.prepareTransactionTest(this.sequelize).bind({}).then(function(sequelize) { var User = sequelize.define('User', { username: Sequelize.STRING }); return User.sync({ force: true }).then(function() { return sequelize.transaction().then(function(t) { return User.create({ username: 'foo' }, { transaction: t }).then(function() { return User.count().then(function(count1) { return User.count({ transaction: t }).then(function(count2) { expect(count1).to.equal(0); expect(count2).to.equal(1); return t.rollback(); }); }); }); }); }); }); }); } it('counts all created objects', function() { var self = this; return this.User.bulkCreate([{username: 'user1'}, {username: 'user2'}]).then(function() { return self.User.count().then(function(count) { expect(count).to.equal(2); }); }); }); it('returns multiple rows when using group', function() { var self = this; return this.User.bulkCreate([ {username: 'user1', data: 'A'}, {username: 'user2', data: 'A'}, {username: 'user3', data: 'B'} ]).then(function() { return self.User.count({ attributes: ['data'], group: ['data'] }).then(function(count) { expect(count.length).to.equal(2); }); }); }); describe("options sent to aggregate", function () { var options, aggregateSpy; beforeEach(function () { options = { where: { username: 'user1'}}; aggregateSpy = sinon.spy(this.User, "aggregate"); }); afterEach(function () { expect(aggregateSpy).to.have.been.calledWith( sinon.match.any, sinon.match.any, sinon.match.object.and(sinon.match.has('where', { username: 'user1'}))); aggregateSpy.restore(); }); it('modifies option "limit" by setting it to null', function() { options.limit = 5; return this.User.count(options).then(function() { expect(aggregateSpy).to.have.been.calledWith( sinon.match.any, sinon.match.any, sinon.match.object.and(sinon.match.has('limit', null))); }); }); it('modifies option "offset" by setting it to null', function() { options.offset = 10; return this.User.count(options).then(function() { expect(aggregateSpy).to.have.been.calledWith( sinon.match.any, sinon.match.any, sinon.match.object.and(sinon.match.has('offset', null))); }); }); it('modifies option "order" by setting it to null', function() { options.order = "username"; return this.User.count(options).then(function() { expect(aggregateSpy).to.have.been.calledWith( sinon.match.any, sinon.match.any, sinon.match.object.and(sinon.match.has('order', null))); }); }); }); it('allows sql logging', function() { var test = false; return this.User.count({ logging: function (sql) { test = true; expect(sql).to.exist; expect(sql.toUpperCase().indexOf('SELECT')).to.be.above(-1); } }).then(function() { expect(test).to.be.true; }); }); it('filters object', function() { var self = this; return this.User.create({username: 'user1'}).then(function() { return self.User.create({username: 'foo'}).then(function() { return self.User.count({where: ["username LIKE '%us%'"]}).then(function(count) { expect(count).to.equal(1); }); }); }); }); it('supports distinct option', function () { const Post = this.sequelize.define('Post', {}); const PostComment = this.sequelize.define('PostComment', {}); Post.hasMany(PostComment); return Post.sync({ force: true }) .then(() => PostComment.sync({ force: true })) .then(() => Post.create({})) .then((post) => PostComment.bulkCreate([{ PostId: post.id },{ PostId: post.id }])) .then(() => Promise.join( Post.count({ distinct: false, include: [{ model: PostComment, required: false }] }), Post.count({ distinct: true, include: [{ model: PostComment, required: false }] }), (count1, count2) => { expect(count1).to.equal(2); expect(count2).to.equal(1); }) ); }); }); describe('min', function() { beforeEach(function() { var self = this; this.UserWithAge = this.sequelize.define('UserWithAge', { age: Sequelize.INTEGER }); this.UserWithDec = this.sequelize.define('UserWithDec', { value: Sequelize.DECIMAL(10, 3) }); return this.UserWithAge.sync({ force: true }).then(function() { return self.UserWithDec.sync({ force: true }); }); }); if (current.dialect.supports.transactions) { it('supports transactions', function() { return Support.prepareTransactionTest(this.sequelize).bind({}).then(function(sequelize) { var User = sequelize.define('User', { age: Sequelize.INTEGER }); return User.sync({ force: true }).then(function() { return sequelize.transaction().then(function(t) { return User.bulkCreate([{ age: 2 }, { age: 5 }, { age: 3 }], { transaction: t }).then(function() { return User.min('age').then(function(min1) { return User.min('age', { transaction: t }).then(function(min2) { expect(min1).to.be.not.ok; expect(min2).to.equal(2); return t.rollback(); }); }); }); }); }); }); }); } it('should return the min value', function() { var self = this; return this.UserWithAge.bulkCreate([{age: 3}, { age: 2 }]).then(function() { return self.UserWithAge.min('age').then(function(min) { expect(min).to.equal(2); }); }); }); it('allows sql logging', function() { var test = false; return this.UserWithAge.min('age', { logging: function (sql) { test = true; expect(sql).to.exist; expect(sql.toUpperCase().indexOf('SELECT')).to.be.above(-1); } }).then(function() { expect(test).to.be.true; }); }); it('should allow decimals in min', function() { var self = this; return this.UserWithDec.bulkCreate([{value: 5.5}, {value: 3.5}]).then(function() { return self.UserWithDec.min('value').then(function(min) { expect(min).to.equal(3.5); }); }); }); it('should allow strings in min', function() { var self = this; return this.User.bulkCreate([{username: 'bbb'}, {username: 'yyy'}]).then(function() { return self.User.min('username').then(function(min) { expect(min).to.equal('bbb'); }); }); }); it('should allow dates in min', function() { var self = this; return this.User.bulkCreate([{theDate: new Date(2000, 1, 1)}, {theDate: new Date(1990, 1, 1)}]).then(function() { return self.User.min('theDate').then(function(min) { expect(min).to.be.a('Date'); expect(new Date(1990, 1, 1)).to.equalDate(min); }); }); }); }); describe('max', function() { beforeEach(function() { var self = this; this.UserWithAge = this.sequelize.define('UserWithAge', { age: Sequelize.INTEGER, order: Sequelize.INTEGER }); this.UserWithDec = this.sequelize.define('UserWithDec', { value: Sequelize.DECIMAL(10, 3) }); return this.UserWithAge.sync({ force: true }).then(function() { return self.UserWithDec.sync({ force: true }); }); }); if (current.dialect.supports.transactions) { it('supports transactions', function() { return Support.prepareTransactionTest(this.sequelize).bind({}).then(function(sequelize) { var User = sequelize.define('User', { age: Sequelize.INTEGER }); return User.sync({ force: true }).then(function() { return sequelize.transaction().then(function(t) { return User.bulkCreate([{ age: 2 }, { age: 5 }, { age: 3 }], { transaction: t }).then(function() { return User.max('age').then(function(min1) { return User.max('age', { transaction: t }).then(function(min2) { expect(min1).to.be.not.ok; expect(min2).to.equal(5); return t.rollback(); }); }); }); }); }); }); }); } it('should return the max value for a field named the same as an SQL reserved keyword', function() { var self = this; return this.UserWithAge.bulkCreate([{age: 2, order: 3}, {age: 3, order: 5}]).then(function() { return self.UserWithAge.max('order').then(function(max) { expect(max).to.equal(5); }); }); }); it('should return the max value', function() { var self = this; return self.UserWithAge.bulkCreate([{age: 2}, {age: 3}]).then(function() { return self.UserWithAge.max('age').then(function(max) { expect(max).to.equal(3); }); }); }); it('should allow decimals in max', function() { var self = this; return this.UserWithDec.bulkCreate([{value: 3.5}, {value: 5.5}]).then(function() { return self.UserWithDec.max('value').then(function(max) { expect(max).to.equal(5.5); }); }); }); it('should allow dates in max', function() { var self = this; return this.User.bulkCreate([ {theDate: new Date(2013, 11, 31)}, {theDate: new Date(2000, 1, 1)} ]).then(function() { return self.User.max('theDate').then(function(max) { expect(max).to.be.a('Date'); expect(max).to.equalDate(new Date(2013, 11, 31)); }); }); }); it('should allow strings in max', function() { var self = this; return this.User.bulkCreate([{username: 'aaa'}, {username: 'zzz'}]).then(function() { return self.User.max('username').then(function(max) { expect(max).to.equal('zzz'); }); }); }); it('allows sql logging', function() { var logged = false; return this.UserWithAge.max('age', { logging: function (sql) { expect(sql).to.exist; logged = true; expect(sql.toUpperCase().indexOf('SELECT')).to.be.above(-1); } }).then(function() { expect(logged).to.true; }); }); }); describe('sum', function() { beforeEach(function() { this.UserWithAge = this.sequelize.define('UserWithAge', { age: Sequelize.INTEGER, order: Sequelize.INTEGER, gender: Sequelize.ENUM('male', 'female') }); this.UserWithDec = this.sequelize.define('UserWithDec', { value: Sequelize.DECIMAL(10, 3) }); this.UserWithFields = this.sequelize.define('UserWithFields', { age: { type: Sequelize.INTEGER, field: 'user_age' }, order: Sequelize.INTEGER, gender: { type: Sequelize.ENUM('male', 'female'), field: 'male_female' } }); return Promise.join( this.UserWithAge.sync({ force: true }), this.UserWithDec.sync({ force: true }), this.UserWithFields.sync({ force: true }) ); }); it('should return the sum of the values for a field named the same as an SQL reserved keyword', function() { var self = this; return this.UserWithAge.bulkCreate([{age: 2, order: 3}, {age: 3, order: 5}]).then(function() { return self.UserWithAge.sum('order').then(function(sum) { expect(sum).to.equal(8); }); }); }); it('should return the sum of a field in various records', function() { var self = this; return self.UserWithAge.bulkCreate([{age: 2}, {age: 3}]).then(function() { return self.UserWithAge.sum('age').then(function(sum) { expect(sum).to.equal(5); }); }); }); it('should allow decimals in sum', function() { var self = this; return this.UserWithDec.bulkCreate([{value: 3.5}, {value: 5.25}]).then(function() { return self.UserWithDec.sum('value').then(function(sum) { expect(sum).to.equal(8.75); }); }); }); it('should accept a where clause', function() { var options = { where: { 'gender': 'male' }}; var self = this; return self.UserWithAge.bulkCreate([{age: 2, gender: 'male'}, {age: 3, gender: 'female'}]).then(function() { return self.UserWithAge.sum('age', options).then(function(sum) { expect(sum).to.equal(2); }); }); }); it('should accept a where clause with custom fields', function() { return this.UserWithFields.bulkCreate([ {age: 2, gender: 'male'}, {age: 3, gender: 'female'} ]).bind(this).then(function() { return expect(this.UserWithFields.sum('age', { where: { 'gender': 'male' } })).to.eventually.equal(2); }); }); it('allows sql logging', function() { var logged = false; return this.UserWithAge.sum('age', { logging: function (sql) { expect(sql).to.exist; logged = true; expect(sql.toUpperCase().indexOf('SELECT')).to.be.above(-1); } }).then(function() { expect(logged).to.true; }); }); }); describe('schematic support', function() { beforeEach(function() { var self = this; this.UserPublic = this.sequelize.define('UserPublic', { age: Sequelize.INTEGER }); this.UserSpecial = this.sequelize.define('UserSpecial', { age: Sequelize.INTEGER }); return self.sequelize.dropAllSchemas().then(function() { return self.sequelize.createSchema('schema_test').then(function() { return self.sequelize.createSchema('special').then(function() { return self.UserSpecial.schema('special').sync({force: true}).then(function(UserSpecialSync) { self.UserSpecialSync = UserSpecialSync; }); }); }); }); }); it('should be able to drop with schemas', function() { return this.UserSpecial.drop(); }); it('should be able to list schemas', function() { return this.sequelize.showAllSchemas().then(function(schemas) { expect(schemas).to.be.instanceof(Array); // FIXME: reenable when schema support is properly added if (dialect !== 'mssql') { // sqlite & MySQL doesn't actually create schemas unless Model.sync() is called // Postgres supports schemas natively expect(schemas).to.have.length((dialect === 'postgres' ? 2 : 1)); } }); }); if (dialect === 'mysql' || dialect === 'sqlite') { it('should take schemaDelimiter into account if applicable', function() { var test = 0; var UserSpecialUnderscore = this.sequelize.define('UserSpecialUnderscore', {age: Sequelize.INTEGER}, {schema: 'hello', schemaDelimiter: '_'}); var UserSpecialDblUnderscore = this.sequelize.define('UserSpecialDblUnderscore', {age: Sequelize.INTEGER}); return UserSpecialUnderscore.sync({force: true}).then(function(User) { return UserSpecialDblUnderscore.schema('hello', '__').sync({force: true}).then(function(DblUser) { return DblUser.create({age: 3}, { logging: function (sql) { expect(sql).to.exist; test++; expect(sql.indexOf('INSERT INTO `hello__UserSpecialDblUnderscores`')).to.be.above(-1); } }).then(function() { return User.create({age: 3}, { logging: function (sql) { expect(sql).to.exist; test++; expect(sql.indexOf('INSERT INTO `hello_UserSpecialUnderscores`')).to.be.above(-1); } }); }); }).then(function() { expect(test).to.equal(2); }); }); }); } it('should describeTable using the default schema settings', function() { var self = this , UserPublic = this.sequelize.define('Public', { username: Sequelize.STRING }) , count = 0; return UserPublic.sync({ force: true }).then(function() { return UserPublic.schema('special').sync({ force: true }).then(function() { return self.sequelize.queryInterface.describeTable('Publics', { logging: function(sql) { if (dialect === 'sqlite' || dialect === 'mysql' || dialect === 'mssql') { expect(sql).to.not.contain('special'); count++; } } }).then(function(table) { if (dialect === 'postgres') { expect(table.id.defaultValue).to.not.contain('special'); count++; } return self.sequelize.queryInterface.describeTable('Publics', { schema: 'special', logging: function(sql) { if (dialect === 'sqlite' || dialect === 'mysql' || dialect === 'mssql') { expect(sql).to.contain('special'); count++; } } }).then(function(table) { if (dialect === 'postgres') { expect(table.id.defaultValue).to.contain('special'); count++; } }); }).then(function() { expect(count).to.equal(2); }); }); }); }); it('should be able to reference a table with a schema set', function() { var self = this; var UserPub = this.sequelize.define('UserPub', { username: Sequelize.STRING }, { schema: 'prefix' }); var ItemPub = this.sequelize.define('ItemPub', { name: Sequelize.STRING }, { schema: 'prefix' }); UserPub.hasMany(ItemPub, { foreignKeyConstraint: true }); var run = function() { return UserPub.sync({ force: true }).then(function() { return ItemPub.sync({ force: true, logging: _.after(2, _.once(function(sql) { if (dialect === 'postgres') { expect(sql).to.match(/REFERENCES\s+"prefix"\."UserPubs" \("id"\)/); } else if (dialect === 'mssql') { expect(sql).to.match(/REFERENCES\s+\[prefix\]\.\[UserPubs\] \(\[id\]\)/); } else { expect(sql).to.match(/REFERENCES\s+`prefix\.UserPubs` \(`id`\)/); } }))}); }); }; if (dialect === 'postgres') { return this.sequelize.queryInterface.dropAllSchemas().then(function() { return self.sequelize.queryInterface.createSchema('prefix').then(function() { return run.call(self); }); }); } else { return run.call(self); } }); it('should be able to create and update records under any valid schematic', function() { var self = this; var logged = 0; return self.UserPublic.sync({ force: true }).then(function(UserPublicSync) { return UserPublicSync.create({age: 3}, { logging: function(UserPublic) { logged++; if (dialect === 'postgres') { expect(self.UserSpecialSync.getTableName().toString()).to.equal('"special"."UserSpecials"'); expect(UserPublic.indexOf('INSERT INTO "UserPublics"')).to.be.above(-1); } else if (dialect === 'sqlite') { expect(self.UserSpecialSync.getTableName().toString()).to.equal('`special.UserSpecials`'); expect(UserPublic.indexOf('INSERT INTO `UserPublics`')).to.be.above(-1); } else if (dialect === 'mssql') { expect(self.UserSpecialSync.getTableName().toString()).to.equal('[special].[UserSpecials]'); expect(UserPublic.indexOf('INSERT INTO [UserPublics]')).to.be.above(-1); } else { expect(self.UserSpecialSync.getTableName().toString()).to.equal('`special.UserSpecials`'); expect(UserPublic.indexOf('INSERT INTO `UserPublics`')).to.be.above(-1); } } }).then(function(UserPublic) { return self.UserSpecialSync.schema('special').create({age: 3}, { logging: function(UserSpecial) { logged++; if (dialect === 'postgres') { expect(UserSpecial.indexOf('INSERT INTO "special"."UserSpecials"')).to.be.above(-1); } else if (dialect === 'sqlite') { expect(UserSpecial.indexOf('INSERT INTO `special.UserSpecials`')).to.be.above(-1); } else if (dialect === 'mssql') { expect(UserSpecial.indexOf('INSERT INTO [special].[UserSpecials]')).to.be.above(-1); } else { expect(UserSpecial.indexOf('INSERT INTO `special.UserSpecials`')).to.be.above(-1); } } }).then(function(UserSpecial) { return UserSpecial.updateAttributes({age: 5}, { logging: function(user) { logged++; if (dialect === 'postgres') { expect(user.indexOf('UPDATE "special"."UserSpecials"')).to.be.above(-1); } else if (dialect === 'mssql') { expect(user.indexOf('UPDATE [special].[UserSpecials]')).to.be.above(-1); } else { expect(user.indexOf('UPDATE `special.UserSpecials`')).to.be.above(-1); } } }); }); }).then(function() { expect(logged).to.equal(3); }); }); }); }); describe('references', function() { beforeEach(function() { var self = this; this.Author = this.sequelize.define('author', { firstName: Sequelize.STRING }); return this.sequelize.getQueryInterface().dropTable('posts', { force: true }).then(function() { return self.sequelize.getQueryInterface().dropTable('authors', { force: true }); }).then(function() { return self.Author.sync(); }); }); it('uses an existing dao factory and references the author table', function() { var authorIdColumn = { type: Sequelize.INTEGER, references: { model: this.Author, key: 'id' } }; var Post = this.sequelize.define('post', { title: Sequelize.STRING, authorId: authorIdColumn }); this.Author.hasMany(Post); Post.belongsTo(this.Author); // The posts table gets dropped in the before filter. return Post.sync({logging: _.once(function(sql) { if (dialect === 'postgres') { expect(sql).to.match(/"authorId" INTEGER REFERENCES "authors" \("id"\)/); } else if (dialect === 'mysql') { expect(sql).to.match(/FOREIGN KEY \(`authorId`\) REFERENCES `authors` \(`id`\)/); } else if (dialect === 'mssql') { expect(sql).to.match(/FOREIGN KEY \(\[authorId\]\) REFERENCES \[authors\] \(\[id\]\)/); } else if (dialect === 'sqlite') { expect(sql).to.match(/`authorId` INTEGER REFERENCES `authors` \(`id`\)/); } else { throw new Error('Undefined dialect!'); } })}); }); it('uses a table name as a string and references the author table', function() { var authorIdColumn = { type: Sequelize.INTEGER, references: { model: 'authors', key: 'id' } }; var self = this , Post = self.sequelize.define('post', { title: Sequelize.STRING, authorId: authorIdColumn }); this.Author.hasMany(Post); Post.belongsTo(this.Author); // The posts table gets dropped in the before filter. return Post.sync({logging: _.once(function(sql) { if (dialect === 'postgres') { expect(sql).to.match(/"authorId" INTEGER REFERENCES "authors" \("id"\)/); } else if (dialect === 'mysql') { expect(sql).to.match(/FOREIGN KEY \(`authorId`\) REFERENCES `authors` \(`id`\)/); } else if (dialect === 'sqlite') { expect(sql).to.match(/`authorId` INTEGER REFERENCES `authors` \(`id`\)/); } else if (dialect === 'mssql') { expect(sql).to.match(/FOREIGN KEY \(\[authorId\]\) REFERENCES \[authors\] \(\[id\]\)/); } else { throw new Error('Undefined dialect!'); } })}); }); it('emits an error event as the referenced table name is invalid', function() { var authorIdColumn = { type: Sequelize.INTEGER, references: { model: '4uth0r5', key: 'id' } }; var Post = this.sequelize.define('post', { title: Sequelize.STRING, authorId: authorIdColumn }); this.Author.hasMany(Post); Post.belongsTo(this.Author); // The posts table gets dropped in the before filter. return Post.sync().then(function() { if (dialect === 'sqlite') { // sorry ... but sqlite is too stupid to understand whats going on ... expect(1).to.equal(1); } else { // the parser should not end up here ... expect(2).to.equal(1); } return; }).catch (function(err) { if (dialect === 'mysql') { expect(err.message).to.match(/Can\'t create table/); } else if (dialect === 'sqlite') { // the parser should not end up here ... see above expect(1).to.equal(2); } else if (dialect === 'postgres') { expect(err.message).to.match(/relation "4uth0r5" does not exist/); } else if (dialect === 'mssql') { expect(err.message).to.match(/Could not create constraint/); } else { throw new Error('Undefined dialect!'); } }); }); it('works with comments', function() { // Test for a case where the comment was being moved to the end of the table when there was also a reference on the column, see #1521 // jshint ignore:start var Member = this.sequelize.define('Member', {}); var idColumn = { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: false, comment: 'asdf' }; idColumn.references = { model: Member, key: 'id' }; var Profile = this.sequelize.define('Profile', { id: idColumn }); // jshint ignore:end return this.sequelize.sync({ force: true }); }); }); describe('blob', function() { beforeEach(function() { this.BlobUser = this.sequelize.define('blobUser', { data: Sequelize.BLOB }); return this.BlobUser.sync({ force: true }); }); describe('buffers', function() { it('should be able to take a buffer as parameter to a BLOB field', function() { return this.BlobUser.create({ data: new Buffer('Sequelize') }).then(function(user) { expect(user).to.be.ok; }); }); it('should return a buffer when fetching a blob', function() { var self = this; return this.BlobUser.create({ data: new Buffer('Sequelize') }).then(function(user) { return self.BlobUser.findById(user.id).then(function(user) { expect(user.data).to.be.an.instanceOf(Buffer); expect(user.data.toString()).to.have.string('Sequelize'); }); }); }); it('should work when the database returns null', function() { var self = this; return this.BlobUser.create({ // create a null column }).then(function(user) { return self.BlobUser.findById(user.id).then(function(user) { expect(user.data).to.be.null; }); }); }); }); if (dialect !== 'mssql') { // NOTE: someone remember to inform me about the intent of these tests. Are // you saying that data passed in as a string is automatically converted // to binary? i.e. "Sequelize" is CAST as binary, OR that actual binary // data is passed in, in string form? Very unclear, and very different. describe('strings', function() { it('should be able to take a string as parameter to a BLOB field', function() { return this.BlobUser.create({ data: 'Sequelize' }).then(function(user) { expect(user).to.be.ok; }); }); it('should return a buffer when fetching a BLOB, even when the BLOB was inserted as a string', function() { var self = this; return this.BlobUser.create({ data: 'Sequelize' }).then(function(user) { return self.BlobUser.findById(user.id).then(function(user) { expect(user.data).to.be.an.instanceOf(Buffer); expect(user.data.toString()).to.have.string('Sequelize'); }); }); }); }); } }); describe('paranoid is true and where is an array', function() { beforeEach(function() { this.User = this.sequelize.define('User', {username: DataTypes.STRING }, { paranoid: true }); this.Project = this.sequelize.define('Project', { title: DataTypes.STRING }, { paranoid: true }); this.Project.belongsToMany(this.User, {through: 'project_user'}); this.User.belongsToMany(this.Project, {through: 'project_user'}); var self = this; return this.sequelize.sync({ force: true }).then(function() { return self.User.bulkCreate([{ username: 'leia' }, { username: 'luke' }, { username: 'vader' }]).then(function() { return self.Project.bulkCreate([{ title: 'republic' },{ title: 'empire' }]).then(function() { return self.User.findAll().then(function(users) { return self.Project.findAll().then(function(projects) { var leia = users[0] , luke = users[1] , vader = users[2] , republic = projects[0] , empire = projects[1]; return leia.setProjects([republic]).then(function() { return luke.setProjects([republic]).then(function() { return vader.setProjects([empire]).then(function() { return leia.destroy(); }); }); }); }); }); }); }); }); }); it('should not fail when array contains Sequelize.or / and', function() { return this.User.findAll({ where: [ this.sequelize.or({ username: 'vader' }, { username: 'luke' }), this.sequelize.and({ id: [1, 2, 3] }) ] }) .then(function(res) { expect(res).to.have.length(2); }); }); it('should not fail with an include', function() { return this.User.findAll({ where: [ this.sequelize.queryInterface.QueryGenerator.quoteIdentifiers('Projects.title') + ' = ' + this.sequelize.queryInterface.QueryGenerator.escape('republic') ], include: [ {model: this.Project} ] }).then(function(users) { expect(users.length).to.be.equal(1); expect(users[0].username).to.be.equal('luke'); }); }); it('should not overwrite a specified deletedAt by setting paranoid: false', function() { var tableName = ''; if (this.User.name) { tableName = this.sequelize.queryInterface.QueryGenerator.quoteIdentifier(this.User.name) + '.'; } return this.User.findAll({ paranoid: false, where: [ tableName + this.sequelize.queryInterface.QueryGenerator.quoteIdentifier('deletedAt') + ' IS NOT NULL ' ], include: [ {model: this.Project} ] }).then(function(users) { expect(users.length).to.be.equal(1); expect(users[0].username).to.be.equal('leia'); }); }); it('should not overwrite a specified deletedAt (complex query) by setting paranoid: false', function() { return this.User.findAll({ paranoid: false, where: [ this.sequelize.or({ username: 'leia' }, { username: 'luke' }), this.sequelize.and( { id: [1, 2, 3] }, this.sequelize.or({ deletedAt: null }, { deletedAt: { gt: new Date(0) } }) ) ] }) .then(function(res) { expect(res).to.have.length(2); }); }); }); if (dialect !== 'sqlite' && current.dialect.supports.transactions) { it('supports multiple async transactions', function() { this.timeout(90000); var self = this; return Support.prepareTransactionTest(this.sequelize).bind({}).then(function(sequelize) { var User = sequelize.define('User', { username: Sequelize.STRING }); var testAsync = function() { return sequelize.transaction().then(function(t) { return User.create({ username: 'foo' }, { transaction: t }).then(function() { return User.findAll({ where: { username: 'foo' } }).then(function(users) { expect(users).to.have.length(0); }); }).then(function() { return User.findAll({ where: { username: 'foo' }, transaction: t }).then(function(users) { expect(users).to.have.length(1); }); }).then(function() { return t; }); }).then(function(t) { return t.rollback(); }); }; return User.sync({ force: true }).then(function() { var tasks = []; for (var i = 0; i < 1000; i++) { tasks.push(testAsync.bind(this)); } return self.sequelize.Promise.resolve(tasks).map(function(entry) { return entry(); }, { // Needs to be one less than ??? else the non transaction query won't ever get a connection concurrency: (sequelize.config.pool && sequelize.config.pool.max || 5) - 1 }); }); }); }); } describe('Unique', function() { it('should set unique when unique is true', function() { var self = this; var uniqueTrue = self.sequelize.define('uniqueTrue', { str: { type: Sequelize.STRING, unique: true } }); return uniqueTrue.sync({force: true, logging: _.after(2, _.once(function(s) { expect(s).to.match(/UNIQUE/); }))}); }); it('should not set unique when unique is false', function() { var self = this; var uniqueFalse = self.sequelize.define('uniqueFalse', { str: { type: Sequelize.STRING, unique: false } }); return uniqueFalse.sync({force: true, logging: _.after(2, _.once(function(s) { expect(s).not.to.match(/UNIQUE/); }))}); }); it('should not set unique when unique is unset', function() { var self = this; var uniqueUnset = self.sequelize.define('uniqueUnset', { str: { type: Sequelize.STRING } }); return uniqueUnset.sync({force: true, logging: _.after(2, _.once(function(s) { expect(s).not.to.match(/UNIQUE/); }))}); }); }); it('should be possible to use a key named UUID as foreign key', function() { // jshint ignore:start var project = this.sequelize.define('project', { UserId: { type: Sequelize.STRING, references: { model: 'Users', key: 'UUID' } } }); var user = this.sequelize.define('Users', { UUID: { type: Sequelize.STRING, primaryKey: true, unique: true, allowNull: false, validate: { notNull: true, notEmpty: true } } }); // jshint ignore:end return this.sequelize.sync({force: true}); }); describe('bulkCreate errors', function() { it('should return array of errors if validate and individualHooks are true', function() { var data = [{ username: null }, { username: null }, { username: null }]; var user = this.sequelize.define('Users', { username: { type: Sequelize.STRING, allowNull: false, validate: { notNull: true, notEmpty: true } } }); return expect(user.bulkCreate(data, { validate: true, individualHooks: true })).to.be.rejectedWith(Promise.AggregateError); }); }); });
(function($){ // Caption $('.entry').each(function(i){ $(this).find('img').each(function(){ if (!$(this).parent().is("a")) { var alt = this.alt, title = this.title; var caption = title ? title : alt; if (caption){ $(this).after('<div class="caption"><i class="fa fa-picture-o"></i>' + caption + '</div>'); } $(this).wrap('<a href="' + this.src + '" title="' + caption + '" class="fancybox" rel="gallery' + i + '" />'); } }); }); // Gallery var play = function(parent, item, callback){ var width = parent.width(); item.imagesLoaded(function(){ var _this = this[0], nWidth = _this.naturalWidth, nHeight = _this.naturalHeight; callback(); this.animate({opacity: 1}, 500); parent.animate({height: width * nHeight / nWidth}, 500); }); }; $('.gallery').each(function(){ var $this = $(this), current = 0, photoset = $this.children('.photoset').children(), all = photoset.length, loading = true; play($this, photoset.eq(0), function(){ loading = false; }); $this.on('click', '.prev', function(){ if (!loading){ var next = (current - 1) % all; loading = true; play($this, photoset.eq(next), function(){ photoset.eq(current).animate({opacity: 0}, 500); loading = false; current = next; }); } }).on('click', '.next', function(){ if (!loading){ var next = (current + 1) % all; loading = true; play($this, photoset.eq(next), function(){ photoset.eq(current).animate({opacity: 0}, 500); loading = false; current = next; }); } }); }); })(jQuery);
/** * E2D Engine v1.0.6 * @author Jack Dalton <jack@jackdalton.org> * Copyright © 2015 Jack Dalton under the MIT license (https://opensource.org/licenses/MIT) **/ "use strict"; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var E2D = { VERSION: "1.0.6" }; E2D.Scene = (function () { /** * @param {Object} options - Scene options * @param {boolean} options.logging - Whether or not to log things. * @param {int} options.idLength - Default ID length for objects. */ function Scene(options) { options = options || {}; this._options = {}; this._options.logging = options.logging || true; this._options.idLength = options.idLength || 16; if (this._options.logging) { console.log("E2D v" + E2D.VERSION); } this._ids = {}; this._objects = {}; this._disabledObjects = {}; this._custom = options.custom || {}; this._extensions = {}; } Scene.prototype.render = function () { var self = this; var queue = []; for (var i in self._objects) { queue.push(self._objects[i]); } queue.sort(function (a, b) { return a._layer - b._layer; }); for (i = 0; i < queue.length; i++) { queue[i].render(); } }; Scene.prototype._updateExtensions = function () { var self = this; for (var i in self._extensions) { self._extensions[i].fn(); } }; return Scene; })(); /** * @constructor * @param {number} x - Vector x coordinate * @param {number} y - Vector y coordinate * @returns {object} pos - Position ({x: x, y: y}) */ E2D.Scene.prototype.Vector2 = (function () { var Vector2 = (function () { function Vector2(x, y) { _classCallCheck(this, Vector2); this.x = typeof x == "number" ? x : 0; this.y = typeof y == "number" ? y : 0; } _createClass(Vector2, [{ key: "getPos", value: function getPos() { return this; } }, { key: "getX", value: function getX() { return this.x; } }, { key: "getY", value: function getY() { return this.y; } }, { key: "setPos", value: function setPos(pos) { this.x = typeof pos.x == "number" ? pos.x : this.x; this.y = typeof pos.y == "number" ? pos.y : this.y; } }, { key: "setX", value: function setX(x) { this.x = typeof x == "number" ? x : this.x; } }, { key: "setY", value: function setY(y) { this.y = typeof y == "number" ? y : this.y; } }, { key: "distanceTo", value: function distanceTo(pos) { return Math.sqrt(Math.pow(pos.x - this.x, 2) + Math.pow(pos.y - this.y, 2)); } }, { key: "midpoint", value: function midpoint(pos) { return new Vector2((this.x + pos.x) / 2, (this.y + pos.y) / 2); } }, { key: "translate", value: function translate(to) { if (arguments.length == 2) { this.x += typeof arguments[0] == "number" ? arguments[0] : 0; this.y += typeof arguments[1] == "number" ? arguments[1] : 0; } else if (to instanceof Vector2) { this.x += to.x || 0; this.y += to.y || 0; } return { x: this.x, y: this.y }; } }]); return Vector2; })(); return Vector2; })(); /** * @param {int} length - Length of ID to generate; default is 16 characters. * @returns {string} id - Random ID to be used with anything. */ E2D.Scene.prototype.generateId = function (length) { var self = this; length = length || self._options.idLength; var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ$_", id = ""; for (var i = 0; i < length; i++) { id += chars[Math.floor(Math.random() * chars.length)]; } return id; }; /** * @param {Object} options - The object's options. * @param {Object} options.pos - The object's position. * @param {int} options.pos.x - The object's X coordinate. * @param {int} options.pos.y - The object's Y coordinate. * @param {function} options.renderer - Function to be called on object.render. The object is passed as a parameter when called. * @param {int} options.layer - Rendering priority/layer -- Lower layer is rendered first */ E2D.Scene.prototype.addObject = function (options) { var self = this; options.pos = options.pos || {}; if (typeof options == "undefined") { options = { pos: new self.Vector2(0, 0) }; } else { if (typeof options.pos.x != "number" || typeof options.pos.y != "number") { if (self._options.logging) console.warn("Invalid position supplied. Using (0, 0) (@addObject)"); } } var obj = {}; obj.id = options.id || self.generateId(); obj.body = { pos: options.pos }; if (typeof options.custom != "undefined") { obj.custom = options.custom; } if (typeof options.renderer == "function") { obj._renderer = options.renderer; obj.render = function () { obj._renderer(obj, arguments); }; obj._layer = options.layer || 0; } self._objects[obj.id] = obj; self._updateExtensions(); return obj; }; /** * @param {string} id - ID of object to destroy. * @returns {boolean} status - Whether the object was deleted. */ E2D.Scene.prototype.destroyObject = function (id) { var self = this; if (typeof self._objects[id] == "undefined") { if (self._options.logging) console.warn(id + " either doesn't exist, or hasn't been added to the scene. Object was not destroyed (@destroyObject)"); return false; } delete self._objects[id]; self._updateExtensions(); return true; }; /** * @param {string} id - ID of object to enable * @returns {boolean} success - Whether or not the object was enabled. */ E2D.Scene.prototype.enableObject = function (id) { var self = this; if (typeof self._disabledObjects[id] == "undefined") { if (self._options.logging) console.warn(id + " either doesn't exist, hasn't been disabled, or hasn't been added to the scene. Object was not enabled (@enableObject)"); return false; } self._objects[id] = self._disabledObjects[id]; delete self._disabledObjects[id]; self._updateExtensions(); return true; }; /** * @param {string} id - ID of object to disable * @returns {boolean} success - Whether or not the object was disabled. */ E2D.Scene.prototype.disableObject = function (id) { var self = this; if (typeof self._objects[id] == "undefined") { if (self._options.logging) console.warn(id + " either doesn't exist, or hasn't been added to the scene. Object was not disabled (@disableObject)"); return false; } self._disabledObjects[id] = self._objects[id]; self.destroyObject(id); self._updateExtensions(); return true; }; /** * Register an E2D extension. * * @param {Object} options - An object containing options for the new extension. * @param {string} options.title - Title of the new extension. * @param {string} options.id - ID of the new extension. Randomly generated if not included. * @param {function} options.fn - Function to be executed on scene runtime. The scene is passed as a parameter. * @returns {string} ext.id - ID of the registered extension. */ E2D.Scene.prototype.registerExtension = function (options) { var self = this; var Extension = function Extension(options) { _classCallCheck(this, Extension); options = options || {}; this.title = options.title || "Untitled Extension " + self.generateId(); this.id = options.id || "ext" + self.generateId(); this.fn = function () { options.fn(self); }; if (typeof options.fn == "undefined") { if (self._options.logging) console.warn("No function provided with " + this.title + ", using an empty function (@registerExtension)."); this.fn = function () {}; } }; var ext = new Extension(options); self._extensions[ext.id] = ext; self._updateExtensions(); return ext.id; }; typeof module !== "undefined" ? module.exports = E2D : window.E2D = E2D;
export default function Home() { return __jsx("h1", null, "Hello World!"); }
const DrawCard = require('../../drawcard.js'); class LittleBird extends DrawCard { setupCardAbilities(ability) { this.whileAttached({ effect: ability.effects.addIcon('intrigue') }); } } LittleBird.code = '01034'; module.exports = LittleBird;
Template.layout.events({ 'click #content, click aside': function(e) { Aside.hide(); hideBalloons(); } });
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'flash', 'fa', { access: 'دسترسی به اسکریپت', accessAlways: 'همیشه', accessNever: 'هرگز', accessSameDomain: 'همان دامنه', alignAbsBottom: 'پائین مطلق', alignAbsMiddle: 'وسط مطلق', alignBaseline: 'خط پایه', alignTextTop: 'متن بالا', bgcolor: 'رنگ پس​زمینه', chkFull: 'اجازه تمام صفحه', chkLoop: 'اجرای پیاپی', chkMenu: 'در دسترس بودن منوی فلش', chkPlay: 'آغاز خودکار', flashvars: 'مقادیر برای فلش', hSpace: 'فاصلهٴ افقی', properties: 'ویژگی​های فلش', propertiesTab: 'ویژگی​ها', quality: 'کیفیت', qualityAutoHigh: 'بالا - خودکار', qualityAutoLow: 'پایین - خودکار', qualityBest: 'بهترین', qualityHigh: 'بالا', qualityLow: 'پایین', qualityMedium: 'متوسط', scale: 'مقیاس', scaleAll: 'نمایش همه', scaleFit: 'جایگیری کامل', scaleNoBorder: 'بدون کران', title: 'ویژگی​های فلش', vSpace: 'فاصلهٴ عمودی', validateHSpace: 'مقدار فاصله گذاری افقی باید یک عدد باشد.', validateSrc: 'لطفا URL پیوند را بنویسید', validateVSpace: 'مقدار فاصله گذاری عمودی باید یک عدد باشد.', windowMode: 'حالت پنجره', windowModeOpaque: 'مات', windowModeTransparent: 'شفاف', windowModeWindow: 'پنجره' });
'use strict'; define('forum/topic', [ 'forum/infinitescroll', 'forum/topic/threadTools', 'forum/topic/postTools', 'forum/topic/events', 'forum/topic/posts', 'forum/topic/images', 'forum/topic/replies', 'navigator', 'sort', 'components', 'storage', ], function (infinitescroll, threadTools, postTools, events, posts, images, replies, navigator, sort, components, storage) { var Topic = {}; var currentUrl = ''; $(window).on('action:ajaxify.start', function (ev, data) { if (Topic.replaceURLTimeout) { clearTimeout(Topic.replaceURLTimeout); Topic.replaceURLTimeout = 0; } if (!String(data.url).startsWith('topic/')) { navigator.disable(); components.get('navbar/title').find('span').text('').hide(); app.removeAlert('bookmark'); events.removeListeners(); $(window).off('keydown', onKeyDown); require(['search'], function (search) { if (search.topicDOM.active) { search.topicDOM.end(); } }); } }); Topic.init = function () { var tid = ajaxify.data.tid; $(window).trigger('action:topic.loading'); app.enterRoom('topic_' + tid); posts.processPage(components.get('post')); postTools.init(tid); threadTools.init(tid); replies.init(tid); events.init(); sort.handleSort('topicPostSort', 'user.setTopicSort', 'topic/' + ajaxify.data.slug); if (!config.usePagination) { infinitescroll.init($('[component="topic"]'), posts.loadMorePosts); } addBlockQuoteHandler(); addParentHandler(); handleKeys(); navigator.init('[component="post"]', ajaxify.data.postcount, Topic.toTop, Topic.toBottom, Topic.navigatorCallback, Topic.calculateIndex); handleBookmark(tid); $(window).on('scroll', updateTopicTitle); handleTopicSearch(); $(window).trigger('action:topic.loaded', ajaxify.data); }; function handleKeys() { if (!config.usePagination) { $(window).off('keydown', onKeyDown).on('keydown', onKeyDown); } } function onKeyDown(ev) { if (ev.target.nodeName === 'BODY') { if (ev.shiftKey || ev.ctrlKey || ev.altKey) { return; } if (ev.which === 36) { // home key Topic.toTop(); return false; } else if (ev.which === 35) { // end key Topic.toBottom(); return false; } } } function handleTopicSearch() { require(['search', 'mousetrap'], function (search, mousetrap) { $('.topic-search').off('click') .on('click', '.prev', function () { search.topicDOM.prev(); }) .on('click', '.next', function () { search.topicDOM.next(); }); mousetrap.bind('ctrl+f', function (e) { if (config.topicSearchEnabled) { // If in topic, open search window and populate, otherwise regular behaviour var match = ajaxify.currentPage.match(/^topic\/([\d]+)/); var tid; if (match) { e.preventDefault(); tid = match[1]; $('#search-fields input').val('in:topic-' + tid + ' '); app.prepareSearch(); } } }); }); } Topic.toTop = function () { navigator.scrollTop(0); }; Topic.toBottom = function () { socket.emit('topics.postcount', ajaxify.data.tid, function (err, postCount) { if (err) { return app.alertError(err.message); } if (config.topicPostSort !== 'oldest_to_newest') { postCount = 2; } navigator.scrollBottom(postCount - 1); }); }; function handleBookmark(tid) { // use the user's bookmark data if available, fallback to local if available var bookmark = ajaxify.data.bookmark || storage.getItem('topic:' + tid + ':bookmark'); var postIndex = ajaxify.data.postIndex; if (postIndex > 0) { if (components.get('post/anchor', postIndex - 1).length) { return navigator.scrollToPostIndex(postIndex - 1, true, 0); } } else if (bookmark && (!config.usePagination || (config.usePagination && ajaxify.data.pagination.currentPage === 1)) && ajaxify.data.postcount > ajaxify.data.bookmarkThreshold) { app.alert({ alert_id: 'bookmark', message: '[[topic:bookmark_instructions]]', timeout: 0, type: 'info', clickfn: function () { navigator.scrollToIndex(parseInt(bookmark - 1, 10), true); }, closefn: function () { storage.removeItem('topic:' + tid + ':bookmark'); }, }); setTimeout(function () { app.removeAlert('bookmark'); }, 10000); } } function addBlockQuoteHandler() { components.get('topic').on('click', 'blockquote .toggle', function () { var blockQuote = $(this).parent('blockquote'); var toggle = $(this); blockQuote.toggleClass('uncollapsed'); var collapsed = !blockQuote.hasClass('uncollapsed'); toggle.toggleClass('fa-angle-down', collapsed).toggleClass('fa-angle-up', !collapsed); }); } function addParentHandler() { components.get('topic').on('click', '[component="post/parent"]', function (e) { var toPid = $(this).attr('data-topid'); var toPost = $('[component="post"][data-pid="' + toPid + '"]'); if (toPost.length) { e.preventDefault(); navigator.scrollToIndex(toPost.attr('data-index'), true); return false; } }); } function updateTopicTitle() { var span = components.get('navbar/title').find('span'); if ($(window).scrollTop() > 50 && span.hasClass('hidden')) { span.html(ajaxify.data.title).removeClass('hidden'); } else if ($(window).scrollTop() <= 50 && !span.hasClass('hidden')) { span.html('').addClass('hidden'); } if ($(window).scrollTop() > 300) { app.removeAlert('bookmark'); } } Topic.calculateIndex = function (index, elementCount) { if (index !== 1 && config.topicPostSort !== 'oldest_to_newest') { return elementCount - index + 2; } return index; }; Topic.navigatorCallback = function (index, elementCount, threshold) { var path = ajaxify.removeRelativePath(window.location.pathname.slice(1)); if (!path.startsWith('topic')) { return; } if (navigator.scrollActive) { return; } images.loadImages(threshold); var newUrl = 'topic/' + ajaxify.data.slug + (index > 1 ? ('/' + index) : ''); if (newUrl !== currentUrl) { if (Topic.replaceURLTimeout) { clearTimeout(Topic.replaceURLTimeout); } Topic.replaceURLTimeout = setTimeout(function () { if (index >= elementCount && app.user.uid) { socket.emit('topics.markAsRead', [ajaxify.data.tid]); } updateUserBookmark(index); Topic.replaceURLTimeout = 0; if (history.replaceState) { var search = window.location.search || ''; if (!config.usePagination) { search = (search && !/^\?page=\d+$/.test(search) ? search : ''); } history.replaceState({ url: newUrl + search, }, null, window.location.protocol + '//' + window.location.host + RELATIVE_PATH + '/' + newUrl + search); } currentUrl = newUrl; }, 500); } }; function updateUserBookmark(index) { var bookmarkKey = 'topic:' + ajaxify.data.tid + ':bookmark'; var currentBookmark = ajaxify.data.bookmark || storage.getItem(bookmarkKey); if (ajaxify.data.postcount > ajaxify.data.bookmarkThreshold && (!currentBookmark || parseInt(index, 10) > parseInt(currentBookmark, 10))) { if (app.user.uid) { socket.emit('topics.bookmark', { tid: ajaxify.data.tid, index: index, }, function (err) { if (err) { return app.alertError(err.message); } ajaxify.data.bookmark = index; }); } else { storage.setItem(bookmarkKey, index); } } // removes the bookmark alert when we get to / past the bookmark if (!currentBookmark || parseInt(index, 10) >= parseInt(currentBookmark, 10)) { app.removeAlert('bookmark'); } } return Topic; });
'use strict'; (function (scope) { /** * Dots input component * * @class MusicDotsInputComponent * @extends AbstractMusicInputComponent * @constructor */ function MusicDotsInputComponent(obj) { scope.AbstractMusicInputComponent.call(this, obj); this.type = 'dots'; if (obj) { if (obj.value) { this.value = obj.value; } } } /** * Inheritance property */ MusicDotsInputComponent.prototype = new scope.AbstractMusicInputComponent(); /** * Constructor property */ MusicDotsInputComponent.prototype.constructor = MusicDotsInputComponent; /** * Get dots input component value * * @method getValue * @returns {String} */ MusicDotsInputComponent.prototype.getValue = function () { return this.value; }; /** * Set dots input component value * * @method setValue * @param {String} value */ MusicDotsInputComponent.prototype.setValue = function (value) { this.value = value; }; // Export scope.MusicDotsInputComponent = MusicDotsInputComponent; })(MyScript);
class Animal { sayHi() { return 'I am an animal.' } sayOther() { return 'WAT?!'; } } class Horse extends Animal { sayHi() { return super.sayOther(); } sayOther() { return 'I see dead objects.'; } } expect(new Horse().sayHi()).toBe('WAT?!');
import { OFFLINE_STATUS_CHANGED, OFFLINE_SCHEDULE_RETRY, OFFLINE_COMPLETE_RETRY, OFFLINE_BUSY } from './constants'; export const networkStatusChanged = online => ({ type: OFFLINE_STATUS_CHANGED, payload: { online } }); export const scheduleRetry = (delay = 0) => ({ type: OFFLINE_SCHEDULE_RETRY, payload: { delay } }); export const completeRetry = (action, retryToken) => ({ type: OFFLINE_COMPLETE_RETRY, payload: action, meta: { retryToken } }); export const busy = isBusy => ({ type: OFFLINE_BUSY, payload: { busy: isBusy } });
/** * @fileoverview Rule to flag when using constructor for wrapper objects * @author Ilya Volodin */ "use strict"; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { docs: { description: "disallow `new` operators with the `String`, `Number`, and `Boolean` objects", category: "Best Practices", recommended: false }, schema: [] }, create: function(context) { return { NewExpression: function(node) { const wrapperObjects = ["String", "Number", "Boolean", "Math", "JSON"]; if (wrapperObjects.indexOf(node.callee.name) > -1) { context.report(node, "Do not use {{fn}} as a constructor.", { fn: node.callee.name }); } } }; } };
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ import {hydrateRoot} from 'react-dom'; import App from './App'; hydrateRoot(document, <App assets={window.assetManifest} />);
import { RECEIVE_USER_PROFILE_STATS } from '../constants'; const initialState = { stats: {}, isLoading: true }; export default function userProfile(state = initialState, action) { switch (action.type) { case RECEIVE_USER_PROFILE_STATS: return { stats: action.data, isLoading: false }; default: return state; } }
var cadpat; (function (cadpat) { 'use strict'; angular.module('cadpat') .config(config); config.$inject = ['$routeProvider', '$locationProvider']; function config($routeProvider, $locationProvider) { $locationProvider.html5Mode(true); $routeProvider .when('/bens', { template: '<home-bens></home-bens>' }) .when('/bens/incluir', { templateUrl: 'app_ts/bem/bem-mantem.html', controller: 'IncluirController', controllerAs: 'vm' }) .when('/bens/alterar/:id', { templateUrl: 'app_ts/bem/bem-mantem.html', controller: 'AlterarController', controllerAs: 'vm' }) .when('/bens/:id', { templateUrl: 'app_ts/bem/bem-detalhe.html', controller: 'DetalheController', controllerAs: 'vm' }) .otherwise({ redirectTo: '/bens' }); } })(cadpat || (cadpat = {}));
/** * Created by Peter on 2017. 10. 15.. */ "use strict"; var async = require('async'); var modelKmaTownMidForecast = require('../../models/kma/kma.town.mid.forecast.model.js'); var modelKmaTownMidLand = require('../../models/kma/kma.town.mid.land.model.js'); var modelKmaTownMidSea = require('../../models/kma/kma.town.mid.sea.model.js'); var modelKmaTownMidTemp = require('../../models/kma/kma.town.mid.temp.model.js'); var kmaTimelib = require('../../lib/kmaTimeLib'); var dbType = { modelMidForecast: modelKmaTownMidForecast, modelMidLand: modelKmaTownMidLand, modelMidSea: modelKmaTownMidSea, modelMidTemp: modelKmaTownMidTemp }; function kmaTownMidController(){ } kmaTownMidController.prototype.saveMid = function(type, newData, overwrite, callback){ var regId = ''; try{ var pubDate = kmaTimelib.getKoreaDateObj(newData.pubDate); log.verbose('KMA Town M> pubDate :', pubDate.toString()); if(newData.pointNumber !== undefined){ regId = newData.pointNumber; }else{ regId = newData.regId; } var db = dbType[type]; if(db == undefined){ var err = new Error('KMA Town M> saveMid : unknown db type : ' + type); log.error(err.message); return callback(err); } log.silly(JSON.stringify(newData)); async.waterfall([ function(cb){ var fcsDate = kmaTimelib.getKoreaDateObj(newData.date + newData.time); var newItem = {regId: regId, pubDate: pubDate, fcsDate: fcsDate, data: newData}; //log.info(JSON.stringify(newItem)); var query; if (overwrite) { query = {regId: regId}; } else { query = {regId: regId, pubDate: pubDate}; } db.update(query, newItem, {upsert:true}, function(err){ if(err){ log.error('KMA Town M> Fail to update Mid : '+ type + ' ID : ' + regId); log.info(JSON.stringify(newItem)); return cb(); } cb(); }); }], function (err) { log.debug('KMA Town M> finished to save town.mid : ', type); var fcsDate; if (overwrite) { fcsDate = pubDate; } else { fcsDate = kmaTimelib.getPast8DaysTime(pubDate); } /** * 불필요하게 중복해서 호출되고 있음. */ log.info('KMA Town M> remove '+ type + ' item before : ', fcsDate.toString()); db.remove({regId: regId, "fcsDate": {$lt:fcsDate}}).exec(); callback(err); } ); } catch (e) { return callback(e); } }; kmaTownMidController.prototype.getMidFromDB = function(type, indicator, req, callback) { try{ var db = dbType[type]; if(db == undefined){ log.error('KMA Town M> getMidFromDB : unknown db type : ', type); return callback(new Error('unknown db type '+type)); } if(req != undefined && req[type] != undefined){ log.debug('KMA Town M> return existed data : ', type, JSON.stringify(req[type])); return callback(null, req[type]); } db.find({regId : indicator}, {_id: 0}).limit(1).lean().exec(function(err, result){ if(err){ log.warn('KMA Town M> Fail to file&get mid data from DB ', {type:type, regId: indicator}); return callback(err); } if(result.length == 0){ err = new Error('KMA Town M> There are no mid datas from DB ' + JSON.stringify({type, indicator})); log.warn(err.message); return callback(err); } if(result.length > 1){ log.error('KMA Town M> _getMidDataFromDB : what happened?? ' + result.length + ' regId='+indicator); } log.silly('KMA Town M>', JSON.stringify(result[0])); if(callback){ var ret = []; var privateString = []; if(result[0].data.hasOwnProperty('wfsv')){ privateString = forecastString; } else if(result[0].data.hasOwnProperty('wh10B')){ privateString = seaString; } else if(result[0].data.hasOwnProperty('taMax10')){ privateString = tempString; } else if(result[0].data.hasOwnProperty('wf10')){ privateString = landString; } else { err = new Error('KMA Town M> ~> what is it???'+JSON.stringify(result[0].data)); log.error(err); return callback(err); } var newItem = {}; commonString.forEach(function(string){ newItem[string] = result[0].data[string]; }); privateString.forEach(function(string){ newItem[string] = result[0].data[string]; }); //log.info(newItem); ret.push(newItem); callback(null, {pubDate: result[0].pubDate, ret: ret}); } }); } catch (e) { return callback(e); } }; kmaTownMidController.prototype.checkPubDate = function(type, srcList, dateString, callback) { var pubDate = kmaTimelib.getKoreaDateObj(''+ dateString.date + dateString.time); log.info('KMA Town M> pubDate : ', pubDate.toString(), 'Type : ', type); try{ var db = dbType[type]; if(db == undefined) { var err = new Error('KMA Town M> check pub Date : unknown db type : ' + type); log.error(err); return callback(err); } async.mapSeries(srcList, function(src,cb){ db.find({regId: src.code}, {_id: 0, regId: 1, pubDate: 1}).sort({"pubDate":1}).lean().exec(function(err, dbList){ if(err){ log.info('KMA Town M> There is no data matched to : ', src); return cb(null, src); } for(var i=0 ; i<dbList.length ; i++){ if(dbList[i].pubDate.getTime() === pubDate.getTime()){ log.info('KMA Town M> Already updated : ', src, dateString, src.code); return cb(null); } } log.debug('KMA Town M> Need to update : ', src.code); cb(null, src); }); }, function(err, result){ result = result.filter(function(item){ if(item === undefined){ return false; } return true; }); log.info('KMA Town M> Count of the list for the updating : ', result.length); log.silly('KMA Town M> ', JSON.stringify(result)); return callback(null, result); } ); } catch(e){ return callback(e); } }; kmaTownMidController.prototype.checkForecastPubDate = function(model, srcList, dateString, callback) { return kmaTownMidController.prototype.checkPubDate('modelMidForecast', srcList, dateString, callback); }; kmaTownMidController.prototype.checkLandPubDate = function(model, srcList, dateString, callback) { return kmaTownMidController.prototype.checkPubDate('modelMidLand', srcList, dateString, callback); }; kmaTownMidController.prototype.checkSeaPubDate = function(model, srcList, dateString, callback) { return kmaTownMidController.prototype.checkPubDate('modelMidSea', srcList, dateString, callback); }; kmaTownMidController.prototype.checkTempPubDate = function(model, srcList, dateString, callback) { return kmaTownMidController.prototype.checkPubDate('modelMidTemp', srcList, dateString, callback); }; module.exports = kmaTownMidController;
// Opinion: I think it's gross to start written English sentences with "there (is|are)" // (most of the time) // this implementation is really naive var re = new RegExp('([^\n\\.;!?]+)([\\.;!?]+)', 'gi'); var startsWithThereIs = new RegExp('^(\\s)*there\\b\\s(is|are)\\b', 'i'); module.exports = function (text) { var suggestions = []; var match, innerMatch; while (match = re.exec(text)) { if (innerMatch = startsWithThereIs.exec(match[1])) { suggestions.push({ index: match.index + (innerMatch[1] || '').length, offset: innerMatch[0].length - (innerMatch[1] || '').length }); } } return suggestions; };
version https://git-lfs.github.com/spec/v1 oid sha256:3860434f80db971d49c66c99011afb45ad197162f47626659d2fbbbfae289f55 size 1425
/** * List for data storage * @module echarts/data/List */ import {__DEV__} from '../config'; import * as zrUtil from 'zrender/src/core/util'; import Model from '../model/Model'; import DataDiffer from './DataDiffer'; import * as modelUtil from '../util/model'; var isObject = zrUtil.isObject; var UNDEFINED = 'undefined'; var globalObj = typeof window === UNDEFINED ? global : window; var dataCtors = { 'float': typeof globalObj.Float64Array === UNDEFINED ? Array : globalObj.Float64Array, 'int': typeof globalObj.Int32Array === UNDEFINED ? Array : globalObj.Int32Array, // Ordinal data type can be string or int 'ordinal': Array, 'number': Array, 'time': Array }; var TRANSFERABLE_PROPERTIES = [ 'stackedOn', 'hasItemOption', '_nameList', '_idList', '_rawData' ]; function transferProperties(a, b) { zrUtil.each(TRANSFERABLE_PROPERTIES.concat(b.__wrappedMethods || []), function (propName) { if (b.hasOwnProperty(propName)) { a[propName] = b[propName]; } }); a.__wrappedMethods = b.__wrappedMethods; } function DefaultDataProvider(dataArray) { this._array = dataArray || []; } DefaultDataProvider.prototype.pure = false; DefaultDataProvider.prototype.count = function () { return this._array.length; }; DefaultDataProvider.prototype.getItem = function (idx) { return this._array[idx]; }; /** * @constructor * @alias module:echarts/data/List * * @param {Array.<string|Object>} dimensions * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...]. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius * @param {module:echarts/model/Model} hostModel */ var List = function (dimensions, hostModel) { dimensions = dimensions || ['x', 'y']; var dimensionInfos = {}; var dimensionNames = []; for (var i = 0; i < dimensions.length; i++) { var dimensionName; var dimensionInfo = {}; if (typeof dimensions[i] === 'string') { dimensionName = dimensions[i]; dimensionInfo = { name: dimensionName, coordDim: dimensionName, coordDimIndex: 0, stackable: false, // Type can be 'float', 'int', 'number' // Default is number, Precision of float may not enough type: 'number' }; } else { dimensionInfo = dimensions[i]; dimensionName = dimensionInfo.name; dimensionInfo.type = dimensionInfo.type || 'number'; if (!dimensionInfo.coordDim) { dimensionInfo.coordDim = dimensionName; dimensionInfo.coordDimIndex = 0; } } dimensionInfo.otherDims = dimensionInfo.otherDims || {}; dimensionNames.push(dimensionName); dimensionInfos[dimensionName] = dimensionInfo; } /** * @readOnly * @type {Array.<string>} */ this.dimensions = dimensionNames; /** * Infomation of each data dimension, like data type. * @type {Object} */ this._dimensionInfos = dimensionInfos; /** * @type {module:echarts/model/Model} */ this.hostModel = hostModel; /** * @type {module:echarts/model/Model} */ this.dataType; /** * Indices stores the indices of data subset after filtered. * This data subset will be used in chart. * @type {Array.<number>} * @readOnly */ this.indices = []; /** * Data storage * @type {Object.<key, TypedArray|Array>} * @private */ this._storage = {}; /** * @type {Array.<string>} */ this._nameList = []; /** * @type {Array.<string>} */ this._idList = []; /** * Models of data option is stored sparse for optimizing memory cost * @type {Array.<module:echarts/model/Model>} * @private */ this._optionModels = []; /** * @param {module:echarts/data/List} */ this.stackedOn = null; /** * Global visual properties after visual coding * @type {Object} * @private */ this._visual = {}; /** * Globel layout properties. * @type {Object} * @private */ this._layout = {}; /** * Item visual properties after visual coding * @type {Array.<Object>} * @private */ this._itemVisuals = []; /** * Item layout properties after layout * @type {Array.<Object>} * @private */ this._itemLayouts = []; /** * Graphic elemnents * @type {Array.<module:zrender/Element>} * @private */ this._graphicEls = []; /** * @type {Array.<Array|Object>} * @private */ this._rawData; /** * @type {Object} * @private */ this._extent; }; var listProto = List.prototype; listProto.type = 'list'; /** * If each data item has it's own option * @type {boolean} */ listProto.hasItemOption = true; /** * Get dimension name * @param {string|number} dim * Dimension can be concrete names like x, y, z, lng, lat, angle, radius * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius' * @return {string} Concrete dim name. */ listProto.getDimension = function (dim) { if (!isNaN(dim)) { dim = this.dimensions[dim] || dim; } return dim; }; /** * Get type and stackable info of particular dimension * @param {string|number} dim * Dimension can be concrete names like x, y, z, lng, lat, angle, radius * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius' */ listProto.getDimensionInfo = function (dim) { return zrUtil.clone(this._dimensionInfos[this.getDimension(dim)]); }; /** * Initialize from data * @param {Array.<Object|number|Array>} data * @param {Array.<string>} [nameList] * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number */ listProto.initData = function (data, nameList, dimValueGetter) { data = data || []; var isDataArray = zrUtil.isArray(data); if (isDataArray) { data = new DefaultDataProvider(data); } if (__DEV__) { if (!isDataArray && (typeof data.getItem != 'function' || typeof data.count != 'function')) { throw new Error('Inavlid data provider.'); } } this._rawData = data; // Clear var storage = this._storage = {}; var indices = this.indices = []; var dimensions = this.dimensions; var dimensionInfoMap = this._dimensionInfos; var size = data.count(); var idList = []; var nameRepeatCount = {}; var nameDimIdx; nameList = nameList || []; // Init storage for (var i = 0; i < dimensions.length; i++) { var dimInfo = dimensionInfoMap[dimensions[i]]; dimInfo.otherDims.itemName === 0 && (nameDimIdx = i); var DataCtor = dataCtors[dimInfo.type]; storage[dimensions[i]] = new DataCtor(size); } var self = this; if (!dimValueGetter) { self.hasItemOption = false; } // Default dim value getter dimValueGetter = dimValueGetter || function (dataItem, dimName, dataIndex, dimIndex) { var value = modelUtil.getDataItemValue(dataItem); // If any dataItem is like { value: 10 } if (modelUtil.isDataItemOption(dataItem)) { self.hasItemOption = true; } return modelUtil.converDataValue( (value instanceof Array) ? value[dimIndex] // If value is a single number or something else not array. : value, dimensionInfoMap[dimName] ); }; for (var i = 0; i < size; i++) { // NOTICE: Try not to write things into dataItem var dataItem = data.getItem(i); // Each data item is value // [1, 2] // 2 // Bar chart, line chart which uses category axis // only gives the 'y' value. 'x' value is the indices of cateogry // Use a tempValue to normalize the value to be a (x, y) value // Store the data by dimensions for (var k = 0; k < dimensions.length; k++) { var dim = dimensions[k]; var dimStorage = storage[dim]; // PENDING NULL is empty or zero dimStorage[i] = dimValueGetter(dataItem, dim, i, k); } indices.push(i); } // Use the name in option and create id for (var i = 0; i < size; i++) { var dataItem = data.getItem(i); if (!nameList[i] && dataItem) { if (dataItem.name != null) { nameList[i] = dataItem.name; } else if (nameDimIdx != null) { nameList[i] = storage[dimensions[nameDimIdx]][i]; } } var name = nameList[i] || ''; // Try using the id in option var id = dataItem && dataItem.id; if (!id && name) { // Use name as id and add counter to avoid same name nameRepeatCount[name] = nameRepeatCount[name] || 0; id = name; if (nameRepeatCount[name] > 0) { id += '__ec__' + nameRepeatCount[name]; } nameRepeatCount[name]++; } id && (idList[i] = id); } this._nameList = nameList; this._idList = idList; }; /** * @return {number} */ listProto.count = function () { return this.indices.length; }; /** * Get value. Return NaN if idx is out of range. * @param {string} dim Dim must be concrete name. * @param {number} idx * @param {boolean} stack * @return {number} */ listProto.get = function (dim, idx, stack) { var storage = this._storage; var dataIndex = this.indices[idx]; // If value not exists if (dataIndex == null || !storage[dim]) { return NaN; } var value = storage[dim][dataIndex]; // FIXME ordinal data type is not stackable if (stack) { var dimensionInfo = this._dimensionInfos[dim]; if (dimensionInfo && dimensionInfo.stackable) { var stackedOn = this.stackedOn; while (stackedOn) { // Get no stacked data of stacked on var stackedValue = stackedOn.get(dim, idx); // Considering positive stack, negative stack and empty data if ((value >= 0 && stackedValue > 0) // Positive stack || (value <= 0 && stackedValue < 0) // Negative stack ) { value += stackedValue; } stackedOn = stackedOn.stackedOn; } } } return value; }; /** * Get value for multi dimensions. * @param {Array.<string>} [dimensions] If ignored, using all dimensions. * @param {number} idx * @param {boolean} stack * @return {number} */ listProto.getValues = function (dimensions, idx, stack) { var values = []; if (!zrUtil.isArray(dimensions)) { stack = idx; idx = dimensions; dimensions = this.dimensions; } for (var i = 0, len = dimensions.length; i < len; i++) { values.push(this.get(dimensions[i], idx, stack)); } return values; }; /** * If value is NaN. Inlcuding '-' * @param {string} dim * @param {number} idx * @return {number} */ listProto.hasValue = function (idx) { var dimensions = this.dimensions; var dimensionInfos = this._dimensionInfos; for (var i = 0, len = dimensions.length; i < len; i++) { if ( // Ordinal type can be string or number dimensionInfos[dimensions[i]].type !== 'ordinal' && isNaN(this.get(dimensions[i], idx)) ) { return false; } } return true; }; /** * Get extent of data in one dimension * @param {string} dim * @param {boolean} stack * @param {Function} filter */ listProto.getDataExtent = function (dim, stack, filter) { dim = this.getDimension(dim); var dimData = this._storage[dim]; var dimInfo = this.getDimensionInfo(dim); stack = (dimInfo && dimInfo.stackable) && stack; var dimExtent = (this._extent || (this._extent = {}))[dim + (!!stack)]; var value; if (dimExtent) { return dimExtent; } // var dimInfo = this._dimensionInfos[dim]; if (dimData) { var min = Infinity; var max = -Infinity; // var isOrdinal = dimInfo.type === 'ordinal'; for (var i = 0, len = this.count(); i < len; i++) { value = this.get(dim, i, stack); // FIXME // if (isOrdinal && typeof value === 'string') { // value = zrUtil.indexOf(dimData, value); // } if (!filter || filter(value, dim, i)) { value < min && (min = value); value > max && (max = value); } } return (this._extent[dim + !!stack] = [min, max]); } else { return [Infinity, -Infinity]; } }; /** * Get sum of data in one dimension * @param {string} dim * @param {boolean} stack */ listProto.getSum = function (dim, stack) { var dimData = this._storage[dim]; var sum = 0; if (dimData) { for (var i = 0, len = this.count(); i < len; i++) { var value = this.get(dim, i, stack); if (!isNaN(value)) { sum += value; } } } return sum; }; /** * Retreive the index with given value * @param {number} idx * @param {number} value * @return {number} */ // FIXME Precision of float value listProto.indexOf = function (dim, value) { var storage = this._storage; var dimData = storage[dim]; var indices = this.indices; if (dimData) { for (var i = 0, len = indices.length; i < len; i++) { var rawIndex = indices[i]; if (dimData[rawIndex] === value) { return i; } } } return -1; }; /** * Retreive the index with given name * @param {number} idx * @param {number} name * @return {number} */ listProto.indexOfName = function (name) { var indices = this.indices; var nameList = this._nameList; for (var i = 0, len = indices.length; i < len; i++) { var rawIndex = indices[i]; if (nameList[rawIndex] === name) { return i; } } return -1; }; /** * Retreive the index with given raw data index * @param {number} idx * @param {number} name * @return {number} */ listProto.indexOfRawIndex = function (rawIndex) { // Indices are ascending var indices = this.indices; // If rawIndex === dataIndex var rawDataIndex = indices[rawIndex]; if (rawDataIndex != null && rawDataIndex === rawIndex) { return rawIndex; } var left = 0; var right = indices.length - 1; while (left <= right) { var mid = (left + right) / 2 | 0; if (indices[mid] < rawIndex) { left = mid + 1; } else if (indices[mid] > rawIndex) { right = mid - 1; } else { return mid; } } return -1; }; /** * Retreive the index of nearest value * @param {string} dim * @param {number} value * @param {boolean} stack If given value is after stacked * @param {number} [maxDistance=Infinity] * @return {Array.<number>} Considere multiple points has the same value. */ listProto.indicesOfNearest = function (dim, value, stack, maxDistance) { var storage = this._storage; var dimData = storage[dim]; var nearestIndices = []; if (!dimData) { return nearestIndices; } if (maxDistance == null) { maxDistance = Infinity; } var minDist = Number.MAX_VALUE; var minDiff = -1; for (var i = 0, len = this.count(); i < len; i++) { var diff = value - this.get(dim, i, stack); var dist = Math.abs(diff); if (diff <= maxDistance && dist <= minDist) { // For the case of two data are same on xAxis, which has sequence data. // Show the nearest index // https://github.com/ecomfe/echarts/issues/2869 if (dist < minDist || (diff >= 0 && minDiff < 0)) { minDist = dist; minDiff = diff; nearestIndices.length = 0; } nearestIndices.push(i); } } return nearestIndices; }; /** * Get raw data index * @param {number} idx * @return {number} */ listProto.getRawIndex = function (idx) { var rawIdx = this.indices[idx]; return rawIdx == null ? -1 : rawIdx; }; /** * Get raw data item * @param {number} idx * @return {number} */ listProto.getRawDataItem = function (idx) { return this._rawData.getItem(this.getRawIndex(idx)); }; /** * @param {number} idx * @param {boolean} [notDefaultIdx=false] * @return {string} */ listProto.getName = function (idx) { return this._nameList[this.indices[idx]] || ''; }; /** * @param {number} idx * @param {boolean} [notDefaultIdx=false] * @return {string} */ listProto.getId = function (idx) { return this._idList[this.indices[idx]] || (this.getRawIndex(idx) + ''); }; function normalizeDimensions(dimensions) { if (!zrUtil.isArray(dimensions)) { dimensions = [dimensions]; } return dimensions; } /** * Data iteration * @param {string|Array.<string>} * @param {Function} cb * @param {boolean} [stack=false] * @param {*} [context=this] * * @example * list.each('x', function (x, idx) {}); * list.each(['x', 'y'], function (x, y, idx) {}); * list.each(function (idx) {}) */ listProto.each = function (dims, cb, stack, context) { if (typeof dims === 'function') { context = stack; stack = cb; cb = dims; dims = []; } dims = zrUtil.map(normalizeDimensions(dims), this.getDimension, this); var value = []; var dimSize = dims.length; var indices = this.indices; context = context || this; for (var i = 0; i < indices.length; i++) { // Simple optimization switch (dimSize) { case 0: cb.call(context, i); break; case 1: cb.call(context, this.get(dims[0], i, stack), i); break; case 2: cb.call(context, this.get(dims[0], i, stack), this.get(dims[1], i, stack), i); break; default: for (var k = 0; k < dimSize; k++) { value[k] = this.get(dims[k], i, stack); } // Index value[k] = i; cb.apply(context, value); } } }; /** * Data filter * @param {string|Array.<string>} * @param {Function} cb * @param {boolean} [stack=false] * @param {*} [context=this] */ listProto.filterSelf = function (dimensions, cb, stack, context) { if (typeof dimensions === 'function') { context = stack; stack = cb; cb = dimensions; dimensions = []; } dimensions = zrUtil.map( normalizeDimensions(dimensions), this.getDimension, this ); var newIndices = []; var value = []; var dimSize = dimensions.length; var indices = this.indices; context = context || this; for (var i = 0; i < indices.length; i++) { var keep; // Simple optimization if (!dimSize) { keep = cb.call(context, i); } else if (dimSize === 1) { keep = cb.call( context, this.get(dimensions[0], i, stack), i ); } else { for (var k = 0; k < dimSize; k++) { value[k] = this.get(dimensions[k], i, stack); } value[k] = i; keep = cb.apply(context, value); } if (keep) { newIndices.push(indices[i]); } } this.indices = newIndices; // Reset data extent this._extent = {}; return this; }; /** * Data mapping to a plain array * @param {string|Array.<string>} [dimensions] * @param {Function} cb * @param {boolean} [stack=false] * @param {*} [context=this] * @return {Array} */ listProto.mapArray = function (dimensions, cb, stack, context) { if (typeof dimensions === 'function') { context = stack; stack = cb; cb = dimensions; dimensions = []; } var result = []; this.each(dimensions, function () { result.push(cb && cb.apply(this, arguments)); }, stack, context); return result; }; function cloneListForMapAndSample(original, excludeDimensions) { var allDimensions = original.dimensions; var list = new List( zrUtil.map(allDimensions, original.getDimensionInfo, original), original.hostModel ); // FIXME If needs stackedOn, value may already been stacked transferProperties(list, original); var storage = list._storage = {}; var originalStorage = original._storage; // Init storage for (var i = 0; i < allDimensions.length; i++) { var dim = allDimensions[i]; var dimStore = originalStorage[dim]; if (zrUtil.indexOf(excludeDimensions, dim) >= 0) { storage[dim] = new dimStore.constructor( originalStorage[dim].length ); } else { // Direct reference for other dimensions storage[dim] = originalStorage[dim]; } } return list; } /** * Data mapping to a new List with given dimensions * @param {string|Array.<string>} dimensions * @param {Function} cb * @param {boolean} [stack=false] * @param {*} [context=this] * @return {Array} */ listProto.map = function (dimensions, cb, stack, context) { dimensions = zrUtil.map( normalizeDimensions(dimensions), this.getDimension, this ); var list = cloneListForMapAndSample(this, dimensions); // Following properties are all immutable. // So we can reference to the same value var indices = list.indices = this.indices; var storage = list._storage; var tmpRetValue = []; this.each(dimensions, function () { var idx = arguments[arguments.length - 1]; var retValue = cb && cb.apply(this, arguments); if (retValue != null) { // a number if (typeof retValue === 'number') { tmpRetValue[0] = retValue; retValue = tmpRetValue; } for (var i = 0; i < retValue.length; i++) { var dim = dimensions[i]; var dimStore = storage[dim]; var rawIdx = indices[idx]; if (dimStore) { dimStore[rawIdx] = retValue[i]; } } } }, stack, context); return list; }; /** * Large data down sampling on given dimension * @param {string} dimension * @param {number} rate * @param {Function} sampleValue * @param {Function} sampleIndex Sample index for name and id */ listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) { var list = cloneListForMapAndSample(this, [dimension]); var storage = this._storage; var targetStorage = list._storage; var originalIndices = this.indices; var indices = list.indices = []; var frameValues = []; var frameIndices = []; var frameSize = Math.floor(1 / rate); var dimStore = targetStorage[dimension]; var len = this.count(); // Copy data from original data for (var i = 0; i < storage[dimension].length; i++) { targetStorage[dimension][i] = storage[dimension][i]; } for (var i = 0; i < len; i += frameSize) { // Last frame if (frameSize > len - i) { frameSize = len - i; frameValues.length = frameSize; } for (var k = 0; k < frameSize; k++) { var idx = originalIndices[i + k]; frameValues[k] = dimStore[idx]; frameIndices[k] = idx; } var value = sampleValue(frameValues); var idx = frameIndices[sampleIndex(frameValues, value) || 0]; // Only write value on the filtered data dimStore[idx] = value; indices.push(idx); } return list; }; /** * Get model of one data item. * * @param {number} idx */ // FIXME Model proxy ? listProto.getItemModel = function (idx) { var hostModel = this.hostModel; idx = this.indices[idx]; return new Model(this._rawData.getItem(idx), hostModel, hostModel && hostModel.ecModel); }; /** * Create a data differ * @param {module:echarts/data/List} otherList * @return {module:echarts/data/DataDiffer} */ listProto.diff = function (otherList) { var idList = this._idList; var otherIdList = otherList && otherList._idList; var val; // Use prefix to avoid index to be the same as otherIdList[idx], // which will cause weird udpate animation. var prefix = 'e\0\0'; return new DataDiffer( otherList ? otherList.indices : [], this.indices, function (idx) { return (val = otherIdList[idx]) != null ? val : prefix + idx; }, function (idx) { return (val = idList[idx]) != null ? val : prefix + idx; } ); }; /** * Get visual property. * @param {string} key */ listProto.getVisual = function (key) { var visual = this._visual; return visual && visual[key]; }; /** * Set visual property * @param {string|Object} key * @param {*} [value] * * @example * setVisual('color', color); * setVisual({ * 'color': color * }); */ listProto.setVisual = function (key, val) { if (isObject(key)) { for (var name in key) { if (key.hasOwnProperty(name)) { this.setVisual(name, key[name]); } } return; } this._visual = this._visual || {}; this._visual[key] = val; }; /** * Set layout property. * @param {string|Object} key * @param {*} [val] */ listProto.setLayout = function (key, val) { if (isObject(key)) { for (var name in key) { if (key.hasOwnProperty(name)) { this.setLayout(name, key[name]); } } return; } this._layout[key] = val; }; /** * Get layout property. * @param {string} key. * @return {*} */ listProto.getLayout = function (key) { return this._layout[key]; }; /** * Get layout of single data item * @param {number} idx */ listProto.getItemLayout = function (idx) { return this._itemLayouts[idx]; }; /** * Set layout of single data item * @param {number} idx * @param {Object} layout * @param {boolean=} [merge=false] */ listProto.setItemLayout = function (idx, layout, merge) { this._itemLayouts[idx] = merge ? zrUtil.extend(this._itemLayouts[idx] || {}, layout) : layout; }; /** * Clear all layout of single data item */ listProto.clearItemLayouts = function () { this._itemLayouts.length = 0; }; /** * Get visual property of single data item * @param {number} idx * @param {string} key * @param {boolean} [ignoreParent=false] */ listProto.getItemVisual = function (idx, key, ignoreParent) { var itemVisual = this._itemVisuals[idx]; var val = itemVisual && itemVisual[key]; if (val == null && !ignoreParent) { // Use global visual property return this.getVisual(key); } return val; }; /** * Set visual property of single data item * * @param {number} idx * @param {string|Object} key * @param {*} [value] * * @example * setItemVisual(0, 'color', color); * setItemVisual(0, { * 'color': color * }); */ listProto.setItemVisual = function (idx, key, value) { var itemVisual = this._itemVisuals[idx] || {}; this._itemVisuals[idx] = itemVisual; if (isObject(key)) { for (var name in key) { if (key.hasOwnProperty(name)) { itemVisual[name] = key[name]; } } return; } itemVisual[key] = value; }; /** * Clear itemVisuals and list visual. */ listProto.clearAllVisual = function () { this._visual = {}; this._itemVisuals = []; }; var setItemDataAndSeriesIndex = function (child) { child.seriesIndex = this.seriesIndex; child.dataIndex = this.dataIndex; child.dataType = this.dataType; }; /** * Set graphic element relative to data. It can be set as null * @param {number} idx * @param {module:zrender/Element} [el] */ listProto.setItemGraphicEl = function (idx, el) { var hostModel = this.hostModel; if (el) { // Add data index and series index for indexing the data by element // Useful in tooltip el.dataIndex = idx; el.dataType = this.dataType; el.seriesIndex = hostModel && hostModel.seriesIndex; if (el.type === 'group') { el.traverse(setItemDataAndSeriesIndex, el); } } this._graphicEls[idx] = el; }; /** * @param {number} idx * @return {module:zrender/Element} */ listProto.getItemGraphicEl = function (idx) { return this._graphicEls[idx]; }; /** * @param {Function} cb * @param {*} context */ listProto.eachItemGraphicEl = function (cb, context) { zrUtil.each(this._graphicEls, function (el, idx) { if (el) { cb && cb.call(context, el, idx); } }); }; /** * Shallow clone a new list except visual and layout properties, and graph elements. * New list only change the indices. */ listProto.cloneShallow = function () { var dimensionInfoList = zrUtil.map(this.dimensions, this.getDimensionInfo, this); var list = new List(dimensionInfoList, this.hostModel); // FIXME list._storage = this._storage; transferProperties(list, this); // Clone will not change the data extent and indices list.indices = this.indices.slice(); if (this._extent) { list._extent = zrUtil.extend({}, this._extent); } return list; }; /** * Wrap some method to add more feature * @param {string} methodName * @param {Function} injectFunction */ listProto.wrapMethod = function (methodName, injectFunction) { var originalMethod = this[methodName]; if (typeof originalMethod !== 'function') { return; } this.__wrappedMethods = this.__wrappedMethods || []; this.__wrappedMethods.push(methodName); this[methodName] = function () { var res = originalMethod.apply(this, arguments); return injectFunction.apply(this, [res].concat(zrUtil.slice(arguments))); }; }; // Methods that create a new list based on this list should be listed here. // Notice that those method should `RETURN` the new list. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map']; // Methods that change indices of this list should be listed here. listProto.CHANGABLE_METHODS = ['filterSelf']; export default List;
/** * Environment for Jasmine * * @constructor */ jasmine.Env = function() { this.currentSpec = null; this.currentSuite = null; this.currentRunner_ = new jasmine.Runner(this); this.reporter = new jasmine.MultiReporter(); this.updateInterval = jasmine.DEFAULT_UPDATE_INTERVAL; this.defaultTimeoutInterval = jasmine.DEFAULT_TIMEOUT_INTERVAL; this.lastUpdate = 0; this.specFilter = function() { return true; }; this.nextSpecId_ = 0; this.nextSuiteId_ = 0; this.equalityTesters_ = []; // wrap matchers this.matchersClass = function() { jasmine.Matchers.apply(this, arguments); }; jasmine.util.inherit(this.matchersClass, jasmine.Matchers); jasmine.Matchers.wrapInto_(jasmine.Matchers.prototype, this.matchersClass); }; jasmine.Env.prototype.setTimeout = jasmine.setTimeout; jasmine.Env.prototype.clearTimeout = jasmine.clearTimeout; jasmine.Env.prototype.setInterval = jasmine.setInterval; jasmine.Env.prototype.clearInterval = jasmine.clearInterval; /** * @returns an object containing jasmine version build info, if set. */ jasmine.Env.prototype.version = function () { if (jasmine.version_) { return jasmine.version_; } else { throw new Error('Version not set'); } }; /** * @returns string containing jasmine version build info, if set. */ jasmine.Env.prototype.versionString = function() { if (jasmine.version_) { var version = this.version(); return version.major + "." + version.minor + "." + version.build + " revision " + version.revision; } else { return "version unknown"; } }; /** * @returns a sequential integer starting at 0 */ jasmine.Env.prototype.nextSpecId = function () { return this.nextSpecId_++; }; /** * @returns a sequential integer starting at 0 */ jasmine.Env.prototype.nextSuiteId = function () { return this.nextSuiteId_++; }; /** * Register a reporter to receive status updates from Jasmine. * @param {jasmine.Reporter} reporter An object which will receive status updates. */ jasmine.Env.prototype.addReporter = function(reporter) { this.reporter.addReporter(reporter); }; jasmine.Env.prototype.execute = function() { this.currentRunner_.execute(); }; jasmine.Env.prototype.describe = function(description, specDefinitions) { var suite = new jasmine.Suite(this, description, specDefinitions, this.currentSuite); var parentSuite = this.currentSuite; if (parentSuite) { parentSuite.add(suite); } else { this.currentRunner_.add(suite); } this.currentSuite = suite; var declarationError = null; try { specDefinitions.call(suite); } catch(e) { declarationError = e; } this.currentSuite = parentSuite; if (declarationError) { this.it("encountered a declaration exception", function() { throw declarationError; }); } return suite; }; jasmine.Env.prototype.beforeEach = function(beforeEachFunction) { if (this.currentSuite) { this.currentSuite.beforeEach(beforeEachFunction); } else { this.currentRunner_.beforeEach(beforeEachFunction); } }; jasmine.Env.prototype.currentRunner = function () { return this.currentRunner_; }; jasmine.Env.prototype.afterEach = function(afterEachFunction) { if (this.currentSuite) { this.currentSuite.afterEach(afterEachFunction); } else { this.currentRunner_.afterEach(afterEachFunction); } }; jasmine.Env.prototype.xdescribe = function(desc, specDefinitions) { return { execute: function() { } }; }; jasmine.Env.prototype.it = function(description, func) { var spec = new jasmine.Spec(this, this.currentSuite, description); this.currentSuite.add(spec); this.currentSpec = spec; if (func) { spec.runs(func); } return spec; }; jasmine.Env.prototype.xit = function(desc, func) { return { id: this.nextSpecId(), runs: function() { } }; }; jasmine.Env.prototype.compareObjects_ = function(a, b, mismatchKeys, mismatchValues) { if (a.__Jasmine_been_here_before__ === b && b.__Jasmine_been_here_before__ === a) { return true; } a.__Jasmine_been_here_before__ = b; b.__Jasmine_been_here_before__ = a; var hasKey = function(obj, keyName) { return obj !== null && obj[keyName] !== jasmine.undefined; }; for (var property in b) { if (!hasKey(a, property) && hasKey(b, property)) { mismatchKeys.push("expected has key '" + property + "', but missing from actual."); } } for (property in a) { if (!hasKey(b, property) && hasKey(a, property)) { mismatchKeys.push("expected missing key '" + property + "', but present in actual."); } } for (property in b) { if (property == '__Jasmine_been_here_before__') continue; if (!this.equals_(a[property], b[property], mismatchKeys, mismatchValues)) { mismatchValues.push("'" + property + "' was '" + (b[property] ? jasmine.util.htmlEscape(b[property].toString()) : b[property]) + "' in expected, but was '" + (a[property] ? jasmine.util.htmlEscape(a[property].toString()) : a[property]) + "' in actual."); } } if (jasmine.isArray_(a) && jasmine.isArray_(b) && a.length != b.length) { mismatchValues.push("arrays were not the same length"); } delete a.__Jasmine_been_here_before__; delete b.__Jasmine_been_here_before__; return (mismatchKeys.length === 0 && mismatchValues.length === 0); }; jasmine.Env.prototype.equals_ = function(a, b, mismatchKeys, mismatchValues) { mismatchKeys = mismatchKeys || []; mismatchValues = mismatchValues || []; for (var i = 0; i < this.equalityTesters_.length; i++) { var equalityTester = this.equalityTesters_[i]; var result = equalityTester(a, b, this, mismatchKeys, mismatchValues); if (result !== jasmine.undefined) return result; } if (a === b) return true; if (a === jasmine.undefined || a === null || b === jasmine.undefined || b === null) { return (a == jasmine.undefined && b == jasmine.undefined); } if (jasmine.isDomNode(a) && jasmine.isDomNode(b)) { return a === b; } if (a instanceof Date && b instanceof Date) { return a.getTime() == b.getTime(); } if (a instanceof jasmine.Matchers.Any) { return a.matches(b); } if (b instanceof jasmine.Matchers.Any) { return b.matches(a); } if (jasmine.isString_(a) && jasmine.isString_(b)) { return (a == b); } if (jasmine.isNumber_(a) && jasmine.isNumber_(b)) { return (a == b); } if (typeof a === "object" && typeof b === "object") { return this.compareObjects_(a, b, mismatchKeys, mismatchValues); } //Straight check return (a === b); }; jasmine.Env.prototype.contains_ = function(haystack, needle) { if (jasmine.isArray_(haystack)) { for (var i = 0; i < haystack.length; i++) { if (this.equals_(haystack[i], needle)) return true; } return false; } return haystack.indexOf(needle) >= 0; }; jasmine.Env.prototype.addEqualityTester = function(equalityTester) { this.equalityTesters_.push(equalityTester); };
/** * $Id: del.js 6572 2009-02-25 02:46:35Z Garbin $ * * @author Moxiecode - based on work by Andrew Tetlaw * @copyright Copyright © 2004-2008, Moxiecode Systems AB, All rights reserved. */ function init() { SXE.initElementDialog('del'); if (SXE.currentAction == "update") { setFormValue('datetime', tinyMCEPopup.editor.dom.getAttrib(SXE.updateElement, 'datetime')); setFormValue('cite', tinyMCEPopup.editor.dom.getAttrib(SXE.updateElement, 'cite')); SXE.showRemoveButton(); } } function setElementAttribs(elm) { setAllCommonAttribs(elm); setAttrib(elm, 'datetime'); setAttrib(elm, 'cite'); } function insertDel() { var elm = tinyMCEPopup.editor.dom.getParent(SXE.focusElement, 'DEL'); tinyMCEPopup.execCommand('mceBeginUndoLevel'); if (elm == null) { var s = SXE.inst.selection.getContent(); if(s.length > 0) { insertInlineElement('del'); var elementArray = tinymce.grep(SXE.inst.dom.select('del'), function(n) {return n.id == '#sxe_temp_del#';}); for (var i=0; i<elementArray.length; i++) { var elm = elementArray[i]; setElementAttribs(elm); } } } else { setElementAttribs(elm); } tinyMCEPopup.editor.nodeChanged(); tinyMCEPopup.execCommand('mceEndUndoLevel'); tinyMCEPopup.close(); } function insertInlineElement(en) { var ed = tinyMCEPopup.editor, dom = ed.dom; ed.getDoc().execCommand('FontName', false, 'mceinline'); tinymce.each(dom.select(tinymce.isWebKit ? 'span' : 'font'), function(n) { if (n.style.fontFamily == 'mceinline' || n.face == 'mceinline') dom.replace(dom.create(en), n, 1); }); } function removeDel() { SXE.removeElement('del'); tinyMCEPopup.close(); } tinyMCEPopup.onInit.add(init);
'use strict'; exports.init = function(grunt, phantomjs) { // node api var fs = require('fs'), path = require('path'); // npm var rimraf = require('rimraf'), _ = require('lodash'); var baseDir = '.', tempDir = '.grunt/grunt-contrib-jasmine'; var exports = {}; exports.writeTempFile = function(dest, contents) { var file = path.join(tempDir,dest); grunt.file.write(file, contents); }; exports.copyTempFile = function(src, dest) { var file = path.join(tempDir,dest); grunt.file.copy(src, file); }; exports.cleanTemp = function(cb) { rimraf(tempDir, function(){ // if this fails, then ./.grunt isn't empty and that's ok. fs.rmdir('.grunt', cb); }); }; exports.buildSpecrunner = function (src, options){ var source = '', outfile = options.outfile, specrunner = path.join(baseDir,outfile), outdir = path.dirname(outfile), gruntfilter = grunt.option("filter"), filteredSpecs = exports.getRelativeFileList(outdir, options.specs); // Let's filter through the spec files here, // there's no need to go on if no specs matches if (gruntfilter) { filteredSpecs = specFilter(gruntfilter, filteredSpecs); if(filteredSpecs.length === 0) { grunt.log.warn("the --filter flag did not match any spec within " + grunt.task.current.target); return null; } } exports.copyTempFile(__dirname + '/../jasmine/reporters/PhantomReporter.js', 'reporter.js'); ['jasmine.css', 'jasmine.js', 'jasmine-html.js', 'boot.js'].forEach(function(name){ var path = __dirname + '/../../vendor/jasmine-' + options.version + '/' + name; if (fs.existsSync(path)) exports.copyTempFile(path, name); }); exports.copyTempFile(__dirname + '/../helpers/phantom-polyfill.js', 'phantom-polyfill.js'); var reporters = [ tempDir + '/reporter.js' ]; var jasmineCss = [ tempDir + '/jasmine.css' ]; jasmineCss = jasmineCss.concat(options.styles); var polyfills = [ tempDir + '/phantom-polyfill.js' ]; var jasmineCore = [ tempDir + '/jasmine.js', tempDir + '/jasmine-html.js' ]; var context = { temp : tempDir, outfile: outfile, css : exports.getRelativeFileList(outdir, jasmineCss, { nonull : true }), scripts : { polyfills : exports.getRelativeFileList(outdir, polyfills), jasmine : exports.getRelativeFileList(outdir, jasmineCore), helpers : exports.getRelativeFileList(outdir, options.helpers, { nonull : true }), specs : filteredSpecs, src : exports.getRelativeFileList(outdir, src, { nonull : true }), vendor : exports.getRelativeFileList(outdir, options.vendor, { nonull : true }), reporters : exports.getRelativeFileList(outdir, reporters), boot : exports.getRelativeFileList(outdir, tempDir + '/boot.js') }, options : options.templateOptions || {} }; if (options.template.process) { var task = { writeTempFile : exports.writeTempFile, copyTempFile : exports.copyTempFile, phantomjs : phantomjs }; source = options.template.process(grunt, task, context); grunt.file.write(specrunner, source); } else { grunt.file.copy(options.template, specrunner, { process : function(src) { source = _.template(src, context); return source; } }); } return source; }; exports.getRelativeFileList = function(outdir, patterns, options) { var files = []; patterns = patterns instanceof Array ? patterns : [ patterns ]; options = options || {}; patterns.forEach(function(listItem){ if (listItem) files = files.concat(grunt.file.expand(options, listItem)); }); files = grunt.util._(files).map(function(file){ return (/^https?:/).test(file) ? file : path.relative(outdir, file).replace(/\\/g, '/'); }); return files; }; // Allows for a spec file to be specified via the command line function specFilter(pattern, files) { var specPattern, patternArray, filteredArray = [], scriptSpecs = [], matchPath = function(path) { return !!path.match(specPattern); }; if(pattern) { // For '*' to work as a wildcard. pattern = pattern.split("*").join("[\\S]*").replace(/\./g, "\\."); // This allows for comma separated strings to which we can match the spec files. patternArray = pattern.split(","); while(patternArray.length > 0) { pattern = (patternArray.splice(0, 1)[0]); if(pattern.length > 0) { if(pattern.indexOf('/') === -1) { specPattern = new RegExp("("+pattern+"[^/]*)(?!/)$", "ig"); } else if(pattern.indexOf('/') === 0) { specPattern = new RegExp("("+pattern+"[^/]*)(?=/)", "ig"); } else { throw new TypeError("--filter flag seems to be in the wrong format."); } // push is usually faster than concat. [].push.apply(scriptSpecs, files.filter(matchPath)); } } filteredArray = _.uniq(scriptSpecs); } return filteredArray; } return exports; };
YUI.add('gallery-itsacalendarmodellist', function (Y, NAME) { 'use strict'; /** * @module gallery-itsacalendarmarkeddates * @class ITSACalendarModelList * @since 0.3 * * <i>Copyright (c) 2013 Its Asbreuk - http://itsasbreuk.nl</i> * YUI BSD License - http://developer.yahoo.com/yui/license.html **/ var Lang = Y.Lang, YArray = Y.Array, YObject = Y.Object, hasKey = YObject.hasKey, YDate = Y.DataType.Date, dateIsValid = YDate.isValidDate, dateCopyObject = function (oDate) { return new Date(oDate.getTime()); }, dateCopyValues = function (aDate, bDate) { bDate.setTime(aDate.getTime()); }, dateAddMinutes = function (oDate, numMinutes) { oDate.setTime(oDate.getTime() + 60000*numMinutes); }, dateAddMonths = function (oDate, numMonths) { var newYear = oDate.getFullYear(), newMonth = oDate.getMonth() + numMonths; newYear = Math.floor(newYear + newMonth / 12); newMonth = (newMonth % 12 + 12) % 12; oDate.setFullYear(newYear); oDate.setMonth(newMonth); }, dateAddDays = function (oDate, numDays) { oDate.setTime(oDate.getTime() + 86400000*numDays); }, dateEqualDays = function(aDate, bDate) { return ((aDate.getDate()===bDate.getDate()) && (aDate.getMonth()===bDate.getMonth()) && (aDate.getFullYear()===bDate.getFullYear())); }, dayisGreater = function(aDate, bDate) { return (YDate.isGreater(aDate, bDate) && !dateEqualDays(aDate, bDate)); }, dayisGreaterOrEqual = function(aDate, bDate) { return (YDate.isGreater(aDate, bDate) || dateEqualDays(aDate, bDate)); }; //=============================================================================================== // First: extend Y.LazyModelList with 2 sugar methods for set- and get- attributes // We mix it to both Y.LazyModelList as well as Y.ModelList // this way we can always call these methods regardsless of a ModelList or LazyModelList as used //=============================================================================================== function ITSAModellistAttrExtention() {} Y.mix(ITSAModellistAttrExtention.prototype, { /** * Gets an attribute-value from a Model OR object. Depends on the class (Y.ModelList v.s. Y.LazyModelList). * Will always work, whether an Y.ModelList or Y.LazyModelList is attached. * * @method getModelAttr * @param {Y.Model} model the model (or extended class) from which the attribute has to be read. * @param {String} name Attribute name or object property path. * @return {Any} Attribute value, or `undefined` if the attribute doesn't exist, or 'null' if no model is passed. * @since 0.1 * */ getModelAttr: function(model, name) { return model && ((model.get && (Lang.type(model.get) === 'function')) ? model.get(name) : model[name]); }, /** * Sets an attribute-value of a Model OR object. Depends on the class (Y.ModelList v.s. Y.LazyModelList). * Will always work, whether an Y.ModelList or Y.LazyModelList is attached. * If you want to be sure the Model fires an attributeChange-event, then set 'revive' true. This way * lazy-Models will become true Models and fire an attributeChange-event. When the attibute was lazy before, * it will return lazy afterwards. * * @method setModelAttr * @param {Y.Model} model the model (or extended class) from which the attribute has to be read. * @param {String} name Attribute name or object property path. * @param {any} value Value to set. * @param {Object} [options] Data to be mixed into the event facade of the `change` event(s) for these attributes. * In case of Lazy-Model, this only has effect when 'revive' is true. * @param {Boolean} [options.silent=false] If `true`, no `change` event will be fired. * @since 0.1 * */ setModelAttr: function(model, name, value, options) { var instance = this, modelIsLazy, revivedModel; if (model) { modelIsLazy = !model.get || (Lang.type(model.get) !== 'function'); if (modelIsLazy) { revivedModel = instance.revive(model); model[name] = value; if (revivedModel) { //====================================================================================== // due to a bug, we need to sync cliendId first https://github.com/yui/yui3/issues/530 // revivedModel._set('clientId', model.clientId, {silent: true}); // //====================================================================================== revivedModel.set(name, value, options); instance.free(revivedModel); } } else { model.set(name, value, options); } } }, /** * Returns the Model as an object. Regardless whether it is a Model-instance, or an item of a LazyModelList * which might be an Object or a Model. Caution: If it is a Model-instance, than you get a Clone. If not * -in case of an object from a LazyModelList- than you get the reference to the original object. * * @method getModelToJSON * @param {Y.Model} model Model or Object from the (Lazy)ModelList * @return {Object} Object or model.toJSON() * @since 0.1 * */ getModelToJSON : function(model) { return (model.get && (Lang.type(model.get) === 'function')) ? model.toJSON() : model; } }, true); Y.ITSAModellistAttrExtention = ITSAModellistAttrExtention; Y.Base.mix(Y.ModelList, [ITSAModellistAttrExtention]); //========================================================================================================== // // Now the final extention // //========================================================================================================== function ITSACalendarModelList() {} ITSACalendarModelList.ATTRS = { /** * The ModelList that is 'attached' to the Calendar, resulting in highlighted dates for each Model * that has a 'Date-match'. For more info how a 'Date-match' is achieved: see the attribute modelConfig. * @attribute modelList * @type {ModelList} * @default null * @since 0.3 */ modelList : { value: null, lazyAdd: false, validator: function(v){ return (v === null) || (v.getByClientId); }, setter: '_setModelList' }, /** * Definition of the Model's <b>date</b>, <b>enddate</b>, <b>count</b>, <b>intervalMinutes</b>, * <b>intervalHours</b>, <b>intervalDays</b> and <b>intervalMonths</b> attributes. These values are Strings and represent the attributenames * in the Models. The actual values (and its types) come form the Models itsself. * * For example: {date: 'startDate'}, which means that yourModel.get('startDate') should return a Date-object. * When not specified, the module tries to find a valid <b>modelConfig.date</b> which it can use, * by looking at the Models structure. * * @attribute modelConfig * @type {Object} with fields: <b>date</b>, <b>enddate</b>, <b>count</b>, <b>intervalMinutes</b>, * <b>intervalHours</b>, <b>intervalDays</b> and <b>intervalMonths</b> * @default null * @since 0.3 */ modelConfig: { value: null, validator: function(v){ return (v === null) || Lang.isObject(v); }, setter: '_setModelConfig' } }; Y.mix(ITSACalendarModelList.prototype, { /** * Internal subscriber to Calendar.after('selectionChange') events * * @property _fireMarkEvent * @type EventHandle * @private * @since 0.3 */ /** * Internal subscriber to Calendar.after(['dateChange', 'markChange']) events * * @property _fireMarkEvent * @type EventHandle * @private * @since 0.3 */ /** * Internal subscriber to Calendar.after('render') events * * @property _syncModelListEvent * @type EventHandle * @private * @since 0.3 */ /** * Internal subscriber to modelList.after('*:change') events * * @property _syncModelListCheckEvent * @type EventHandle * @private * @since 0.3 */ /** * Internal flag that tells whether the attribute modelConfig is initiated. * * @property _modelConfigInitiated * @type Boolean * @private * @since 0.3 */ /** * Internal flag that tells whether the attribute modelList is initiated. * * @property _modelListInitiated * @type Boolean * @private * @since 0.3 */ /** * Internal flag that is used to check whether modelConfig is updated by an internal set('modelList'). * * @property _internalUpdate * @type Boolean * @private * @since 0.3 */ /** * Designated initializer * Initializes instance-level properties of ITSACalendarModelList. * * @method initializer * @protected * @since 0.3 */ initializer : function () { var instance = this; instance._modelConfigInitiated = false; instance._modelListInitiated = false; instance._internalUpdate = false; instance._storedModelDates = {}; instance._fireModelsEvent = instance.after('selectionChange', instance._fireSelectedModels); }, /** * Returns an Array with the Models that fall with the specified Date-range. * If aDate is an Array, then the search will be inside this Array. * If aDate is a Date-Object then the search will go between the range aDate-bDate * (bDate included, when bDate is not specified, only aDate is taken) * * @method getModels * @param {Date|Array} aDate the startDate, or an Array of Dates to search within * @param {Date} [bDate] The last Date to search within (in case of a range aDate-bDate) * Will only be taken if aDate is a Date-object * @return {Array} Array with all unique Models that fall within the searchargument * @since 0.3 */ getModels : function (aDate, bDate) { var instance = this, returnModels = [], year, month, day, searchDay, modelArrayDay, useFunction; if (Lang.isArray(aDate)) { returnModels = instance._getSelectedModelList({newSelection: aDate, validateDate: true}); } else if (YDate.isValidDate(aDate)) { useFunction = function(model) { if (YArray.indexOf(returnModels, model) === -1) { returnModels.push(model); } }; if (!YDate.isValidDate(bDate) || dayisGreater(aDate, bDate)) { bDate = dateCopyObject(aDate); } searchDay = new Date(aDate.getTime()); do { year = searchDay.getFullYear(); month = searchDay.getMonth(); day = searchDay.getDate(); modelArrayDay = (instance._storedModelDates[year] && instance._storedModelDates[year][month] && instance._storedModelDates[year][month][day]) || []; YArray.each( modelArrayDay, useFunction ); dateAddDays(searchDay, 1); } while (!dayisGreater(searchDay, bDate)); } return returnModels; }, /** * Returns whether a Date has any Models * * @method dateHasModels * @param {Date} oDate Date to be checked * @return {Boolean} * @since 0.3 */ dateHasModels : function (oDate) { var instance = this, storedModelDates = instance._storedModelDates, year = oDate.getFullYear(), month = oDate.getMonth(), day = oDate.getDate(), modelArray = (storedModelDates[year] && storedModelDates[year][month] && storedModelDates[year][month][day]) || [], hasModels = (modelArray.length > 0); return hasModels; }, /** * Returns an Array with the Models that fall in the specified <b>Date</b>. * <br />Sugar-method: the same as when calling the method getModels(oDate); * * @method getModelsInDate * @param {Date} oDate a Date-Object to search within. * @return {Array} Array with the Models within the specified Date * @since 0.3 */ getModelsInDate : function (oDate) { var instance = this; return instance.getModels(oDate); }, /** * Returns an Array with the Models that fall with the <b>Week</b> specified by the Date-argument. * * @method getModelsInWeek * @param {Date} oDate a Date-Object that determines the <b>Week</b> to search within. * @return {Array} Array with the Models within the specified Week * @since 0.3 */ getModelsInWeek : function (oDate) { var instance = this, dayOfWeek = oDate.getDay(), aDate = dateCopyObject(oDate), bDate = dateCopyObject(oDate); dateAddDays(aDate, -dayOfWeek); dateAddDays(bDate, 6-dayOfWeek); return instance.getModels(aDate, bDate); }, /** * Returns an Array with the Models that fall with the <b>Month</b> specified by the Date-argument. * * @method getModelsInMonth * @param {Date} oDate a Date-Object that determines the <b>Month</b> to search within. * @return {Array} Array with the Models within the specified Month * @since 0.3 */ getModelsInMonth : function (oDate) { var instance = this, aDate = dateCopyObject(oDate), bDate = YDate.addMonths(oDate, 1); aDate.setDate(1); bDate.setDate(1); dateAddDays(bDate, -1); return instance.getModels(aDate, bDate); }, /** * Returns an Array with the Models that fall with the <b>Year</b>. * * @method getModelsInYear * @param {int} year The <b>Year</b> to search within. * @return {Array} Array with the Models within the specified Year * @since 0.3 */ getModelsInYear : function (year) { var instance = this, aDate = new Date(year, 0, 1), bDate = new Date(year, 11, 31); return instance.getModels(aDate, bDate); }, /** * Cleans up events * * @method destructor * @protected * @since 0.3 */ destructor: function () { var instance = this; instance._clearSyncSubscriptionModelList(); if (instance._fireModelsEvent) { instance._fireModelsEvent.detach(); } if (instance._afterRenderEvent) { instance._afterRenderEvent.detach(); } }, //-------------------------------------------------------------------------- // Protected properties and methods //-------------------------------------------------------------------------- /** * Clears subscriptions _syncModelListEvent and _syncModelListCheckEvent * * @method _clearSyncSubscriptionModelList * @private * @since 0.3 */ _clearSyncSubscriptionModelList : function () { var instance = this; if (instance._syncModelListEvent) { instance._syncModelListEvent.detach(); } if (instance._syncModelListCheckEvent) { instance._syncModelListCheckEvent.detach(); } }, /** * Setter when changing attribute modelConfig. * Will sync the ModelList with the Calendar. * * @method _setModelConfig * @param {Object} val the new modelConfig * @private * @since 0.3 */ _setModelConfig : function (val) { var instance = this; // do not sync at startup: if (instance._modelConfigInitiated && !instance._internalUpdate) { instance._syncModelList(null, null, val); } else { instance._modelConfigInitiated = true; } }, /** * Setter when changing attribute modelList. * Will sync the ModelList with the Calendar. * * @method _setModelList * @param {ModelList} val the new modelList * @private * @since 0.3 */ _setModelList : function (val) { var instance = this, modelconfig = instance.get('modelConfig') || {}, modeldateattr = modelconfig.date, firstModel, valid; // search datefield when not available if (!modeldateattr && val && val.size()>0) { firstModel = val.item(0); YObject.some( firstModel.getAttrs(), function(val, key) { valid = Lang.isDate(val); if (valid) { modeldateattr = key; } return valid; } ); if (valid) { instance._internalUpdate = true; modelconfig.date = modeldateattr; instance.set('modelConfig', modelconfig); instance._internalUpdate = false; } else { } } instance._clearSyncSubscriptionModelList(); if (val) { instance._syncModelListEvent = val.after(['add', 'remove', 'reset'], instance._syncModelList, instance); instance._syncModelListCheckEvent = val.after('*:change', instance._checkSyncModelList, instance); } // do not sync at startup: if (instance._modelListInitiated || val) { instance._syncModelList(null, val); } else { instance._modelListInitiated = true; } }, /** * Subscriber to this.modelList.after('*:change') * Might call _syncModelList, but only if the Models-attribute that is changed is one of these: * date, enddate, count, intervalMinutes, intervalHours, intervalDays or intervalMonths * * @method _checkSyncModelList * @param {EventTarget} e * @private * @since 0.3 */ _checkSyncModelList : function (e) { var instance = this, modelconfig = instance.get('modelConfig') || {}, modelconfigDate = modelconfig.date || '', modelconfigEnddate = modelconfig.enddate || '', modelconfigCount = modelconfig.count || '', modelconfigIntervalMinutes = modelconfig.intervalMinutes || '', modelconfigIntervalHours = modelconfig.intervalHours || '', modelconfigIntervalDays = modelconfig.intervalDays || '', modelconfigIntervalMonths = modelconfig.intervalMonths || ''; if (e.changed[modelconfigDate] || e.changed[modelconfigEnddate] || e.changed[modelconfigCount] || e.changed[modelconfigIntervalMinutes] || e.changed[modelconfigIntervalHours] || e.changed[modelconfigIntervalDays] || e.changed[modelconfigIntervalMonths]) { if (instance.get('rendered')) { instance._doSyncModelList(); } else { instance._afterRenderEvent = instance.after( 'render', Y.bind(instance._doSyncModelList, instance) ); } } else { } }, /** * Will call _doSyncModelList, but waits until the Calendar is rendered. * * @method _syncModelList * @param {EventTarget} e * @param {EventTarget} [attrmodellist] for internal use: when coming from _setModelList * it holds the new value for modelList * @param {EventTarget} [attrmodelconfig] for internal use: when coming from _setModelConfig * it holds the new value for modelConfig * @private * @since 0.3 */ _syncModelList : function (e, attrmodellist, attrmodelconfig) { var instance = this; if (instance.get('rendered')) { instance._doSyncModelList(attrmodellist, attrmodelconfig); } else { instance._afterRenderEvent = instance.after( 'render', Y.bind(instance._doSyncModelList, instance, attrmodellist, attrmodelconfig) ); } }, /** * Syncs the modelList with Calendar using the attributes defined in modelConfig. * * @method _doSyncModelList * @param {EventTarget} [attrmodellist] for internal use: when coming from _setModelList * it holds the new value for modelList * @param {EventTarget} [attrmodelconfig] for internal use: when coming from _setModelConfig * it holds the new value for modelConfig * @private * @since 0.3 */ _doSyncModelList : function (attrmodellist, attrmodelconfig) { var instance = this, modellist = attrmodellist || instance.get('modelList'), modelconfig = attrmodelconfig || instance.get('modelConfig') || {}, attrDate = modelconfig && modelconfig.date, attrEnddate = modelconfig && modelconfig.enddate, attrCount = modelconfig && modelconfig.count, attrIntervalMinutes = modelconfig && modelconfig.intervalMinutes, attrIntervalHours = modelconfig && modelconfig.intervalHours, attrIntervalDays = modelconfig && modelconfig.intervalDays, attrIntervalMonths = modelconfig && modelconfig.intervalMonths, dates = [], modelfunc, pushDate, i, prevDate, prevCount; instance.clearMarkedDates(modellist && attrDate); prevCount = YObject.size(instance._storedModelDates); instance._storedModelDates = {}; if (modellist && attrDate) { // I choosed to split it up in 4 scenario's. This is a bit more code, but it makes runtime faster when // an easier configuration is used (probably most of the cases) if (!attrEnddate && !attrCount) { modelfunc = function(model) { var modelDate = modellist.getModelAttr(model, attrDate); if (dateIsValid(modelDate)) { dates.push(modelDate); instance._storeModelDate(model, modelDate); } }; } else if (attrEnddate && !attrCount) { modelfunc = function(model) { var modelDate = modellist.getModelAttr(model, attrDate), modelEndDate = modellist.getModelAttr(model, attrEnddate) || modelDate; if (dateIsValid(modelDate)) { if (!dateIsValid(modelEndDate)) { modelEndDate = modelDate; } pushDate = dateCopyObject(modelDate); do { dates.push(dateCopyObject(pushDate)); instance._storeModelDate(model, pushDate); dateAddDays(pushDate, 1); } while (dayisGreaterOrEqual(modelEndDate, pushDate)); } }; } else if (!attrEnddate && attrCount) { modelfunc = function(model) { var modelDate = modellist.getModelAttr(model, attrDate), modelCount = modellist.getModelAttr(model, attrCount) || 1, modelIntervalMinutes = (attrIntervalMinutes && modellist.getModelAttr(model, attrIntervalMinutes)), modelIntervalHours = (attrIntervalHours && modellist.getModelAttr(model, attrIntervalHours)), modelIntervalDays = (attrIntervalDays && modellist.getModelAttr(model, attrIntervalDays)), modelIntervalMonths = (attrIntervalMonths && modellist.getModelAttr(model, attrIntervalMonths)), stepMinutes; if (dateIsValid(modelDate)) { if (!Lang.isNumber(modelCount)) { modelCount = 1; } if (!Lang.isNumber(modelIntervalMinutes)) { modelIntervalMinutes = 0; } if (!Lang.isNumber(modelIntervalHours)) { modelIntervalHours = 0; } if (!Lang.isNumber(modelIntervalDays)) { modelIntervalDays = 0; } if (!Lang.isNumber(modelIntervalMonths)) { modelIntervalMonths = 0; } stepMinutes = (1440*modelIntervalDays) + (60*modelIntervalHours) + modelIntervalMinutes; if ((stepMinutes===0) && (modelIntervalMonths===0)) { stepMinutes = 1440; } pushDate = dateCopyObject(modelDate); prevDate = new Date(0); for (i=0; i<modelCount; i++) { if (!dateEqualDays(pushDate, prevDate)) { dates.push(dateCopyObject(pushDate)); instance._storeModelDate(model, pushDate); } dateCopyValues(pushDate, prevDate); if (stepMinutes>0) { dateAddMinutes(pushDate, stepMinutes); } if (modelIntervalMonths>0) { dateAddMonths(pushDate, modelIntervalMonths); } } } }; } else if (attrEnddate && attrCount) { // Make pushDate a Date object, so we can copy Date-values to it pushDate = new Date(0); modelfunc = function(model) { var modelDate = modellist.getModelAttr(model, attrDate), modelEndDate = modellist.getModelAttr(model, attrEnddate) || modelDate, modelCount = modellist.getModelAttr(model, attrCount) || 1, modelIntervalMinutes = (attrIntervalMinutes && modellist.getModelAttr(model, attrIntervalMinutes)), modelIntervalHours = (attrIntervalHours && modellist.getModelAttr(model, attrIntervalHours)), modelIntervalDays = (attrIntervalDays && modellist.getModelAttr(model, attrIntervalDays)), modelIntervalMonths = (attrIntervalMonths && modellist.getModelAttr(model, attrIntervalMonths)), stepMinutes, startPushDate, endPushDate; if (dateIsValid(modelDate)) { if (!dateIsValid(modelEndDate)) { modelEndDate = modelDate; } if (!Lang.isNumber(modelCount)) { modelCount = 1; } if (!Lang.isNumber(modelIntervalMinutes)) { modelIntervalMinutes = 0; } if (!Lang.isNumber(modelIntervalHours)) { modelIntervalHours = 0; } if (!Lang.isNumber(modelIntervalDays)) { modelIntervalDays = 0; } if (!Lang.isNumber(modelIntervalMonths)) { modelIntervalMonths = 0; } stepMinutes = (1440*modelIntervalDays) + (60*modelIntervalHours) + modelIntervalMinutes; if ((stepMinutes===0) && (modelIntervalMonths===0)) { stepMinutes = 1440; } startPushDate = dateCopyObject(modelDate); endPushDate = dateCopyObject(modelEndDate); prevDate = new Date(0); for (i=0; i<modelCount; i++) { dateCopyValues(startPushDate, pushDate); do { if (dayisGreater(pushDate, prevDate)) { dates.push(dateCopyObject(pushDate)); instance._storeModelDate(model, pushDate); } dateAddDays(pushDate, 1); } while (dayisGreaterOrEqual(endPushDate, pushDate)); dateCopyValues(pushDate, prevDate); // correct prevDate --> because pushDate has been added 1 day that has not been handled dateAddDays(prevDate, -1); if (stepMinutes>0) { dateAddMinutes(startPushDate, stepMinutes); dateAddMinutes(endPushDate, stepMinutes); } if (modelIntervalMonths>0) { dateAddMonths(startPushDate, modelIntervalMonths); dateAddMonths(endPushDate, modelIntervalMonths); } } } }; } modellist.each(modelfunc); instance.markDates(dates); instance._fireSelectedModels(); } else { if (prevCount>0) { instance._fireSelectedModels(); } } }, /** * Stores the model in an internal object: _storedModelDates * _storedModelDates is used to retrieve the models when a date is selected. Every model could * mark multiple Dates in case they have an <i>interval</i> set and/or in case an <i>enddate</i> is available. * * @method _storeModelDate * @param {Y.Model} model The model to store * @param {Date} oDate The Date that the model should mark the Calendar * @private * @since 0.3 */ _storeModelDate : function(model, oDate) { var instance = this, year = oDate.getFullYear(), month = oDate.getMonth(), day = oDate.getDate(); if (!hasKey(instance._storedModelDates, year)) { instance._storedModelDates[year] = {}; } if (!hasKey(instance._storedModelDates[year], month)) { instance._storedModelDates[year][month] = {}; } if (!hasKey(instance._storedModelDates[year][month], day)) { // define as an Array, NOT an object --> needs to be filled with Models instance._storedModelDates[year][month][day] = []; } instance._storedModelDates[year][month][day].push(model); }, /** * A utility method that fires the selected Models on a selectionChange event or when syncing the modelList. * * @method _fireSelectedModels * @param {eventTarget} [e] The eventTarget after a selectionChange * @private * @since 0.3 */ _fireSelectedModels : function (e) { var instance = this; /** * Is fired when the user changes the dateselection. In case multiple Dates are selected and the same Model is * available in more than one Date: the Model is only once in the resultarray. Meaning: only unique Models are returned. * @event modelSelectionChange * @param {Array} newModelSelection contains [Model] with all modelList's unique original Models that are selected. * @param {Array} selectedDates contains [Date] with all selected Dates (passed through by the Calendar-instance) * @since 0.3 **/ instance.fire("modelSelectionChange", { newModelSelection: instance._getSelectedModelList(e), selectedDates: (e && e.newSelection) || instance.get('selectedDates') }); }, /** * Retrieves the unique Models that are available in the selectedDates. * * @method _getSelectedModelList * @param {eventTarget} [e] The eventTarget after a selectionChange. When not provided, the attribute 'selectedDates' is taken. * @private * @protected * @return {Array} Unique list of Models that are present in selectedDates * @since 0.3 */ _getSelectedModelList : function(e) { var instance = this, dateselection = (e && e.newSelection) || instance.get('selectedDates'), modelArray = []; YArray.each( dateselection, function(oDate) { // e.validateDate is undefined when comes from event --> in that case we always are sure // the array consist only Date-objects if ((e && !e.validateDate) || YDate.isValidDate(oDate)) { var year = oDate.getFullYear(), month = oDate.getMonth(), day = oDate.getDate(), modelArrayDay = (instance._storedModelDates[year] && instance._storedModelDates[year][month] && instance._storedModelDates[year][month][day]) || []; YArray.each( modelArrayDay, function(model) { if (YArray.indexOf(modelArray, model) === -1) { modelArray.push(model); } } ); } } ); return modelArray; } }, true); Y.Calendar.ITSACalendarModelList = ITSACalendarModelList; Y.Base.mix(Y.Calendar, [ITSACalendarModelList]); }, 'gallery-2013.07.03-22-52', { "requires": [ "base-build", "node-base", "calendar-base", "model", "model-list", "lazy-model-list", "datatype-date-math", "gallery-itsacalendarmarkeddates" ] });
define("clipart/Refresh", [ "dojo/_base/declare", "clipart/_clipart" ], function(declare, _clipart){ return declare("clipart.Refresh", [_clipart], { }); });
/* Language: SubUnit Author: Sergey Bronnikov <sergeyb@bronevichok.ru> Website: https://pypi.org/project/python-subunit/ */ function subunit(hljs) { var DETAILS = { className: 'string', begin: '\\[\n(multipart)?', end: '\\]\n' }; var TIME = { className: 'string', begin: '\\d{4}-\\d{2}-\\d{2}(\\s+)\\d{2}:\\d{2}:\\d{2}\.\\d+Z' }; var PROGRESSVALUE = { className: 'string', begin: '(\\+|-)\\d+' }; var KEYWORDS = { className: 'keyword', relevance: 10, variants: [ { begin: '^(test|testing|success|successful|failure|error|skip|xfail|uxsuccess)(:?)\\s+(test)?' }, { begin: '^progress(:?)(\\s+)?(pop|push)?' }, { begin: '^tags:' }, { begin: '^time:' } ], }; return { name: 'SubUnit', case_insensitive: true, contains: [ DETAILS, TIME, PROGRESSVALUE, KEYWORDS ] }; } module.exports = subunit;
var should = require('should'); var serverController = require("../controllers/server"); describe("Server", function(){ it('start one server', function(done) { serverController.startup(8000, 1, done); }); it('start two server', function(done) { serverController.startup(8000, 2, done); }); it("list", function(done){ serverController.list(function(err, res){ res.length.should.eql(3); done(); }); }); it.skip("stop by file", function(done){ serverController.list(function(err, res){ serverController.stop(res[0].file, function(err, res){ res.should.be.an.Object; done(); }); }); }); it("stopAll", function(done){ serverController.stopAll(function(err, res){ res.should.be.an.Object; done(); }); }); });
var searchData= [ ['bool1',['bool1',['../a00732.html#gaddcd7aa2e30e61af5b38660613d3979e',1,'glm']]], ['bool1x1',['bool1x1',['../a00732.html#ga7f895c936f0c29c8729afbbf22806090',1,'glm']]], ['bool2',['bool2',['../a00732.html#gaa09ab65ec9c3c54305ff502e2b1fe6d9',1,'glm']]], ['bool2x2',['bool2x2',['../a00732.html#gadb3703955e513632f98ba12fe051ba3e',1,'glm']]], ['bool2x3',['bool2x3',['../a00732.html#ga9ae6ee155d0f90cb1ae5b6c4546738a0',1,'glm']]], ['bool2x4',['bool2x4',['../a00732.html#ga4d7fa65be8e8e4ad6d920b45c44e471f',1,'glm']]], ['bool3',['bool3',['../a00732.html#ga99629f818737f342204071ef8296b2ed',1,'glm']]], ['bool3x2',['bool3x2',['../a00732.html#gac7d7311f7e0fa8b6163d96dab033a755',1,'glm']]], ['bool3x3',['bool3x3',['../a00732.html#ga6c97b99aac3e302053ffb58aace9033c',1,'glm']]], ['bool3x4',['bool3x4',['../a00732.html#gae7d6b679463d37d6c527d478fb470fdf',1,'glm']]], ['bool4',['bool4',['../a00732.html#ga13c3200b82708f73faac6d7f09ec91a3',1,'glm']]], ['bool4x2',['bool4x2',['../a00732.html#ga9ed830f52408b2f83c085063a3eaf1d0',1,'glm']]], ['bool4x3',['bool4x3',['../a00732.html#gad0f5dc7f22c2065b1b06d57f1c0658fe',1,'glm']]], ['bool4x4',['bool4x4',['../a00732.html#ga7d2a7d13986602ae2896bfaa394235d4',1,'glm']]], ['bvec1',['bvec1',['../a00685.html#ga067af382616d93f8e850baae5154cdcc',1,'glm']]], ['bvec2',['bvec2',['../a00699.html#ga0b6123e03653cc1bbe366fc55238a934',1,'glm']]], ['bvec3',['bvec3',['../a00699.html#ga197151b72dfaf289daf98b361760ffe7',1,'glm']]], ['bvec4',['bvec4',['../a00699.html#ga9f7b9712373ff4342d9114619b55f5e3',1,'glm']]], ['byte',['byte',['../a00771.html#ga3005cb0d839d546c616becfa6602c607',1,'glm']]] ];
const init = ({ next_disabled, dev }) => new Promise(resolve => { // Disabled? if (next_disabled) return resolve(null) // Create NextJS const nextjs = require('next')({ dev }) // Preparing... nextjs.prepare().then(() => resolve(nextjs)) }) module.exports = init
import T from './Translated'; import Modal from './Modal'; import {has} from '../Helpers'; export default class ConfirmDeleteModal extends React.Component { constructor(props) { has(props, 'modalId'); has(props, 'modalBody'); has(props, 'onDelete'); super(props); } render() { let modalTitle = <T k='confirmdeletemodal.title'>Confirm deletion</T>; let modalFooter = <div> <button type="button" className="btn btn-default" data-dismiss="modal"> <T k='confirmdeletemodal.dont_delete'>Don't delete</T> </button> <button type="button" className="btn btn-danger" data-dismiss="modal" onClick={this.props.onDelete}> <T k='confirmdeletemodal.confirm'>Confirm deletion</T> </button> </div>; return <Modal modalId={this.props.modalId} modalBody={this.props.modalBody} modalTitle={modalTitle} modalFooter={modalFooter} />; } }
import Ember from 'ember'; export default Ember.Route.extend({ model() { return this.get('store').findAll('todo'); } });
console.log('test'); console.log('foo'); console.log('bar'); console.log('baz');
function isAutoComplete(keyboardProxy) { var typeahead = keyboardProxy.data("typeahead"); if (typeahead && typeahead.$menu.is(":visible")) { return typeahead; } else { return false; } } /** * Autocomplete editor * @param {Object} instance Handsontable instance * @param {Element} td Table cell where to render * @param {Number} row * @param {Number} col * @param {String|Number} prop Row object property name * @param {Object} keyboardProxy jQuery element of keyboard proxy that contains current editing value * @param {Object} cellProperties Cell properites (shared by cell renderer and editor) */ Handsontable.AutocompleteEditor = function (instance, td, row, col, prop, keyboardProxy, cellProperties) { var typeahead = keyboardProxy.data('typeahead') , i , dontHide = false; if (!typeahead) { keyboardProxy.typeahead(cellProperties.options || {}); typeahead = keyboardProxy.data('typeahead'); typeahead._show = typeahead.show; typeahead._hide = typeahead.hide; typeahead._render = typeahead.render; typeahead._highlighter = typeahead.highlighter; } else { if (cellProperties.options) { /* overwrite typeahead options (most importantly `items`) */ for (i in cellProperties) { if (cellProperties.hasOwnProperty(i)) { typeahead.options[i] = cellProperties.options[i]; } } } typeahead.$menu.off(); //remove previous typeahead bindings keyboardProxy.off(); //remove previous typeahead bindings. Removing this will cause prepare to register 2 keydown listeners in typeahead typeahead.listen(); //add typeahead bindings } typeahead.minLength = 0; typeahead.highlighter = typeahead._highlighter; typeahead.show = function () { if (keyboardProxy.parent().hasClass('htHidden')) { return; } return typeahead._show.call(this); }; typeahead.hide = function () { if (!dontHide) { dontHide = false; //set to true by dblclick handler, otherwise appears and disappears immediately after double click return typeahead._hide.call(this); } }; typeahead.lookup = function () { var items; this.query = this.$element.val(); items = $.isFunction(this.source) ? this.source(this.query, $.proxy(this.process, this)) : this.source; return items ? this.process(items) : this; }; typeahead.matcher = function () { return true; }; typeahead.select = function () { var val = this.$menu.find('.active').attr('data-value') || keyboardProxy.val(); destroyer(true); instance.setDataAtCell(row, prop, typeahead.updater(val)); return this.hide(); }; typeahead.render = function (items) { typeahead._render.call(this, items); if (!cellProperties.strict) { this.$menu.find('li:eq(0)').removeClass('active'); } return this; }; /* overwrite typeahead methods (matcher, sorter, highlighter, updater, etc) if provided in cellProperties */ for (i in cellProperties) { if (cellProperties.hasOwnProperty(i)) { typeahead[i] = cellProperties[i]; } } var wasDestroyed = false; keyboardProxy.on("keydown.editor", function (event) { switch (event.keyCode) { case 27: /* ESC */ dontHide = false; break; case 37: /* arrow left */ case 39: /* arrow right */ case 38: /* arrow up */ case 40: /* arrow down */ case 9: /* tab */ case 13: /* return/enter */ if (!keyboardProxy.parent().hasClass('htHidden')) { event.stopImmediatePropagation(); } event.preventDefault(); } }); keyboardProxy.on("keyup.editor", function (event) { if (wasDestroyed) { return; } switch (event.keyCode) { case 9: /* tab */ case 13: /* return/enter */ if (!isAutoComplete(keyboardProxy)) { var ev = $.Event('keyup'); ev.keyCode = 113; //113 triggers lookup, in contrary to 13 or 9 which only trigger hide keyboardProxy.trigger(ev); } else { setTimeout(function () { //so pressing enter will move one row down after change is applied by 'select' above var ev = $.Event('keydown'); ev.keyCode = event.keyCode; keyboardProxy.parent().trigger(ev); }, 10); } break; default: if (!Handsontable.helper.isPrintableChar(event.keyCode)) { //otherwise Del or F12 would open suggestions list event.stopImmediatePropagation(); } } } ); var textDestroyer = Handsontable.TextEditor(instance, td, row, col, prop, keyboardProxy, cellProperties); function onDblClick() { dontHide = true; setTimeout(function () { //otherwise is misaligned in IE9 keyboardProxy.data('typeahead').lookup(); }, 1); } $(td).on('dblclick.editor', onDblClick); instance.container.find('.htBorder.current').on('dblclick.editor', onDblClick); var destroyer = function (isCancelled) { wasDestroyed = true; keyboardProxy.off(); //remove typeahead bindings textDestroyer(isCancelled); dontHide = false; if (isAutoComplete(keyboardProxy)) { isAutoComplete(keyboardProxy).hide(); } }; return destroyer; };
'use strict'; const DataTypes = require('./data-types'); const SqlString = require('./sql-string'); const _ = require('lodash'); const parameterValidator = require('./utils/parameter-validator'); const Logger = require('./utils/logger'); const uuid = require('uuid'); const Promise = require('./promise'); const operators = require('./operators'); const operatorsArray = _.values(operators); const primitives = ['string', 'number', 'boolean']; let inflection = require('inflection'); const logger = new Logger(); exports.Promise = Promise; exports.debug = logger.debug.bind(logger); exports.deprecate = logger.deprecate.bind(logger); exports.warn = logger.warn.bind(logger); exports.getLogger = () => logger ; function useInflection(_inflection) { inflection = _inflection; } exports.useInflection = useInflection; function camelizeIf(str, condition) { let result = str; if (condition) { result = camelize(str); } return result; } exports.camelizeIf = camelizeIf; function underscoredIf(str, condition) { let result = str; if (condition) { result = underscore(str); } return result; } exports.underscoredIf = underscoredIf; function isPrimitive(val) { return primitives.indexOf(typeof val) !== -1; } exports.isPrimitive = isPrimitive; // Same concept as _.merge, but don't overwrite properties that have already been assigned function mergeDefaults(a, b) { return _.mergeWith(a, b, objectValue => { // If it's an object, let _ handle it this time, we will be called again for each property if (!_.isPlainObject(objectValue) && objectValue !== undefined) { return objectValue; } }); } exports.mergeDefaults = mergeDefaults; // An alternative to _.merge, which doesn't clone its arguments // Cloning is a bad idea because options arguments may contain references to sequelize // models - which again reference database libs which don't like to be cloned (in particular pg-native) function merge() { const result = {}; for (const obj of arguments) { _.forOwn(obj, (value, key) => { if (typeof value !== 'undefined') { if (!result[key]) { result[key] = value; } else if (_.isPlainObject(value) && _.isPlainObject(result[key])) { result[key] = merge(result[key], value); } else if (Array.isArray(value) && Array.isArray(result[key])) { result[key] = value.concat(result[key]); } else { result[key] = value; } } }); } return result; } exports.merge = merge; function lowercaseFirst(s) { return s[0].toLowerCase() + s.slice(1); } exports.lowercaseFirst = lowercaseFirst; function uppercaseFirst(s) { return s[0].toUpperCase() + s.slice(1); } exports.uppercaseFirst = uppercaseFirst; function spliceStr(str, index, count, add) { return str.slice(0, index) + add + str.slice(index + count); } exports.spliceStr = spliceStr; function camelize(str) { return str.trim().replace(/[-_\s]+(.)?/g, (match, c) => c.toUpperCase()); } exports.camelize = camelize; function underscore(str) { return inflection.underscore(str); } exports.underscore = underscore; function format(arr, dialect) { const timeZone = null; // Make a clone of the array beacuse format modifies the passed args return SqlString.format(arr[0], arr.slice(1), timeZone, dialect); } exports.format = format; function formatNamedParameters(sql, parameters, dialect) { const timeZone = null; return SqlString.formatNamedParameters(sql, parameters, timeZone, dialect); } exports.formatNamedParameters = formatNamedParameters; function cloneDeep(obj) { obj = obj || {}; return _.cloneDeepWith(obj, elem => { // Do not try to customize cloning of arrays or POJOs if (Array.isArray(elem) || _.isPlainObject(elem)) { return undefined; } // Don't clone stuff that's an object, but not a plain one - fx example sequelize models and instances if (typeof elem === 'object') { return elem; } // Preserve special data-types like `fn` across clones. _.get() is used for checking up the prototype chain if (elem && typeof elem.clone === 'function') { return elem.clone(); } }); } exports.cloneDeep = cloneDeep; /* Expand and normalize finder options */ function mapFinderOptions(options, Model) { if (Model._hasVirtualAttributes && Array.isArray(options.attributes)) { for (const attribute of options.attributes) { if (Model._isVirtualAttribute(attribute) && Model.rawAttributes[attribute].type.fields) { options.attributes = options.attributes.concat(Model.rawAttributes[attribute].type.fields); } } options.attributes = _.without.apply(_, [options.attributes].concat(Model._virtualAttributes)); options.attributes = _.uniq(options.attributes); } mapOptionFieldNames(options, Model); return options; } exports.mapFinderOptions = mapFinderOptions; /* Used to map field names in attributes and where conditions */ function mapOptionFieldNames(options, Model) { if (Array.isArray(options.attributes)) { options.attributes = options.attributes.map(attr => { // Object lookups will force any variable to strings, we don't want that for special objects etc if (typeof attr !== 'string') return attr; // Map attributes to aliased syntax attributes if (Model.rawAttributes[attr] && attr !== Model.rawAttributes[attr].field) { return [Model.rawAttributes[attr].field, attr]; } return attr; }); } if (options.where && _.isPlainObject(options.where)) { options.where = mapWhereFieldNames(options.where, Model); } return options; } exports.mapOptionFieldNames = mapOptionFieldNames; function mapWhereFieldNames(attributes, Model) { if (attributes) { getComplexKeys(attributes).forEach(attribute => { const rawAttribute = Model.rawAttributes[attribute]; if (rawAttribute && rawAttribute.field !== rawAttribute.fieldName) { attributes[rawAttribute.field] = attributes[attribute]; delete attributes[attribute]; } if (_.isPlainObject(attributes[attribute]) && !(rawAttribute && ( rawAttribute.type instanceof DataTypes.HSTORE || rawAttribute.type instanceof DataTypes.JSON))) { // Prevent renaming of HSTORE & JSON fields attributes[attribute] = mapOptionFieldNames({ where: attributes[attribute] }, Model).where; } if (Array.isArray(attributes[attribute])) { attributes[attribute] = attributes[attribute].map(where => { if (_.isPlainObject(where)) { return mapWhereFieldNames(where, Model); } return where; }); } }); } return attributes; } exports.mapWhereFieldNames = mapWhereFieldNames; /* Used to map field names in values */ function mapValueFieldNames(dataValues, fields, Model) { const values = {}; for (const attr of fields) { if (dataValues[attr] !== undefined && !Model._isVirtualAttribute(attr)) { // Field name mapping if (Model.rawAttributes[attr] && Model.rawAttributes[attr].field && Model.rawAttributes[attr].field !== attr) { values[Model.rawAttributes[attr].field] = dataValues[attr]; } else { values[attr] = dataValues[attr]; } } } return values; } exports.mapValueFieldNames = mapValueFieldNames; function isColString(value) { return typeof value === 'string' && value.substr(0, 1) === '$' && value.substr(value.length - 1, 1) === '$'; } exports.isColString = isColString; function argsArePrimaryKeys(args, primaryKeys) { let result = args.length === Object.keys(primaryKeys).length; if (result) { _.each(args, arg => { if (result) { if (['number', 'string'].indexOf(typeof arg) !== -1) { result = true; } else { result = arg instanceof Date || Buffer.isBuffer(arg); } } }); } return result; } exports.argsArePrimaryKeys = argsArePrimaryKeys; function canTreatArrayAsAnd(arr) { return arr.reduce((treatAsAnd, arg) => { if (treatAsAnd) { return treatAsAnd; } else { return _.isPlainObject(arg); } }, false); } exports.canTreatArrayAsAnd = canTreatArrayAsAnd; function combineTableNames(tableName1, tableName2) { return tableName1.toLowerCase() < tableName2.toLowerCase() ? tableName1 + tableName2 : tableName2 + tableName1; } exports.combineTableNames = combineTableNames; function singularize(str) { return inflection.singularize(str); } exports.singularize = singularize; function pluralize(str) { return inflection.pluralize(str); } exports.pluralize = pluralize; function removeCommentsFromFunctionString(s) { s = s.replace(/\s*(\/\/.*)/g, ''); s = s.replace(/(\/\*[\n\r\s\S]*?\*\/)/mg, ''); return s; } exports.removeCommentsFromFunctionString = removeCommentsFromFunctionString; function toDefaultValue(value) { if (typeof value === 'function') { const tmp = value(); if (tmp instanceof DataTypes.ABSTRACT) { return tmp.toSql(); } else { return tmp; } } else if (value instanceof DataTypes.UUIDV1) { return uuid.v1(); } else if (value instanceof DataTypes.UUIDV4) { return uuid.v4(); } else if (value instanceof DataTypes.NOW) { return now(); } else if (_.isPlainObject(value) || _.isArray(value)) { return _.clone(value); } else { return value; } } exports.toDefaultValue = toDefaultValue; /** * Determine if the default value provided exists and can be described * in a db schema using the DEFAULT directive. * * @param {*} value Any default value. * @return {boolean} yes / no. * @private */ function defaultValueSchemable(value) { if (typeof value === 'undefined') { return false; } // TODO this will be schemable when all supported db // have been normalized for this case if (value instanceof DataTypes.NOW) { return false; } if (value instanceof DataTypes.UUIDV1 || value instanceof DataTypes.UUIDV4) { return false; } if (_.isFunction(value)) { return false; } return true; } exports.defaultValueSchemable = defaultValueSchemable; function removeNullValuesFromHash(hash, omitNull, options) { let result = hash; options = options || {}; options.allowNull = options.allowNull || []; if (omitNull) { const _hash = {}; _.forIn(hash, (val, key) => { if (options.allowNull.indexOf(key) > -1 || key.match(/Id$/) || val !== null && val !== undefined) { _hash[key] = val; } }); result = _hash; } return result; } exports.removeNullValuesFromHash = removeNullValuesFromHash; function stack() { const orig = Error.prepareStackTrace; Error.prepareStackTrace = (_, stack) => stack; const err = new Error(); Error.captureStackTrace(err, stack); const errStack = err.stack; Error.prepareStackTrace = orig; return errStack; } exports.stack = stack; function sliceArgs(args, begin) { begin = begin || 0; const tmp = new Array(args.length - begin); for (let i = begin; i < args.length; ++i) { tmp[i - begin] = args[i]; } return tmp; } exports.sliceArgs = sliceArgs; function now(dialect) { const now = new Date(); if (['mysql', 'postgres', 'sqlite', 'mssql'].indexOf(dialect) === -1) { now.setMilliseconds(0); } return now; } exports.now = now; // Note: Use the `quoteIdentifier()` and `escape()` methods on the // `QueryInterface` instead for more portable code. const TICK_CHAR = '`'; exports.TICK_CHAR = TICK_CHAR; function addTicks(s, tickChar) { tickChar = tickChar || TICK_CHAR; return tickChar + removeTicks(s, tickChar) + tickChar; } exports.addTicks = addTicks; function removeTicks(s, tickChar) { tickChar = tickChar || TICK_CHAR; return s.replace(new RegExp(tickChar, 'g'), ''); } exports.removeTicks = removeTicks; /** * Receives a tree-like object and returns a plain object which depth is 1. * * - Input: * * { * name: 'John', * address: { * street: 'Fake St. 123', * coordinates: { * longitude: 55.6779627, * latitude: 12.5964313 * } * } * } * * - Output: * * { * name: 'John', * address.street: 'Fake St. 123', * address.coordinates.latitude: 55.6779627, * address.coordinates.longitude: 12.5964313 * } * * @param value, an Object * @return Object, an flattened object * @private */ function flattenObjectDeep(value) { if (!_.isPlainObject(value)) return value; const flattenedObj = {}; function flattenObject(obj, subPath) { Object.keys(obj).forEach(key => { const pathToProperty = subPath ? `${subPath}.${key}` : `${key}`; if (typeof obj[key] === 'object') { flattenObject(obj[key], flattenedObj, pathToProperty); } else { flattenedObj[pathToProperty] = _.get(obj, key); } }); return flattenedObj; } return flattenObject(value, undefined); } exports.flattenObjectDeep = flattenObjectDeep; /** * Utility functions for representing SQL functions, and columns that should be escaped. * Please do not use these functions directly, use Sequelize.fn and Sequelize.col instead. * @private */ class SequelizeMethod {} exports.SequelizeMethod = SequelizeMethod; class Fn extends SequelizeMethod { constructor(fn, args) { super(); this.fn = fn; this.args = args; } clone() { return new Fn(this.fn, this.args); } } exports.Fn = Fn; class Col extends SequelizeMethod { constructor(col) { super(); if (arguments.length > 1) { col = this.sliceArgs(arguments); } this.col = col; } } exports.Col = Col; class Cast extends SequelizeMethod { constructor(val, type, json) { super(); this.val = val; this.type = (type || '').trim(); this.json = json || false; } } exports.Cast = Cast; class Literal extends SequelizeMethod { constructor(val) { super(); this.val = val; } } exports.Literal = Literal; class Json extends SequelizeMethod { constructor(conditionsOrPath, value) { super(); if (_.isObject(conditionsOrPath)) { this.conditions = conditionsOrPath; } else { this.path = conditionsOrPath; if (value) { this.value = value; } } } } exports.Json = Json; class Where extends SequelizeMethod { constructor(attribute, comparator, logic) { super(); if (logic === undefined) { logic = comparator; comparator = '='; } this.attribute = attribute; this.comparator = comparator; this.logic = logic; } } exports.Where = Where; exports.validateParameter = parameterValidator; exports.mapIsolationLevelStringToTedious = (isolationLevel, tedious) => { if (!tedious) { throw new Error('An instance of tedious lib should be passed to this function'); } const tediousIsolationLevel = tedious.ISOLATION_LEVEL; switch (isolationLevel) { case 'READ_UNCOMMITTED': return tediousIsolationLevel.READ_UNCOMMITTED; case 'READ_COMMITTED': return tediousIsolationLevel.READ_COMMITTED; case 'REPEATABLE_READ': return tediousIsolationLevel.REPEATABLE_READ; case 'SERIALIZABLE': return tediousIsolationLevel.SERIALIZABLE; case 'SNAPSHOT': return tediousIsolationLevel.SNAPSHOT; } }; //Collection of helper methods to make it easier to work with symbol operators /** * getOperators * @param {Object} obj * @return {Array<Symbol>} All operators properties of obj * @private */ function getOperators(obj) { return _.intersection(Object.getOwnPropertySymbols(obj || {}), operatorsArray); } exports.getOperators = getOperators; /** * getComplexKeys * @param {Object} obj * @return {Array<String|Symbol>} All keys including operators * @private */ function getComplexKeys(obj) { return getOperators(obj).concat(_.keys(obj)); } exports.getComplexKeys = getComplexKeys; /** * getComplexSize * @param {Object|Array} obj * @return {Integer} Length of object properties including operators if obj is array returns its length * @private */ function getComplexSize(obj) { return Array.isArray(obj) ? obj.length : getComplexKeys(obj).length; } exports.getComplexSize = getComplexSize; /** * Returns true if a where clause is empty, even with Symbols * * @param {Object} obj * @return {Boolean} * @private */ function isWhereEmpty(obj) { return _.isEmpty(obj) && getOperators(obj).length === 0; } exports.isWhereEmpty = isWhereEmpty;
define(["npm:aurelia-history-browser@1.0.0-beta.1/aurelia-history-browser"], function(main) { return main; });
/** * @class AjaxBootstrapSelect * * @param {jQuery|HTMLElement} element * The select element this plugin is to affect. * @param {Object} [options={}] * The options used to affect the desired functionality of this plugin. * * @return {AjaxBootstrapSelect|null} * A new instance of this class or null if unable to instantiate. */ var AjaxBootstrapSelect = function (element, options) { var i, l, plugin = this; options = options || {}; /** * The select element this plugin is being attached to. * @type {jQuery} */ this.$element = $(element); /** * The merged default and passed options. * @type {Object} */ this.options = $.extend(true, {}, $.fn.ajaxSelectPicker.defaults, options); /** * Used for logging error messages. * @type {Number} */ this.LOG_ERROR = 1; /** * Used for logging warning messages. * @type {Number} */ this.LOG_WARNING = 2; /** * Used for logging informational messages. * @type {Number} */ this.LOG_INFO = 3; /** * Used for logging debug messages. * @type {Number} */ this.LOG_DEBUG = 4; /** * The jqXHR object of the last request, false if there was none. * @type {jqXHR|Boolean} */ this.lastRequest = false; /** * The previous query that was requested. * @type {String} */ this.previousQuery = ''; /** * The current query being requested. * @type {String} */ this.query = ''; /** * The jqXHR object of the current request, false if there is none. * @type {jqXHR|Boolean} */ this.request = false; // Maps deprecated options to new ones between releases. var deprecatedOptionsMap = [ // @todo Remove these options in next minor release. { from: 'ajaxResultsPreHook', to: 'preprocessData' }, { from: 'ajaxSearchUrl', to: { ajax: { url: '{{{value}}}' } } }, { from: 'ajaxOptions', to: 'ajax' }, { from: 'debug', to: function (map) { var _options = {}; _options.log = Boolean(plugin.options[map.from]) ? plugin.LOG_DEBUG : 0; plugin.options = $.extend(true, {}, plugin.options, _options); delete plugin.options[map.from]; plugin.log(plugin.LOG_WARNING, 'Deprecated option "' + map.from + '". Update code to use:', _options); } }, { from: 'mixWithCurrents', to: 'preserveSelected' }, { from: 'placeHolderOption', to: { locale: { emptyTitle: '{{{value}}}' } } } ]; if (deprecatedOptionsMap.length) { $.map(deprecatedOptionsMap, function (map) { // Depreciated option detected. if (plugin.options[map.from]) { // Map with an object. Use "{{{value}}}" anywhere in the object to // replace it with the passed value. if ($.isPlainObject(map.to)) { plugin.replaceValue(map.to, '{{{value}}}', plugin.options[map.from]); plugin.options = $.extend(true, {}, plugin.options, map.to); plugin.log(plugin.LOG_WARNING, 'Deprecated option "' + map.from + '". Update code to use:', map.to); delete plugin.options[map.from]; } // Map with a function. Functions are silos. They are responsible // for deleting the original option and displaying debug info. else if ($.isFunction(map.to)) { map.to.apply(plugin, [map]); } // Map normally. else { var _options = {}; _options[map.to] = plugin.options[map.from]; plugin.options = $.extend(true, {}, plugin.options, _options); plugin.log(plugin.LOG_WARNING, 'Deprecated option "' + map.from + '". Update code to use:', _options); delete plugin.options[map.from]; } } }); } // Retrieve the element data attributes. var data = this.$element.data(); // @todo Deprecated. Remove this in the next minor release. if (data['searchUrl']) { plugin.log(plugin.LOG_WARNING, 'Deprecated attribute name: "data-search-url". Update markup to use: \' data-abs-ajax-url="' + data['searchUrl'] + '" \''); this.options.ajax.url = data['searchUrl']; } // Helper functions. var matchToLowerCase = function (match, p1) { return p1.toLowerCase(); }; var expandObject = function (keys, value, obj) { var k = [].concat(keys), l = k.length, o = obj || {}; if (l) { var key = k.shift(); o[key] = expandObject(k, value, o[key]); } return l ? o : value; }; // Filter out only the data attributes prefixed with 'data-abs-'. var dataKeys = Object.keys(data).filter(/./.test.bind(new RegExp('^abs[A-Z]'))); // Map the data attributes to their respective place in the options object. if (dataKeys.length) { // Object containing the data attribute options. var dataOptions = {}; var flattenedOptions = ['locale']; for (i = 0, l = dataKeys.length; i < l; i++) { var name = dataKeys[i].replace(/^abs([A-Z])/, matchToLowerCase).replace(/([A-Z])/g, '-$1').toLowerCase(); var keys = name.split('-'); // Certain options should be flattened to a single object // and not fully expanded (such as Locale). if (keys[0] && keys.length > 1 && flattenedOptions.indexOf(keys[0]) !== -1) { var newKeys = [keys.shift()]; var property = ''; // Combine the remaining keys as a single property. for (var ii = 0; ii < keys.length; ii++) { property += (ii === 0 ? keys[ii] : keys[ii].charAt(0).toUpperCase() + keys[ii].slice(1)); } newKeys.push(property); keys = newKeys; } this.log(this.LOG_DEBUG, 'Processing data attribute "data-abs-' + name + '":', data[dataKeys[i]]); expandObject(keys, data[dataKeys[i]], dataOptions); } this.options = $.extend(true, {}, this.options, dataOptions); this.log(this.LOG_DEBUG, 'Merged in the data attribute options: ', dataOptions, this.options); } /** * Reference to the selectpicker instance. * @type {Selectpicker} */ this.selectpicker = data['selectpicker']; if (!this.selectpicker) { this.log(this.LOG_ERROR, 'Cannot instantiate an AjaxBootstrapSelect instance without selectpicker first being initialized!'); return null; } // Ensure there is a URL. if (!this.options.ajax.url) { this.log(this.LOG_ERROR, 'Option "ajax.url" must be set! Options:', this.options); return null; } // Initialize the locale strings. this.locale = $.extend(true, {}, $.fn.ajaxSelectPicker.locale); // Ensure the langCode is properly set. this.options.langCode = this.options.langCode || window.navigator.userLanguage || window.navigator.language || 'en'; if (!this.locale[this.options.langCode]) { var langCode = this.options.langCode; // Reset the language code. this.options.langCode = 'en'; // Check for both the two and four character language codes, using // the later first. var langCodeArray = langCode.split('-'); for (i = 0, l = langCodeArray.length; i < l; i++) { var code = langCodeArray.join('-'); if (code.length && this.locale[code]) { this.options.langCode = code; break; } langCodeArray.pop(); } this.log(this.LOG_WARNING, 'Unknown langCode option: "' + langCode + '". Using the following langCode instead: "' + this.options.langCode + '".'); } // Allow options to override locale specific strings. this.locale[this.options.langCode] = $.extend(true, {}, this.locale[this.options.langCode], this.options.locale); /** * The select list. * @type {AjaxBootstrapSelectList} */ this.list = new window.AjaxBootstrapSelectList(this); this.list.refresh(); // We need for selectpicker to be attached first. Putting the init in a // setTimeout is the easiest way to ensure this. // @todo Figure out a better way to do this (hopefully listen for an event). setTimeout(function () { plugin.init(); }, 500); }; /** * Initializes this plugin on a selectpicker instance. */ AjaxBootstrapSelect.prototype.init = function () { var requestDelayTimer, plugin = this; // Rebind select/deselect to process preserved selections. if (this.options.preserveSelected) { this.selectpicker.$menu.off('click', '.actions-btn').on('click', '.actions-btn', function (e) { if (plugin.selectpicker.options.liveSearch) { plugin.selectpicker.$searchbox.focus(); } else { plugin.selectpicker.$button.focus(); } e.preventDefault(); e.stopPropagation(); if ($(this).is('.bs-select-all')) { if (plugin.selectpicker.$lis === null) { plugin.selectpicker.$lis = plugin.selectpicker.$menu.find('li'); } plugin.$element.find('option:enabled').prop('selected', true); $(plugin.selectpicker.$lis).not('.disabled').addClass('selected'); plugin.selectpicker.render(); } else { if (plugin.selectpicker.$lis === null) { plugin.selectpicker.$lis = plugin.selectpicker.$menu.find('li'); } plugin.$element.find('option:enabled').prop('selected', false); $(plugin.selectpicker.$lis).not('.disabled').removeClass('selected'); plugin.selectpicker.render(); } plugin.selectpicker.$element.change(); }); } // Add placeholder text to the search input. this.selectpicker.$searchbox .attr('placeholder', this.t('searchPlaceholder')) // Remove selectpicker events on the search input. .off('input propertychange'); // Bind this plugin's event. this.selectpicker.$searchbox.on(this.options.bindEvent, function (e) { var query = plugin.selectpicker.$searchbox.val(); plugin.log(plugin.LOG_DEBUG, 'Bind event fired: "' + plugin.options.bindEvent + '", keyCode:', e.keyCode, e); // Dynamically ignore the "enter" key (13) so it doesn't // create an additional request if the "cache" option has // been disabled. if (!plugin.options.cache) { plugin.options.ignoredKeys[13] = 'enter'; } // Don't process ignored keys. if (plugin.options.ignoredKeys[e.keyCode]) { plugin.log(plugin.LOG_DEBUG, 'Key ignored.'); return; } // Clear out any existing timer. clearTimeout(requestDelayTimer); // Process empty search value. if (!query.length) { // Clear the select list. if (plugin.options.clearOnEmpty) { plugin.list.destroy(); } // Don't invoke a request. if (!plugin.options.emptyRequest) { return; } } // Store the query. plugin.previousQuery = plugin.query; plugin.query = query; // Return the cached results, if any. if (plugin.options.cache && e.keyCode !== 13) { var cache = plugin.list.cacheGet(plugin.query); if (cache) { plugin.list.setStatus(!cache.length ? plugin.t('statusNoResults') : ''); plugin.list.replaceOptions(cache); plugin.log(plugin.LOG_INFO, 'Rebuilt options from cached data.'); return; } } requestDelayTimer = setTimeout(function () { // Abort any previous requests. if (plugin.lastRequest && plugin.lastRequest.jqXHR && $.isFunction(plugin.lastRequest.jqXHR.abort)) { plugin.lastRequest.jqXHR.abort(); } // Create a new request. plugin.request = new window.AjaxBootstrapSelectRequest(plugin); // Store as the previous request once finished. plugin.request.jqXHR.always(function () { plugin.lastRequest = plugin.request; plugin.request = false; }); }, plugin.options.requestDelay || 300); }); }; /** * Wrapper function for logging messages to window.console. * * @param {Number} type * The type of message to log. Must be one of: * * - AjaxBootstrapSelect.LOG_ERROR * - AjaxBootstrapSelect.LOG_WARNING * - AjaxBootstrapSelect.LOG_INFO * - AjaxBootstrapSelect.LOG_DEBUG * * @param {String|Object|*...} message * The message(s) to log. Multiple arguments can be passed. * * @return {void} */ AjaxBootstrapSelect.prototype.log = function (type, message) { if (window.console && this.options.log) { // Ensure the logging level is always an integer. if (typeof this.options.log !== 'number') { if (typeof this.options.log === 'string') { this.options.log = this.options.log.toLowerCase(); } switch (this.options.log) { case true: case 'debug': this.options.log = this.LOG_DEBUG; break; case 'info': this.options.log = this.LOG_INFO; break; case 'warn': case 'warning': this.options.log = this.LOG_WARNING; break; default: case false: case 'error': this.options.log = this.LOG_ERROR; break; } } if (type <= this.options.log) { var args = [].slice.apply(arguments, [2]); // Determine the correct console method to use. switch (type) { case this.LOG_DEBUG: type = 'debug'; break; case this.LOG_INFO: type = 'info'; break; case this.LOG_WARNING: type = 'warn'; break; default: case this.LOG_ERROR: type = 'error'; break; } // Prefix the message. var prefix = '[' + type.toUpperCase() + '] AjaxBootstrapSelect:'; if (typeof message === 'string') { args.unshift(prefix + ' ' + message); } else { args.unshift(message); args.unshift(prefix); } // Display the message(s). window.console[type].apply(window.console, args); } } }; /** * Replaces an old value in an object or array with a new value. * * @param {Object|Array} obj * The object (or array) to iterate over. * @param {*} needle * The value to search for. * @param {*} value * The value to replace with. * @param {Object} [options] * Additional options for restricting replacement: * - recursive: {boolean} Whether or not to iterate over the entire * object or array, defaults to true. * - depth: {int} The number of level this method is to search * down into child elements, defaults to false (no limit). * - limit: {int} The number of times a replacement should happen, * defaults to false (no limit). * * @return {void} */ AjaxBootstrapSelect.prototype.replaceValue = function (obj, needle, value, options) { var plugin = this; options = $.extend({ recursive: true, depth: false, limit: false }, options); // The use of $.each() opposed to native loops here is beneficial // since obj can be either an array or an object. This helps reduce // the amount of duplicate code needed. $.each(obj, function (k, v) { if (options.limit !== false && typeof options.limit === 'number' && options.limit <= 0) { return false; } if ($.isArray(obj[k]) || $.isPlainObject(obj[k])) { if ((options.recursive && options.depth === false) || (options.recursive && typeof options.depth === 'number' && options.depth > 0)) { plugin.replaceValue(obj[k], needle, value, options); } } else { if (v === needle) { if (options.limit !== false && typeof options.limit === 'number') { options.limit--; } obj[k] = value; } } }); }; /** * Generates a translated {@link $.fn.ajaxSelectPicker.locale locale string} for a given locale key. * * @param {String} key * The translation key to use. * @param {String} [langCode] * Overrides the currently set {@link $.fn.ajaxSelectPicker.defaults#langCode langCode} option. * * @return * The translated string. */ AjaxBootstrapSelect.prototype.t = function (key, langCode) { langCode = langCode || this.options.langCode; if (this.locale[langCode] && this.locale[langCode].hasOwnProperty(key)) { return this.locale[langCode][key]; } this.log(this.LOG_WARNING, 'Unknown translation key:', key); return key; }; /** * Use an existing definition in the Window object or create a new one. * * Note: This must be the last statement of this file. * * @type {AjaxBootstrapSelect} * @ignore */ window.AjaxBootstrapSelect = window.AjaxBootstrapSelect || AjaxBootstrapSelect;
/** * bardjs - Mocha/chai spec helpers for testing angular apps * @authors John Papa,Ward Bell * @version v0.0.9 * @link https://github.com/wardbell/bardjs * @license MIT */ /* jshint -W117, -W030 */ (function() { window.bard = window.bard || {}; /** * Creates the global ngRouteTester function * to help test ngRoute changes in the DOM * * Usage: * * beforeEach(function() { * module('app.module', ngRouteTester(options)); * ... other config ... * ... ready to roll; inject! ... * bard.inject('ngRouteTester', ...); * }); * * @function ngRouteTester * @param {Object} [opts] * @param {Object} [opts.document=document] The document node of the page * @param {Object} [opts.templateUrl] The template file for the HTML layout of the tester * @param {Object} [opts.template] The template string for the HTML layout of the tester * @param {Object} [opts.mockLocationPaths=true] Whether or not to fake the URL change in the browser address bar * * Thanks to Matias Niemelä and his ngMidwayTester from * which most of this code is lifted. * See http://www.yearofmoo.com/2013/01/full-spectrum-testing-with-angularjs-and-karma.html */ window.bard.ngRouteTester = function(opts) { ngRouteTester.$inject = ['$provide']; return ngRouteTester; /////////////////// function ngRouteTester($provide) { var options = { document: document }; angular.extend(options, opts); configure(); $provide.factory('ngRouteTester', tester); /////////////////////// var $rootElement, $timers = [], $viewContainer, $terminalElement, $viewCounter = 0, doc, noop = angular.noop; var viewSelector = 'ng-view, [ng-view], .ng-view, [x-ng-view], [data-ng-view]'; function configure() { doc = options.document; $rootElement = angular.element(doc.createElement('div')); $provide.value('$rootElement', $rootElement); var mockPaths = options.mockLocationPaths; if (mockPaths == null ? true : mockPaths) { $provide.decorator('$location', LocationDecorator); } if (options.templateUrl) { getTemplate(); } if (options.template) { $rootElement.html(options.template); var view = angular.element($rootElement[0].querySelector(viewSelector)); $viewContainer = view.parent(); } else { $viewContainer = angular.element('<div><div ng-view></div></div>'); $rootElement.append($viewContainer); } } LocationDecorator.$inject = ['$delegate', '$rootScope']; function LocationDecorator($delegate, $rootScope) { var _path = $delegate.path(); $delegate.path = function(path) { if (path) { // sometimes the broadcast triggers a new request for same path // added this conditional to mitigate risk of this infinite loop if (_path !== path) { _path = path; $rootScope.$broadcast('$locationChangeSuccess', path); } return this; } else { return _path; } }; return $delegate; } // get the template from the server synchronously function getTemplate() { var request = new XMLHttpRequest(); request.open('GET', options.templateUrl, false); request.send(null); if (request.status !== 200) { throw new Error('ngRouteTester: Unable to download template file'); } options.template = request.responseText; } // ngRouteTester factory tester.$inject = ['$compile', '$injector', '$rootScope', '$route']; function tester($compile, $injector, $rootScope, $route) { bootstrap(); // Arrange for mocha/jasmine to destroy after each test afterEach && afterEach(destroy); return { $injector: $injector, $rootScope: $rootScope, $route: $route, path: path, rootElement: $rootElement, until: until, viewElement : viewElement, visit : visit }; /////////////////// function bootstrap() { $terminalElement = angular.element( '<div status="{{__VIEW_STATUS}}"></div>'); $rootElement.append($terminalElement); $rootScope.$apply(function() { $rootElement.data('$injector', $injector); $compile($rootElement)($rootScope); angular.element(doc.body).append($rootElement); }); } /** * Removes the $rootElement and clears the module from the page. * This is done automatically for mocha tests * * @method destroy */ function destroy() { angular.forEach($timers, function(timer) { clearTimeout(timer); }); var body = angular.element(document.body); body.removeData(); $rootElement.remove(); $rootScope.$destroy(); } /** * @method path * @return {String} Returns the path of the current route */ function path() { return $injector.get('$location').path(); } /** * @method viewElement * @return {Element} The current element that has ng-view attached to it */ function viewElement() { return angular.element($viewContainer[0].querySelector(viewSelector)); } /** * Changes the current route of the page and then fires the callback when the page has loaded * * @param {String} path The given path that the current route will be changed to * @param {function} [callback] The given callback to fire once the view has been fully loaded * @method visit */ function visit(path, callback) { // wait until view shows up /* jshint -W106 */ $rootScope.__VIEW_STATUS = ++$viewCounter; /* jshint +W106 */ until(function() { return parseInt($terminalElement.attr('status')) >= $viewCounter; }, function() { // give it another tick to settle setTimeout(callback || noop, 0); }); // tell router to visit the view var fn = function() { $injector.get('$location').path(path); }; $rootScope.$$phase ? fn() : $rootScope.$apply(fn); } /** * Keeps checking an expression until it returns a truthy value and then runs the provided callback * * @param {function} exp The given function to poll * @param {function} callback The given callback to fire once the exp function returns a truthy value * @method until */ function until(exp, callback) { var timer, delay = 50; timer = setInterval(function() { if (exp()) { clearTimeout(timer); callback(); } }, delay); $timers.push(timer); } } } }; })();