code
stringlengths
2
1.05M
(function() { 'use strict'; angular.module('onEnter', []) .directive('onEnter', [function() { var linkFunc = function(scope, el, attrs) { el.on('keypress', function(event) { if (event.keyCode !== 13 || event.shiftKey) return; event.preventDefault(); scope.$apply(attrs.onEnter); }); }; return { restrict: 'A', link: linkFunc }; }]); })();
(function() { 'use strict'; angular .module('blocks.storage') .factory('$localStorage', factory); factory.$inject = ['$window']; /* @ngInject */ function factory($window) { var service = { set: set, get: get, setObject: setObject, getObject: getObject, remove: remove }; return service; function set(key,value) { if (value === null) { remove(key); } else { $window.localStorage[key] = value; } } function get(key,defaultValue) { return $window.localStorage[key] || defaultValue; } function setObject(key,value) { if (value === null) { remove(key); } else { $window.localStorage[key] = JSON.stringify(value); } } function getObject(key) { return JSON.parse($window.localStorage[key] || '{}'); } function remove(key) { $window.localStorage.removeItem(key); } } })();
'use strict'; const debug = require('debug')('wechat-JSSDK'); const isEmpty = require('lodash.isempty'); const urlParser = require('url'); const utils = require('./utils'); const config = require('./config'); const Store = require('./store/Store'); const FileStore = require('./store/FileStore'); const wxConfig = config.getDefaultConfiguration(); class JSSDK { /** * Pass custom wechat config for the instance * @constructor * @param {object=} options * @see ./config.js * @return {JSSDK} JSSDK instance */ constructor(options) { config.checkPassedConfiguration(options); this.refreshedTimes = 0; this.wechatConfig = isEmpty(options) ? /* istanbul ignore next */ wxConfig : Object.assign({}, wxConfig, options); //no custom store provided, using default FileStore /* istanbul ignore if */ if (!options.store || !(options.store instanceof Store)) { debug('[JSSDK]Store not provided, using default FileStore...'); this.store = new FileStore(options.storeOptions); } else { this.store = options.store; } //clear the counter every 2 hour setInterval( () => (this.refreshedTimes = 0), options.clearCountInterval || 1000 * 7200 ); } /** * Check if token is expired starting from the modify date * @param modifyDate * @static * @return {boolean} */ static isTokenExpired(modifyDate) { return utils.isExpired(modifyDate); } /** * Create NonceStr before generating the signature * @static * @return {string} */ static createNonceStr() { return utils.nonceStr(); } /** * Filter the signature for the client * @param {object} originalSignatureObj original signature information * @return {object} filtered signature object */ filterSignature(originalSignatureObj) { if (!originalSignatureObj) { return {}; } return { appId: this.wechatConfig.appId, timestamp: originalSignatureObj.timestamp, nonceStr: originalSignatureObj.nonceStr, signature: originalSignatureObj.signature, url: originalSignatureObj.url, }; } /** * Remove hash from the url, wechat signature does not need it * @param {string} url original url * @static * @return {string} */ static normalizeUrl(url) { const temp = urlParser.parse(url); const hashIndex = url.indexOf(temp.hash); //remove hash from url return hashIndex > 0 ? url.substring(0, hashIndex) : url; } /** * Generate the url signature with the provided info * @param {string} url current url * @param {string} accessToken * @param {string} ticket js ticket * @static * @returns {object} generated wechat signature info */ static generateSignature(url, accessToken, ticket) { const ret = { jsapi_ticket: ticket, nonceStr: JSSDK.createNonceStr(), timestamp: utils.timestamp(), url: JSSDK.normalizeUrl(url), }; const originalStr = utils.paramsToString(ret); ret.signature = utils.genSHA1(originalStr); ret.accessToken = accessToken; return ret; } /** * Need to verify before you are a wechat developer * @param {object} query url query sent by the wechat server to do the validation * @return {boolean} */ verifySignature(query) { const keys = [ this.wechatConfig.wechatToken, query['timestamp'], query['nonce'], ]; let str = keys.sort().join(''); str = utils.genSHA1(str); return str === query.signature; } /** * Send request to get wechat access token * @return {Promise} */ getAccessToken() { const cfg = this.wechatConfig; return utils.getGlobalAccessToken( cfg.appId, cfg.appSecret, cfg.accessTokenUrl ); } /** * Get wechat ticket with the accessToken * @param {string} accessToken token received from the @see getAccessToken above * @return {Promise} */ getJsApiTicket(accessToken) { const params = { access_token: accessToken, type: 'jsapi', }; return utils .sendWechatRequest(this.wechatConfig.ticketUrl, { query: params, }) .then(data => data) .catch(reason => { debug('get ticket failed!'); return Promise.reject(reason); }); } /** * Update the global token or js_ticket, we should cache this to prevent requesting too often * @param {string} token * @param {string} ticket * @return {Promise} resolved with the updated globalToken object */ updateAccessTokenOrTicketGlobally(token, ticket) { const info = { modifyDate: new Date() }; token && (info.accessToken = token); ticket && (info.jsapi_ticket = ticket); return this.store.updateGlobalToken(info); } /** * Get new access token and ticket from wechat server, and update that to cache * @param {boolean=} force force update, by default it will only get at most 5 times within 2 hours, * cause the wechat server limits the access_token requests number * @return {Promise} */ getGlobalTokenAndTicket(force) { force || this.refreshedTimes++; /* istanbul ignore if */ if (!force && this.refreshedTimes > 5) { return Promise.reject( new Error('maximum manual refresh threshold reached!') ); } let accessToken = ''; return this.getAccessToken() .then(result => { accessToken = result.access_token; return accessToken; }) .catch(reason => { debug('get new global token failed!'); return Promise.reject(reason); }) .then(receivedAccessToken => { return this.getJsApiTicket(receivedAccessToken); }) .then(ticketResult => { return this.updateAccessTokenOrTicketGlobally( accessToken, ticketResult.ticket ); }) .catch(ticketReason => { debug('get new global ticket failed!'); debug(ticketReason); return Promise.reject(ticketReason); }); } /** * Get or generate global token info for signature generating process * @return {Promise} */ prepareGlobalToken() { return this.store.getGlobalToken().then(globalToken => { if ( !globalToken || !globalToken.accessToken || JSSDK.isTokenExpired(globalToken.modifyDate) ) { debug( 'global access token was expired, getting new global access token and ticket now...' ); return this.getGlobalTokenAndTicket(true); } debug('global ticket exists, use cached access token'); return Promise.resolve(globalToken); }); } /** * Save or update the signature * @param {object} info signature information to save * @return {Promise} */ saveSignature(info) { const signature = Object.assign({}, info); signature.createDate = new Date(); signature.modifyDate = signature.createDate; return this.store .isSignatureExisting(signature.url) .then(existing => { if (existing) { debug('wechat url signature existed, try updating the signature...'); return this.updateSignature(signature.url, signature); } return this.store.saveSignature(signature.signatureName, signature); }) .then(sig => { debug('create/update wechat signature finished'); return Promise.resolve(sig); }); } /** * Update the signature for existing url * @param {string} url signature of url need to update * @param {object} info update info need to be updated to the existing url signature info * @return {Promise} */ updateSignature(url, info) { url = JSSDK.normalizeUrl(url); info.modifyDate = new Date(); delete info.createDate; delete info.url; //prevent changing the original url delete info.signatureName; //prevent changing the original name return this.store.updateSignature(url, info).then(sig => { debug('update wechat signature finished'); return Promise.resolve(sig); }); } /** * Get the signature from cache or create a new one * @param {string} url * @param {boolean=} forceNewSignature if true, generate a new signature rather than getting from cache * @return {Promise} */ getSignature(url, forceNewSignature) { url = JSSDK.normalizeUrl(url); return this.store.getSignature(url).then(signature => { if ( !forceNewSignature && signature && !JSSDK.isTokenExpired(signature.modifyDate) ) { signature = this.filterSignature(signature); return Promise.resolve(signature); } return this.createSignature(url); }); } /** * Create a new signature now, and save to store * @param {string} url signature will be created for the url * @return {Promise} resolved with filtered signature results */ createSignature(url) { return this.prepareGlobalToken() .then(data => { const ret = JSSDK.generateSignature( url, data.accessToken, data.jsapi_ticket ); ret.signatureName = ret.url; return this.saveSignature(ret); }) .then(sig => this.filterSignature(sig)); } /** * Just get url signature from cache * @param {string} url * @return {Promise} filtered signature info */ getCachedSignature(url) { url = JSSDK.normalizeUrl(url); return this.store.getSignature(url).then(signature => { return Promise.resolve(this.filterSignature(signature)); }); } } module.exports = JSSDK;
define("ghost/routes/settings/tags", ["ghost/routes/authenticated","ghost/mixins/current-user-settings","ghost/mixins/pagination-route","exports"], function(__dependency1__, __dependency2__, __dependency3__, __exports__) { "use strict"; var AuthenticatedRoute = __dependency1__["default"]; var CurrentUserSettings = __dependency2__["default"]; var PaginationRouteMixin = __dependency3__["default"]; var TagsRoute = AuthenticatedRoute.extend(CurrentUserSettings, PaginationRouteMixin, { actions: { willTransition: function () { this.send('closeSettingsMenu'); } }, titleToken: 'Tags', beforeModel: function () { if (!this.get('config.tagsUI')) { return this.transitionTo('settings.general'); } return this.currentUser() .then(this.transitionAuthor()); }, model: function () { return this.store.find('tag'); }, setupController: function (controller, model) { this._super(controller, model); this.setupPagination(); }, renderTemplate: function (controller, model) { this._super(controller, model); this.render('settings/tags/settings-menu', { into: 'application', outlet: 'settings-menu', view: 'settings/tags/settings-menu' }); } }); __exports__["default"] = TagsRoute; });
const path = require('path'); const util = require('./util'); class Manager { /** * @param {string} id */ static async import(id) { if (module.import) { return await module.import(id); } return { default: module.require(id) }; } /** * @param {string} name * @param {Object} config */ constructor(name, { opts, filter, throwPackageNotFound } = {}) { if (!opts) { opts = { prefix: process.cwd() }; } if (!filter) { filter = async (pkg) => { if (!pkg.hasOwnProperty(this._name)) { throw new Error('Package `' + pkg['name'] + '@' + pkg['version'] + '` is not supported'); } }; } if (!throwPackageNotFound) { throwPackageNotFound = (name) => { throw new Error('Unable to locate package `' + name + '`'); }; } this._name = name; this._opts = opts; this._filter = filter; this._throwPackageNotFound = throwPackageNotFound; this._minSupportedNpmVersion = '6.14.5'; this._npmVersionCheck = async () => { if (!this._npmVersion) { const { stdout, stderr } = await util.npmExec('-v'); this._npmVersion = stdout.trim(); } if (this._npmVersion !== this._minSupportedNpmVersion) { if (!util.isNewerVersion(this._minSupportedNpmVersion, this._npmVersion)) { throw new Error( 'unsupported NPM version, require `npm@>=' + this._minSupportedNpmVersion + '`' ); } } }; } /** * Import package * * @param {string} name * @returns {*} */ async import(name) { name = await util.resolvePath(name, this._opts); return await Manager.import(name); } /** * Package info * * @param {string} name * @returns {Object} */ async info(name) { const resolved = await util.resolveName(name); if ('folder' == resolved['type']) { const { default: pkg } = await Manager.import(path.join(resolved['value'], 'package.json')); if (false !== await this._filter(pkg)) { return pkg; } } else if (['tarball_file', 'tarball_url'].includes(resolved['type'])) { const pkg = await util.readTarballPkg(resolved); if (false !== await this._filter(pkg)) { return pkg; } } else if ('name' == resolved['type']) { try { const cmd = 'show ' + resolved['value'] + ' --json --no-update-notifier'; const { stdout, stderr } = await util.npmExec(cmd); const pkg = JSON.parse(stdout); if (false !== await this._filter(pkg)) { return pkg; } } catch (e) {} } this._throwPackageNotFound(name); } /** * Installed package info * * @param {string} name * @returns {Object} */ async package(name) { const { default: pkg } = await this.import(path.join(name, 'package.json')); if (false !== await this._filter(pkg)) { return pkg; } this._throwPackageNotFound(name); } /** * Installed packages * * @returns {string[]} */ async list() { const cmd = 'ls ' + util.optsToString(this._opts) + ' --depth=0 --json --no-update-notifier'; const { stdout, stderr } = await util.npmExec(cmd); const data = []; const dependencies = JSON.parse(stdout)['dependencies'] || {}; for (let name in dependencies) { const { default: pkg } = await this.import(path.join(name, 'package.json')); try { if (false !== await this._filter(pkg)) { data.push(name); } } catch (e) {} } return data; } /** * Install package * * @param {string} name * @param {Promise} [satisfies] * @returns {Object} */ async install(name, satisfies = async (pkg) => {}) { await this._npmVersionCheck(); let pkg = null; try { pkg = await this.info(name); } catch (e) {} if (pkg && false !== await satisfies(pkg)) { const resolved = await util.resolveName(name); // prevent symlinks let cleaning = async () => {}; if ('folder' == resolved['type']) { const cmd = 'pack ' + resolved['value'] + ' --no-update-notifier'; const { stdout, stderr } = await util.npmExec(cmd); resolved['value'] = path.resolve(stdout.split('\n')[0]); cleaning = async () => { await util.fsUnlink(resolved['value']); }; } let exitCode; try { const cmd = 'install ' + resolved['value'] + ' ' + util.optsToString(this._opts) + ' --no-update-notifier'; exitCode = await util.npmSpawn(cmd.split(' ')); await cleaning(); } catch (e) { await cleaning(); throw e; } return { name, exitCode, pkg }; } this._throwPackageNotFound(name); } /** * Remove package * * @param {string} name * @returns {Object} */ async remove(name) { await this._npmVersionCheck(); let pkg = null; try { pkg = await this.package(name); } catch (e) {} if (pkg) { const cmd = 'remove ' + name + ' ' + util.optsToString(this._opts) + ' --no-update-notifier'; const exitCode = await util.npmSpawn(cmd.split(' ')); return { name, exitCode }; } this._throwPackageNotFound(name); } } module.exports = Manager;
import prompt from 'prompt'; import io from 'socket.io-client'; import fetch from 'node-fetch'; import imessagemodule from 'imessagemodule'; import sqlite from 'sqlite3'; import glob from 'glob'; const IMESSAGE_DB = process.env.HOME + '/Library/Messages/chat.db'; //const URL_BASE = 'http://imessage.dokku.jdupserver.com'; const URL_BASE = 'http://localhost:8000'; const URL_LOGIN = URL_BASE + '/api/login'; const URL_LAST_APPLE_ID = URL_BASE + '/api/lastAppleId'; let db = null; let socket = null; let reconnectInterval = null; let latestMessageId = null; let token = null; process.on('exit', () => { if(db) { db.close(); } }); let schema = { properties: { username: { }, password: { hidden: true, }, }, }; loginPrompt(); function loginPrompt() { prompt.get(schema, (err, result) => { if(err) { console.error(err); return; } login(result.username, result.password); }); } async function send(method, url, params) { let body = null; if(params) { body = JSON.stringify(params); } let headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', }; if(token) { headers['Authorization'] = 'Bearer ' + token; } return await fetch(url, { method: method, body: body, headers: headers, }) .then(resp => resp.json()) .catch((err) => { console.error('send error', err); }); } async function login(username, password) { let resp = await send('POST', URL_LOGIN, { username: username, password: password, }); if(resp.result !== 'OK') { console.log('Invalid username or password. Please try again.'); loginPrompt(); return; } token = resp.token; latestMessageId = await getLastSentMessageId(); console.log(latestMessageId); createSocket(); } function createSocket() { try { socket = io.connect(URL_BASE); } catch(error) { console.error(error); } socket.on('authenticated', () => { socket.emit('ready', { type: 'mac', }); }); socket.on('message', sendMessage); socket.on('connect', () => { clearInterval(reconnectInterval); connect(); }); socket.on('disconnect', () => { console.log('Disconnected. Trying to reconnect...'); tryReconnect(); }); } function tryReconnect() { reconnectInterval = setInterval(() => { socket.connect(); }, 5000); } function connect() { socket.connect(); socket.emit('authenticate', {token}); console.log('Connected'); db = new sqlite.Database(IMESSAGE_DB); checkNewMessages(); } function receiveMessages(messages) { console.log(`Received ${messages.length} new messages`); socket.emit('send', { type: 'mac', messages: messages, }); } function sendMessage(message) { console.log('Sending message:', message); imessagemodule.sendMessage(message.convoName, message.text); } async function checkNewMessages() { if(!latestMessageId) { try { latestMessageId = await getLastSentMessageId(); } catch(err) { console.error(err); return; } } clearInterval(checkNewMessages.interval); checkNewMessages.interval = setInterval(async () => { let newMessages; try { newMessages = await getNewMessages(latestMessageId); } catch(err) { console.error(err); return; } if(newMessages.length > 0) { latestMessageId = newMessages[0].ROWID; let messages = []; for(let m of newMessages) { let isFromMe = m.is_from_me === 1; let author; if(isFromMe) { author = 'me'; } else { try { author = await getNameFromPhone(m.id); } catch(err) { console.error(err); } } let date = getDateFromTimestamp(m.date); messages.push({ appleId: m.ROWID, author: author, date: date, text: m.text, convoName: m.display_name || author, fromMe: isFromMe, }); } receiveMessages(messages); } }, 1000); } function getNewMessages(lastMessageId) { return new Promise((resolve, reject) => { const sql = ` SELECT DISTINCT message.ROWID, handle.id, message.text, message.is_from_me, message.date, message.date_delivered, message.date_read, chat.chat_identifier, chat.display_name FROM message LEFT OUTER JOIN chat ON chat.room_name = message.cache_roomnames LEFT OUTER JOIN handle ON handle.ROWID = message.handle_id WHERE message.service = 'iMessage' AND message.ROWID > (?) ORDER BY message.date DESC` + (lastMessageId === 0 ? ` LIMIT 500 ` : ''); db.serialize(function() { db.all(sql, lastMessageId, (err, messages) => { if(err) { reject(err); return; } resolve(messages); }); }); }); } async function getLastSentMessageId() { let resp = await send('GET', URL_LAST_APPLE_ID); if(resp.error) { throw Error(resp.error); } return resp.id; } function getLatestMessageId() { return new Promise((resolve, reject) => { const sql = ` SELECT MAX(message.ROWID) AS maxid FROM message`; db.serialize(function() { db.all(sql, function(err, rows) { if(err) { reject(err); return; } resolve(rows[0].maxid); }); }); }); } const phoneNumberNames = {}; function getNameFromPhone(phoneNumber) { return new Promise((resolve, reject) => { // Cache if(phoneNumberNames[phoneNumber]) { resolve(phoneNumberNames[phoneNumber]); return; } if(phoneNumber.indexOf('@') >= 0) { phoneNumberNames[phoneNumber] = phoneNumber; resolve(phoneNumber); return; } let phone = phoneNumber.replace(/\(/g, '').replace(/\)/g, '').replace(/\-/g, '').replace(/\ /g, '').replace(/\+/g, ''); // need to make a like statement so we can get the following phone, which is now in the format // 11231231234 into 123%123%1234 // NOTE: this will probably not work for other countries since I assume they store their address differently? // fall back to phone number for that case for now // Remove the country code if there is one. if(phone.length > 10) { phone = phone.substr(1); } // %123 phone = '%' + phone.substr(0, 3) + '%' + phone.substr(3); // %123%123 phone = phone.substr(0, 8) + '%' + phone.substr(8); // %123%123%1234 console.log(phone); glob(process.env.HOME + '/Library/Application\ Support/AddressBook/**/AddressBook-v22.abcddb', async (err, files) => { if(err) { reject(); return; } for(let file of files) { const db = new sqlite.Database(file); let name; try { name = await getNameFromDB(db, phone); console.log(name); } catch(err) { console.error(err); reject(); return; } finally { db.close(); } if(name) { phoneNumberNames[phoneNumber] = name; resolve(name); return; } } phoneNumberNames[phoneNumber] = phoneNumber; resolve(phoneNumber); }); }); } function getNameFromDB(db, phone) { return new Promise((resolve, reject) => { db.serialize(() => { const sql = ` SELECT * FROM ZABCDCONTACTINDEX LEFT OUTER JOIN ZABCDPHONENUMBER ON ZABCDCONTACTINDEX.ZCONTACT = ZABCDPHONENUMBER.ZOWNER LEFT OUTER JOIN ZABCDEMAILADDRESS ON ZABCDEMAILADDRESS.ZOWNER = ZABCDCONTACTINDEX.ZCONTACT LEFT OUTER JOIN ZABCDMESSAGINGADDRESS ON ZABCDMESSAGINGADDRESS.ZOWNER = ZABCDCONTACTINDEX.ZCONTACT LEFT OUTER JOIN ZABCDRECORD ON ZABCDRECORD.Z_PK = ZABCDCONTACTINDEX.ZCONTACT WHERE ZFULLNUMBER LIKE (?)`; db.all(sql, phone, (err, rows) => { if(err) { reject(); return; } let name = null; if (rows.length > 0) { name = rows[0].ZFIRSTNAME + ' ' + ((rows[0].ZLASTNAME) ? rows[0].ZLASTNAME : ''); } resolve(name); }); }); }); } function getDateFromTimestamp(timestamp) { // Dates are stored in sqlite as a timestamp in seconds since Jan 1st 2001. // 978307200000 = JS timestamp for that date. return new Date((timestamp * 1000) + 978307200000); }
function anadir_carrito(nameform, sitio, canal, promocion) { var tienda = 'http://kiosco/'; //##c## var formid = document.getElementById(nameform+promocion); var parametros = { "guidx" : formid.guidx.value, 'guidz' : formid.guidz.value, 'imagen' : formid.imagen.value, 'descripcion' : formid.descripcion.value, 'precio' : formid.precio.value, 'cantidad' : formid.cantidad.value, 'moneda' : formid.moneda.value, 'iva' : formid.iva.value, 'id_sitio' : sitio, 'id_canal' : canal, 'id_promocion' : promocion, 'ajax' : '1' } var url_carrito = tienda+'carrito.php'; $.ajax({ data: parametros, url: url_carrito, type: 'POST', beforeSend: function () { $("#dialog-modal").html("Procesando, espere por favor..."); }, success: function (response) { $("#dialog-modal").dialog( "open" ); $("#dialog-modal").html(response); $("#carrito").text($('#cuenta-detalle-carrito').html()); } }); } $(function() { $('#dialog-modal').dialog({ position: ['top', 100], modal: true, show: 'slide', width:'750px', stack: true, autoOpen: false, draggable: false, //esta parte hace que se cierre el popup al dar click en cualquier parte fuera del mismo open: function(event, ui){ //$('body').css('overflow','hidden'); $('.ui-widget-overlay').css('width','100%'); $('.ui-widget-overlay').css('height','100%'); $('.ui-widget-overlay').bind('click',function(){ $('#dialog-modal').dialog('close'); }) }, close: function(event, ui){ $('body').css('overflow','auto'); } }); /** * ajuste de revisión de moneda */ $("#no-moneda").dialog({ modal: true, title: "Error", width: 550, minWidth: 400, maxWidth: 650, show: "slide", autoOpen: false, draggable: false, open: function(event, ui){ $('body').css('overflow','hidden'); $('.ui-widget-overlay').css('width','100%'); $('.ui-widget-overlay').css('height','100%'); $('.ui-widget-overlay').bind('click',function(){ $('#no-moneda').dialog('close'); }) }, close: function(event, ui){ $('body').css('overflow','auto'); } }); });
const Dare = require('../../src/'); // Test Generic DB functions const sqlEqual = require('../lib/sql-equal'); const DareError = require('../../src/utils/error'); describe('post', () => { let dare; beforeEach(() => { dare = new Dare(); // Should not be called... dare.execute = () => { throw new Error('execute called'); }; }); it('should contain the function dare.post', () => { expect(dare.post).to.be.a('function'); }); it('should generate an INSERT statement and execute dare.execute', async () => { dare.execute = async ({sql, values}) => { sqlEqual(sql, 'INSERT INTO test (`id`) VALUES (?)'); expect(values).to.deep.equal([1]); return {id: 1}; }; const resp = await dare .post('test', {id: 1}); expect(resp).to.have.property('id', 1); }); it('should accept an Array of records to insert', async () => { dare.execute = async ({sql, values}) => { sqlEqual(sql, ` INSERT INTO test (\`id\`, \`name\`, \`field\`) VALUES (?, ?, DEFAULT), (?, ?, ?) `); expect(values).to.deep.equal([1, '1', 2, '2', 'extra']); return []; }; return dare .post('test', [{id: 1, name: '1'}, {name: '2', id: 2, field: 'extra'}]); }); it('should accept option.duplicate_keys=ignore', async () => { let called; dare.execute = async ({sql, values}) => { called = 1; sqlEqual(sql, 'INSERT INTO test (`id`) VALUES (?) ON DUPLICATE KEY UPDATE _rowid=_rowid'); expect(values).to.deep.equal([1]); return {}; }; await dare .post('test', {id: 1}, {duplicate_keys: 'ignore'}); expect(called).to.eql(1); }); it('should accept option.ignore=true', async () => { let called; dare.execute = async ({sql, values}) => { called = 1; sqlEqual(sql, 'INSERT IGNORE INTO test (`id`) VALUES (?)'); expect(values).to.deep.equal([1]); return {}; }; await dare .post('test', {id: 1}, {ignore: true}); expect(called).to.eql(1); }); it('should accept option.update=[field1, field2, ...fieldn]', async () => { let called; dare.execute = async ({sql, values}) => { called = 1; sqlEqual(sql, 'INSERT INTO test (`id`, `name`, `age`) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE `name`=VALUES(`name`), `age`=VALUES(`age`)'); expect(values).to.deep.equal([1, 'name', 38]); return {}; }; await dare .post('test', {id: 1, name: 'name', age: 38}, {duplicate_keys_update: ['name', 'age']}); expect(called).to.eql(1); }); it('should understand a request object', async () => { dare.execute = async ({sql, values}) => { // Limit: 1 sqlEqual(sql, 'INSERT INTO test (`name`) VALUES (?)'); expect(values).to.deep.equal(['name']); return {success: true}; }; return dare .post({ table: 'test', body: {name: 'name'} }); }); it('should trigger pre handler, options.post.[table]', async () => { dare.execute = async ({sql, values}) => { sqlEqual(sql, 'INSERT INTO tbl (`name`) VALUES (?)'); expect(values).to.deep.equal(['andrew']); return {success: true}; }; dare.options.models = { tbl: { post(req) { // Augment the request req.body.name = 'andrew'; } } }; return dare .post({ table: 'tbl', body: {name: 'name'} }); }); it('should trigger pre handler, options.post.default, and wait for Promise to resolve', async () => { dare.execute = async ({sql, values}) => { sqlEqual(sql, 'INSERT INTO tbl (`name`) VALUES (?)'); expect(values).to.deep.equal(['andrew']); return {success: true}; }; dare.options.models = { default: { async post(req) { // Augment the request req.body.name = 'andrew'; } } }; return dare .post({ table: 'tbl', body: {name: 'name'} }); }); it('should trigger pre handler, and handle errors being thrown', async () => { const msg = 'snap'; dare.options.models = { default: { post() { // Augment the request throw new Error(msg); } } }; const test = dare.post({ table: 'tbl', body: {name: 'name'} }); return expect(test) .to.be.eventually.rejectedWith(Error, msg); }); it('should not exectute if the opts.skip request is marked', async () => { const skip = 'true'; dare.options.models = { default: { post(opts) { opts.skip = skip; } } }; const resp = await dare .post({ table: 'tbl', body: {name: 'name'} }); expect(resp).to.eql(skip); }); it('legacy: options.schema, not execute if the opts.skip request is marked', async () => { const skip = 'true'; const dare2 = dare.use({ post: { default(opts) { opts.skip = skip; } } }); const resp = await dare2 .post({ table: 'tbl', body: {name: 'name'} }); expect(resp).to.eql(skip); }); describe('validate formatting of input values', () => { [ { input: 'field' }, { input: null } ].forEach(({input}) => { it(`should pass ${input}`, async () => { dare.execute = async ({sql, values}) => { // Limit: 1 sqlEqual(sql, 'INSERT INTO test (`name`) VALUES (?)'); expect(values).to.deep.equal([input]); return {success: true}; }; return dare .post({ table: 'test', body: {name: input} }); }); }); [ { key: 'value' }, [ 1, 2, 3 ] ].forEach(given => { it(`type=json: should accept object, given ${JSON.stringify(given)}`, async () => { dare.options = { models: { 'test': { schema: { meta: { type: 'json' } } } } }; const output = JSON.stringify(given); dare.execute = async ({sql, values}) => { // Limit: 1 sqlEqual(sql, 'INSERT INTO test (`meta`) VALUES (?)'); expect(values).to.deep.equal([output]); return {success: true}; }; return dare .post({ table: 'test', body: {meta: given} }); }); it(`type!=json: should throw an exception, given ${JSON.stringify(given)}`, async () => { const call = dare .patch({ table: 'test', filter: {id: 1}, body: {name: given} }); return expect(call).to.be.eventually .rejectedWith(DareError, 'Field \'name\' does not accept objects as values') .and.have.property('code', DareError.INVALID_VALUE); }); }); }); });
`use strict`; const mocha = require('mocha'); console.log({ mocha: mocha });
import React, { PropTypes, Component } from 'react'; import Son from './Son'; class Dad extends Component { static defaultProps = { name: 'A' }; static propTypes = { name: PropTypes.string }; constructor(props) { super(props); this.state = { happy: true }; console.log("-----------我是Dad,我在构造------"); } shouldComponentUpdate(nextProps, nextState) { console.log("-------------should Dad update?-----------"); return true; } componentWillReceiveProps(nextProps) { console.log('Dad WillReceiveProps'); } componentWillMount() { console.log('Dad WillMount!'); } componentDidMount() { console.log('Dad DidMount!'); } componentWillUpdate() { console.log('Dad WillUpdate'); } componentDidUpdate() { console.log('-------------Dad DidUpdate!---------'); } componentWillUnmount() { console.log('---------Dad WillUnMount!---------'); } render() { //this.props.name = "frank"; console.log('Dad render!'); return ( <div className="dad"> <div>I am Dad {this.props.name} and I am {this.state.happy ? '开心':'伤心'}</div> <div className="button" onClick={(e) => {e.preventDefault(); this.setState({happy: !this.state.happy});}}>Change</div> <div>I have a son:</div> <Son/> <div>And another son:</div> <Son name="D"/> </div> ); } } module.exports = Dad;
import DS from 'ember-data'; import Validator from '../../mixins/model-validator'; export default DS.Model.extend(Validator,{ favoriteColor: DS.attr('string'), validations: { favoriteColor: { color: true } } });
import { createStore } from 'redux'; import rootReducer from '../reducers'; export default function configureStore(initialState) { const store = createStore( rootReducer, initialState ); return store; }
var test = require('../index').test; var html = require('../html').html; var log = require('../index').log; var http = require('http'); var assert = require('assert'); var success_server = http.createServer(function(req, res) { res.writeHead(200, { 'Content-type': 'text/html' }); res.write('<html><head><title>OK</title></head><body>OK</body></html>'); res.end(); }); var error_server = http.createServer(function(req, res) { res.writeHead(400, { 'Content-type': 'text/html' }); res.write('<html><head><title>ERROR</title></head><body>ERROR</body></html>'); res.end(); }); var test_counter = 0; function test_with_array() { var url1 = 'http://localhost:44444/'; var url2 = 'http://localhost:55555/'; function close_server() { test_counter++; if (test_counter >= 6) { success_server.close(); error_server.close(); } console.log(test_counter + '. Array Test is running.'); } function response_tester(status_result) { if (status_result.url == url1) { assert.ok(status_result.success, 'success property should be true, but now it is ' + status_result.success); assert.equal(status_result.error, false, 'error property should be false'); assert.equal(status_result.message, 'SUCCESS', 'status message should be "SUCCESS"'); assert.equal(status_result.url, url1, "url property should be " + url1 + ", but it is " + status_result.url); assert.equal(status_result.code, 200, 'http status code should be 200'); } else { assert.equal(status_result.success, false, 'success property should be false'); assert.ok(status_result.error, 'error property should be true'); assert.equal(status_result.message, 'ERROR', 'status message should be "ERROR"'); assert.equal(status_result.url, url2, "url property should be " + url2 + ", but it is " + status_result.url); assert.equal(status_result.code, 400, 'http status code should be 400'); } close_server(); } var url = [url1, url2]; test(url, function(data) { console.log('Testing test method with arrays.'); response_tester(data); }); html(url, function(data) { console.log('Testing html method with arrays.'); response_tester(data); }); log(url, function(data) { console.log('Testing log method with arrays.'); response_tester(data); }); } success_server.listen(44444, function() { error_server.listen(55555, test_with_array); });
function initAnimations(Q) { Q.animations('person', { idle_front: { frames: [0] }, running_front: { frames: [1,0,2,0], rate: 1/4 }, striking_front: { frames: [3], rate: 1/4, next: 'idle_front' }, idle_left: { frames: [4] }, running_left: { frames: [5,4,6,4], rate: 1/4 }, striking_left: { frames: [7], rate: 1/4, next: 'idle_left' }, idle_right: { frames: [8] }, running_right: { frames: [9,8,10,8], rate: 1/4 }, striking_right: { frames: [11], rate: 1/4, next: 'idle_right' }, idle_back: { frames: [12] }, running_back: { frames: [13,12,14,12], rate: 1/4 }, striking_back: { frames: [15], rate: 1/4, next: 'idle_back' }, dead_right: { frames: [16], rate: 15, trigger: 'destroy' }, }); }
(function($){//Модули: var defaultOptions = { nameIFrame: "", minWIFrame: 320, minHIFrame: 480, $dimensions: undefined }; var resizeIFrame = function($container, options) { this._options = options; var ____ = this; ____._last_cursor_Y = 0; ____._last_cursor_X = 0; this._create = function() { var $iFrame = $("#"+(____._options.nameIFrame)).contents(); $container.append('<div class="rif-show-dimensions panel panel-primary"><div class="panel-body"><span class="rif-width btn btn-default btn-lg">0</span> X <span class="rif-height btn btn-default btn-lg">0</span></div></div>'); //Свойства для навигатора ____._resize = false; ____._cursor_Y = 0; ____._cursor_X = 0; ____._fixVisibledDimensions = false; ____._temporarilyVisibledDimensionsTimeout = null; //Установка обработчиков событий $iFrame.find('body').on('mousemove', ____._handlerMove); $('body').on('mousemove', ____._handlerMove); $('body').on('keydown', ____._handlerDown); $iFrame.find('body').on('keydown', ____._handlerDown); $('body').on('keyup', ____._handlerUp); $iFrame.find('body').on('keyup', ____._handlerUp); $(window).on('resize', ____._handlerResize); var iframe = document.getElementById(____._options.nameIFrame); var win = iframe.contentWindow || iframe; $(win).on('resize', ____._handlerResize); } this._destroy = function() { var $iFrame = $("#"+(____._options.nameIFrame)).contents(); $container.find(" .rif-show-dimensions").remove(); $iFrame.find('body').off('mousemove', ____._handlerMove); $('body').off('mousemove', ____._handlerMove); $('body').off('keydown', ____._handlerDown); $iFrame.find('body').off('keydown', ____._handlerDown); $('body').off('keyup', ____._handlerUp); $iFrame.find('body').off('keyup', ____._handlerUp); $(window).off('resize', ____._handlerResize); var iframe = document.getElementById(____._options.nameIFrame); var win = iframe.contentWindow || iframe; $(win).off('resize', ____._handlerResize); } this.reload = function() { ____._destroy(); ____._create(); } //Нажатие на комбинацию клавиш this._handlerDown = function(e) { if(e.which == 82 && e.ctrlKey && !e.shiftKey && !e.altKey) { if(!____._resize) { $container.trigger("rifStartResize"); //Фиксация в пикселах (чтоб меньше багов при расчётах было) и центрирование var $rif = $container.find(" .rif-show-dimensions"); $rif .attr("style", "") .css({display: "block"}); ____._fixVisibledDimensions = true; var w = Math.ceil($rif.outerWidth() + 1); var h = Math.ceil($rif.outerHeight()); var w_c = $container.find(".pmv-outer-wrap").width(); var h_c = $container.find(".pmv-outer-wrap").height(); $rif.css({ width: Math.round( w ), height: Math.round( h ), top: Math.round( (h_c - h) / 2 ), left: Math.round( (w_c - w) / 2 ), }); ____._resize = true; ____._cursor_X = false; ____._cursor_Y = false; ____._reloadShowDimensions(); } if(e.preventDefault){ e.preventDefault()} else{e.stop()};e.returnValue = false;e.stopPropagation();return false; } } //Отпускание клавиш this._handlerUp = function(e) { if( ____._resize ) { var $mnif = $container.find(" .rif-show-dimensions"); $mnif.css({display: "none"}); ____._fixVisibledDimensions = false; ____._resize = false; $container.trigger("rifStopResize"); } } this._handlerResize = function() { ____._centerIFrameAndNoEmptySpace(); ____._reloadShowDimensions(); } this._showDimensions = function() { //Добавляем класс "active" на 1 сек if(!____._fixVisibledDimensions) { var $mnif = $container.find(" .rif-show-dimensions"); if(____._temporarilyVisibledDimensionsTimeout !== null) { clearTimeout(____._temporarilyVisibledDimensionsTimeout); } if($mnif.is(":hidden")) { $mnif .attr("style", "") .css({display: "block"}); var w = Math.ceil($mnif.outerWidth() + 1); var h = Math.ceil($mnif.outerHeight()); var w_c = $container.find(".pmv-outer-wrap").width(); var h_c = $container.find(".pmv-outer-wrap").height(); $mnif.css({ width: Math.round( w ), height: Math.round( h ), top: Math.round( (h_c - h) / 2 ), left: Math.round( (w_c - w) / 2 ), }); } $mnif.css({display: "block"}); ____._temporarilyVisibledDimensionsTimeout = setTimeout(function() { $mnif.css({display: "none"}); ____._temporarilyVisibledDimensionsTimeout = null; }, 1000); } // } //Центрирование iFrame при ресайзе если он меньше контейнера, а также если рамер iFrame больше чем размер контенера то правый край лепим к правому и нижний к нижнему чтобы небыло пустого пространства //нужно для нормальной работы "map-navigator-iframe" this._centerIFrameAndNoEmptySpace = function() { var $iframe = $("#"+(____._options.nameIFrame)); var $fittingWrap = $iframe.closest(".pmv-fitting-wrap"); var $outerWrap = $iframe.closest(".pmv-outer-wrap"); var w, h, w_c, t, l, h_c; w = $fittingWrap.width(); h = $fittingWrap.height(); t = $fittingWrap.position().top; l = $fittingWrap.position().left; w_c = $outerWrap.width(); h_c = $outerWrap.height(); if( w > w_c ) { if( (l + w) < w_c ) { $fittingWrap.css({left: Math.round( - w + w_c )}); } //fix if( l > 0 ) { $fittingWrap.css({left: Math.round( 0 )}); } } else { $fittingWrap.css({left: Math.round( (w_c - w) / 2 )}); } if( h > h_c ) { if( (t + h) < h_c ) { $fittingWrap.css({top: Math.round( - h + h_c )}); } } else { $fittingWrap.css({top: 0}); } $container.trigger("rif.center-iframe"); } //Обновление показывателя текущих размеров this._reloadShowDimensions = function() { var $fittingWrap = $("#"+(____._options.nameIFrame)).closest(".pmv-fitting-wrap"); var w = $fittingWrap.width(); var h = $fittingWrap.height(); //____._options.$dimensions.find(" .rif-width").text( Math.round( w ) ); //____._options.$dimensions.find(" .rif-height").text( Math.round( h ) ); var $rif = $container.find(" .rif-show-dimensions"); $rif.find(" .rif-width").text( Math.round( w ) ); $rif.find(" .rif-height").text( Math.round( h ) ); ____._showDimensions(); } //Обновление размеров IFrame this._handlerMove = function(e) { ____._last_cursor_X = e.screenX; ____._last_cursor_Y = e.screenY; if( ____._resize ) { if(____._cursor_Y === false) { ____._cursor_X = ____._last_cursor_X; ____._cursor_Y = ____._last_cursor_Y; } var $iframe = $("#"+(____._options.nameIFrame)); var $fittingWrap = $iframe.closest(".pmv-fitting-wrap"); var w = $fittingWrap.width(); var h = $fittingWrap.height(); w += e.screenX - ____._cursor_X; h += e.screenY - ____._cursor_Y; ____._cursor_X = e.screenX; ____._cursor_Y = e.screenY; if(w < ____._options.minWIFrame) {w = ____._options.minWIFrame} if(h < ____._options.minHIFrame) {h = ____._options.minHIFrame} $fittingWrap.css({ width: Math.round( w ), height: Math.round( h ), maxHeight: "" }); $container.trigger("rifResize"); } } } modules.resizeIFrame = resizeIFrame; })(jQuery);
'use strict'; module.exports = { __configKey__: { /** * Connection details for resque service * * @see {@link https://github.com/taskrabbit/node-resque} * @type {Object} */ connection: { package: 'ioredis', host: '127.0.0.1', password: '', port: 6379, database: 0, namespace: 'resque' }, /** * Should host clear all queues on app start * * @type {Boolean} */ clearQueueOnStartup: true, /** * List of queues for worker * * @type {Array} */ queues: ['sails'], /** * Path to your resque Jobs in application * * @type {String} */ jobsPath: 'api/jobs', /** * Should hook start worker and scheduler automatically on app start ? * * @type {Object} */ autoStart: { /** * Should worker be autostarted on app start. Defaults to `true` * * If set to `false` you will need to do it manually in your application * Example: * ```javscript * // ... * sails.resque.worker.start(); * ``` * * @type {Boolean} */ worker: true, /** * Should scheduler be autostarted on app start. Defaults to `true` * * If set to `false` you will need to do it manually in your application * Example: * ```javscript * // ... * sails.resque.scheduler.start(); * ``` * @type {Boolean} */ scheduler: true } } };
function factorial(num) { if (num === 0 || num === 1) return 1; for(var i = num - 1; i >= 1; i--) { num *= i; } return num; } console.log(factorial(process.argv[2]))
import * as db from '../db.js'; export function createRoom(req) { let url = req.body.url; let title = req.body.title; if(url){ if(!/^http:\/\/|https:\/\//.test(url)){ url = 'http://' + url; } let room = db.createRoom(url.trim(), title.trim()); return Promise.resolve(room); } else{ return Promise.reject('Wrong Url'); } } export function getRoom(req) { let id = req.query.id; let room = db.getRoom(id); if(room){ return Promise.resolve(room); } else{ return Promise.reject('Not Found'); } } export function getActive(){ return Promise.resolve(db.getActive()); }
var searchData= [ ['factory',['Factory',['../interfacewcmf_1_1lib_1_1core_1_1_factory.html',1,'wcmf::lib::core']]], ['failurecontroller',['FailureController',['../classwcmf_1_1application_1_1controller_1_1_failure_controller.html',1,'wcmf::application::controller']]], ['fatal',['fatal',['../classwcmf_1_1lib_1_1core_1_1impl_1_1_log4php_logger.html#a8d1211f6f08eef712b4cfc80f22895b2',1,'wcmf\lib\core\impl\Log4phpLogger\fatal()'],['../classwcmf_1_1lib_1_1core_1_1impl_1_1_monolog_file_logger.html#a8d1211f6f08eef712b4cfc80f22895b2',1,'wcmf\lib\core\impl\MonologFileLogger\fatal()'],['../interfacewcmf_1_1lib_1_1core_1_1_logger.html#a8d1211f6f08eef712b4cfc80f22895b2',1,'wcmf\lib\core\Logger\fatal()']]], ['filecache',['FileCache',['../classwcmf_1_1lib_1_1io_1_1impl_1_1_file_cache.html',1,'wcmf::lib::io::impl']]], ['fileliststrategy',['FileListStrategy',['../classwcmf_1_1lib_1_1presentation_1_1control_1_1lists_1_1impl_1_1_file_list_strategy.html',1,'wcmf::lib::presentation::control::lists::impl']]], ['filemessage',['FileMessage',['../classwcmf_1_1lib_1_1i18n_1_1impl_1_1_file_message.html',1,'wcmf::lib::i18n::impl']]], ['fileutil',['FileUtil',['../classwcmf_1_1lib_1_1io_1_1_file_util.html',1,'wcmf::lib::io']]], ['filter',['filter',['../classwcmf_1_1lib_1_1model_1_1_node.html#a5849a1f83d8d9003b7b9ead0a731937b',1,'wcmf::lib::model::Node']]], ['filter',['Filter',['../classwcmf_1_1lib_1_1persistence_1_1validator_1_1impl_1_1_filter.html',1,'wcmf::lib::persistence::validator::impl']]], ['filtervalue',['filterValue',['../classwcmf_1_1lib_1_1presentation_1_1format_1_1impl_1_1_abstract_format.html#ab8e263d5b941af8fa12419ec1dba6664',1,'wcmf::lib::presentation::format::impl::AbstractFormat']]], ['find',['find',['../classwcmf_1_1lib_1_1search_1_1impl_1_1_lucene_search.html#a5bb35dd607d805d55f4fabadf08414de',1,'wcmf\lib\search\impl\LuceneSearch\find()'],['../interfacewcmf_1_1lib_1_1search_1_1_search.html#a5bb35dd607d805d55f4fabadf08414de',1,'wcmf\lib\search\Search\find()']]], ['finishexport',['finishExport',['../classwcmf_1_1application_1_1controller_1_1_x_m_l_export_controller.html#ae44dbe1e4ab0266b5a090985ea10258f',1,'wcmf::application::controller::XMLExportController']]], ['fitintosquare',['fitIntoSquare',['../classwcmf_1_1lib_1_1util_1_1_graphics_util.html#aa860714adf80e86f2f5c4eefd82caa8a',1,'wcmf::lib::util::GraphicsUtil']]], ['fixedliststrategy',['FixedListStrategy',['../classwcmf_1_1lib_1_1presentation_1_1control_1_1lists_1_1impl_1_1_fixed_list_strategy.html',1,'wcmf::lib::presentation::control::lists::impl']]], ['fixqueryquotes',['fixQueryQuotes',['../classwcmf_1_1test_1_1lib_1_1_base_test_case.html#ad1a59c1e7dcb4ad6a7715ffef962920e',1,'wcmf::test::lib::BaseTestCase']]], ['flip',['flip',['../classwcmf_1_1lib_1_1model_1_1visitor_1_1_layout_visitor.html#ab7b978294481794664ea5ffa6530e020',1,'wcmf::lib::model::visitor::LayoutVisitor']]], ['format',['Format',['../interfacewcmf_1_1lib_1_1presentation_1_1format_1_1_format.html',1,'wcmf::lib::presentation::format']]], ['formatter',['Formatter',['../interfacewcmf_1_1lib_1_1presentation_1_1format_1_1_formatter.html',1,'wcmf::lib::presentation::format']]], ['formatvalue',['formatValue',['../classwcmf_1_1application_1_1controller_1_1_x_m_l_export_controller.html#a0644ffdfd583dcd917f1340d4cf03f9e',1,'wcmf::application::controller::XMLExportController']]], ['fputsunicode',['fputsUnicode',['../classwcmf_1_1lib_1_1io_1_1_file_util.html#aa6760690808348739c7ca764415f26e0',1,'wcmf::lib::io::FileUtil']]], ['fromexception',['fromException',['../classwcmf_1_1lib_1_1presentation_1_1_application_error.html#a1f2f6ebfa3e2bed60cec09e80a525191',1,'wcmf::lib::presentation::ApplicationError']]], ['fromobject',['fromObject',['../classwcmf_1_1lib_1_1persistence_1_1_persistent_object_proxy.html#a44afea04975deab052cb652ae6811031',1,'wcmf::lib::persistence::PersistentObjectProxy']]], ['functionliststrategy',['FunctionListStrategy',['../classwcmf_1_1lib_1_1presentation_1_1control_1_1lists_1_1impl_1_1_function_list_strategy.html',1,'wcmf::lib::presentation::control::lists::impl']]] ];
import Ember from 'ember'; const {assert, isArray} = Ember; const {keys} = Object; export default Ember.Mixin.create({ /* Don't render anything directly. */ tagName: '', /* The attributes that need to be passed to this component. */ attrs: { context: null, name: null, range: null, domain: null, invert: false }, /* An overwritable hook for getting the range, in case the scale component needs to do something to this. */ getRange() { let range = this.getAttr('range'); /* If just a value is provided for the range, we should just assume that's meant to be the max value. */ if(!isArray(range)) { range = [0, range || 1]; } if(this.getAttr('invert')) { range = range.slice(0).reverse(); } return range; }, /* An overwritable hook for getting the domain, in case the scale component needs to do something to this. */ getDomain() { return this.getAttr('domain'); }, /* This hook executes whenever the data changes and would have triggered a render (if there was actually anything to render). */ didRender() { let range = this.getRange(); let domain = this.getDomain(); this.getAttr('_e3Context').updateMeta('scales', this.getAttr('name'), this._generateScale(range, domain)); }, /* Remove this item from the container's meta hash. */ willDestroyElement() { this.getAttr('_e3Context').removeMeta('scales', this.getAttr('name')); }, /* The private hook for generating the scale, which runs both the generate scale and add attributes hook to the scale. */ _generateScale(range, domain) { let scale = this.generateScale(range, domain); let attrs = this.generateScaleAttrs(range, domain); assert('The result of the generateScale method must be a function', typeof scale === 'function'); keys(attrs).forEach(key => { scale[key] = attrs[key]; }); return scale; }, /* Hook that generates the scale object. */ generateScale(/*range, domain*/) {}, /* Hook that returns a hash of properties and/or methods that are added to the properties on the scale method. */ generateScaleAttrs(range, domain) { return { range: range, domain: domain }; } });
"use strict"; const pgn = require("./lib/pgn"); const winston = require("winston"); const startTime = Date.now(); function getRuntime() { return (Date.now() - startTime)/1000; } function printRuntime(runTime) { winston.info(`links search had a runtime of ${runTime}s`); } exports.demo = function () { const playerName = "Kurt Richter"; winston.level = "info"; function printPgns(err, pgns) { if (err) { winston.error(err); } const runTime = getRuntime(); winston.log(pgns); printRuntime(runTime); } pgn.getPgnsForPlayer(playerName, printPgns); }; exports.getPgnsForPlayer = pgn.getPgnsForPlayer; exports.stream = pgn.stream;
import React from 'react'; import RoutingContext from 'react-router/lib/RoutingContext'; import { getPrefetchedData, getDeferredData } from 'react-fetcher'; import ReduxContextContainer from './redux-context-container'; export default class ReduxContext extends React.Component { static childContextTypes = { reduxContext: React.PropTypes.object }; static propTypes = { components: React.PropTypes.array.isRequired, params: React.PropTypes.object.isRequired, location: React.PropTypes.object.isRequired, store: React.PropTypes.object.isRequired, blocking: React.PropTypes.bool, initalClientLoading: React.PropTypes.func }; static defaultProps = { blocking: false }; constructor(props, context) { super(props, context); this.state = { loading: false, prevProps: null, inital: true && this.props.blocking }; } getChildContext() { const { loading } = this.state; return { reduxContext: { loading } }; } componentWillReceiveProps(nextProps) { const routeChanged = nextProps.location !== this.props.location; if (!routeChanged) { return; } const newComponents = this.filterAndFlattenComponents(nextProps.components, 'fetchers'); if (newComponents.length > 0) { this.loadData(newComponents, nextProps.params, nextProps.location); } else { this.setState({ loading: false, prevProps: null }); } const newComponentsDefered = this.filterAndFlattenComponents(nextProps.components, 'deferredFetchers'); if (newComponentsDefered.length > 0) { this.loadDataDefered(newComponentsDefered, nextProps.params, nextProps.location); } } componentWillUnmount() { this.unmounted = true; } createElement(Component, props) { return ( <ReduxContextContainer Component={Component} routerProps={props}/> ); } filterAndFlattenComponents(components, staticMethod) { return components.filter((component) => !!component[staticMethod]); } loadDataDefered(components, params, location) { // Get deferred data, will not block route transitions getDeferredData(components, { location, params, dispatch: this.props.store.dispatch, getState: this.props.store.getState }).catch((err) => { if (process.env.NODE_ENV !== 'production') { console.error('There was an error when fetching data: ', err); } }); } loadData(components, params, location) { const completeRouteTransition = () => { const sameLocation = this.props.location === location; if (sameLocation && !this.unmounted) { this.setState({ loading: false, prevProps: null, inital: false }); } }; if (this.props.blocking) { this.setState({ loading: true, prevProps: this.props }); } getPrefetchedData(components, { location, params, dispatch: this.props.store.dispatch, getState: this.props.store.getState }).then(() => { completeRouteTransition(); }).catch((err) => { if (process.env.NODE_ENV !== 'production') { console.error('There was an error when fetching data: ', err); } completeRouteTransition(); }); } render() { if (this.props.initalClientLoading && this.state.inital) { return <this.props.initalClientLoading />; } const props = this.state.loading ? this.state.prevProps : this.props; return <RoutingContext {...props} createElement={ this.createElement } />; } }
import { createSelector } from 'reselect'; import { calculatePayments } from '../helpers/saving'; const getSavings = (state) => state.saving; export default createSelector( [ getSavings ], (saving) => { return calculatePayments({ ...saving }) } );
/** * @author Abe Pazos / https://hamoid.com * @author Mugen87 / https://github.com/Mugen87 */ import { Geometry } from '../core/Geometry'; import { PolyhedronBufferGeometry } from './PolyhedronGeometry'; // DodecahedronGeometry function DodecahedronGeometry( radius, detail ) { Geometry.call( this ); this.type = 'DodecahedronGeometry'; this.parameters = { radius: radius, detail: detail }; this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) ); this.mergeVertices(); } DodecahedronGeometry.prototype = Object.create( Geometry.prototype ); DodecahedronGeometry.prototype.constructor = DodecahedronGeometry; // DodecahedronBufferGeometry function DodecahedronBufferGeometry( radius, detail ) { var t = ( 1 + Math.sqrt( 5 ) ) / 2; var r = 1 / t; var vertices = [ // (±1, ±1, ±1) - 1, - 1, - 1, - 1, - 1, 1, - 1, 1, - 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, 1, 1, 1, - 1, 1, 1, 1, // (0, ±1/φ, ±φ) 0, - r, - t, 0, - r, t, 0, r, - t, 0, r, t, // (±1/φ, ±φ, 0) - r, - t, 0, - r, t, 0, r, - t, 0, r, t, 0, // (±φ, 0, ±1/φ) - t, 0, - r, t, 0, - r, - t, 0, r, t, 0, r ]; var indices = [ 3, 11, 7, 3, 7, 15, 3, 15, 13, 7, 19, 17, 7, 17, 6, 7, 6, 15, 17, 4, 8, 17, 8, 10, 17, 10, 6, 8, 0, 16, 8, 16, 2, 8, 2, 10, 0, 12, 1, 0, 1, 18, 0, 18, 16, 6, 10, 2, 6, 2, 13, 6, 13, 15, 2, 16, 18, 2, 18, 3, 2, 3, 13, 18, 1, 9, 18, 9, 11, 18, 11, 3, 4, 14, 12, 4, 12, 0, 4, 0, 8, 11, 9, 5, 11, 5, 19, 11, 19, 7, 19, 5, 14, 19, 14, 4, 19, 4, 17, 1, 12, 14, 1, 14, 5, 1, 5, 9 ]; PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail ); this.type = 'DodecahedronBufferGeometry'; this.parameters = { radius: radius, detail: detail }; } DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype ); DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry; export { DodecahedronGeometry, DodecahedronBufferGeometry };
var fs = require('fs'); var utils = require('./utils'); function toLookLike() { var compare = function (actual, expected) { var result = { pass: null, message: null }; var path = utils.getFixturePathByName(expected); if(!fs.existsSync(path)) { result.pass = false; result.message = 'Does not look like '+path+'. Fixture image not found.'; } else { var fixture = fs.readFileSync(path); result.pass = new Buffer(actual, 'base64').toString() == fixture.toString(); result.message = 'Does not look like '+path+'.'; } return result; }; return { compare: compare }; } module.exports = { toLookLike: toLookLike };
Ext.onReady(function () { Ext.define('App.Model', { extend: 'Ext.data.Model', fields: [{ name: 'f', type: 'string' }, { name: 'l', type: 'string' }], identifier: 'uuid', getFullName: function () { return this.get('f') + ' ' + this.get('l'); } }); Ext.define('App.Store', { extend: 'Ext.data.Store', model: 'App.Model', requires: ['App.Model'], groupField: 'l', constructor: function (config) { var me = this, properties = config || {}; properties.proxy = me.getAppProxy(); me.callParent([properties]); }, getAppProxy: function () { var me = this; return { type: 'ajax', url: 'data.json', reader: { rootProperty: 'items', transform: { fn: function (data) { var records = me.injectDuplicate(data.items); data.items = records; return data; }, scope: me } } }; }, injectDuplicate: function (items) { var records = []; if (items) { Ext.Array.forEach(items, function (item) { records.push(item); records.push(["Tyrion", "Lanister"]); }, this); } return records; } }); try { Ext.create('App.Store', { storeId: 'myStore' }); var myStore = Ext.getStore('myStore'); myStore.load(); Ext.create('Ext.grid.Panel', { store: myStore, features: { id: 'group', ftype: 'grouping', groupHeaderTpl: '<b>{name}</b>', hideGroupedHeader: true, enableGroupingMenu: false }, columns: [{ text: 'id', dataIndex: 'id', flex: 1 }, { text: 'First Name', dataIndex: 'f' }, { text: 'Last Name', dataIndex: 'l' }, { }], renderTo: Ext.getBody() }); } catch (e) { Ext.Msg.alert('Error', e); } });
angular.module('jv.json-viewer', []);
//Choose type of accounts - disabled next button, only undisable it if user selects Abridged, Micro or Dormant $( document ) .ready( function () { $( '#choose-accounts-button' ) .attr( 'disabled', 'true' ); // Disables Next button on page load $( 'input:radio[name=choosetypeaccounts]' ) .click( function () { var checkval = $( this ) .val(); // $('#choose-accounts-button').prop('disabled', !(checkval == 'abridged' || checkval == 'micro' || checkval == 'dormant')); $( '#choose-accounts-button' ) .prop( 'disabled', !( checkval == 'abridged' ) ); } ); } ); //Start page - disabled next button, until user confirms they have a set of prepared accounts ready //$(document).ready(function(){ // $('#accounts-start-button').attr('disabled', 'true'); // Disables Next button on page load // $('input:checkbox[name=prepared]').click(function() { // var checkval = $(this).val(); // // $('#choose-accounts-button').prop('disabled', !(checkval == 'abridged' || checkval == 'micro' || checkval == 'dormant')); // $('#accounts-start-button').prop('disabled', !(checkval == 'prepared-yes')); // }); //}); //Balance sheet statements page - disabled continue/next button, until user agrees to statements //$(document).ready(function(){ // $('#statements-button').attr('disabled', 'true'); // Disables Next button on page load // $('input:checkbox[name=confirmation]').click(function() { // var checkval = $(this).val(); // $('#statements-button').prop('disabled', !(checkval == 'agree')); // //}); //Balance sheet statements //$(function(){ // $('#confirmation').on('change',function(){ // $('.confirmation-child').prop('checked',$(this).prop('checked')); // }); // $('.confirmation-child').on('change',function(){ // $('#confirmation').prop('checked',$('.confirmation-child:checked').length ? true: false); // }); // }); //About your business (2 from 3 for Micro eligibility) $( '.micro-eligibility-questions' ) .click( function () { if ( $( this ) .find( 'input[type="radio"]:checked' ) .length > 3 ) { $( ".button" ) .removeClass( "disabled" ); } else { $( ".button" ) .addClass( "disabled" ); } } ); $( '.micro-eligibility' ) .click( function () { if ( $( 'input[type=radio][value="Yes"]:checked' ) .length > 1 ) { window.location.replace( "/accounts/accounts-choose-micros" ); } else { window.location.replace( "/accounts/accounts-choose-full-or-abridged" ); } return false; } );
import { factory } from '../../../utils/factory' const name = 'splitUnit' const dependencies = ['typed'] export const createSplitUnit = /* #__PURE__ */ factory(name, dependencies, ({ typed }) => { /** * Split a unit in an array of units whose sum is equal to the original unit. * * Syntax: * * splitUnit(unit: Unit, parts: Array.<Unit>) * * Example: * * math.splitUnit(new Unit(1, 'm'), ['feet', 'inch']) * // [ 3 feet, 3.3700787401575 inch ] * * See also: * * unit * * @param {Array} [parts] An array of strings or valueless units. * @return {Array} An array of units. */ return typed(name, { 'Unit, Array': function (unit, parts) { return unit.splitUnit(parts) } }) })
'use strict'; define(['phaser', 'util'], function(Phaser, Util) { function BlueNumber(game, parent, fx) { Phaser.Group.call(this, game, parent); this.fx = fx; this.digit = this.create(0, 0, 'marbleatlas', 'COMMON03_DIGIT_0'); this.digit.animations.add('0', ['COMMON03_DIGIT_0']); this.digit.animations.add('1', ['COMMON03_DIGIT_1']); this.digit.animations.add('2', ['COMMON03_DIGIT_2']); this.digit.animations.add('3', ['COMMON03_DIGIT_3']); this.digit.animations.add('4', ['COMMON03_DIGIT_4']); this.digit.animations.add('5', ['COMMON03_DIGIT_5']); this.digit.animations.add('6', ['COMMON03_DIGIT_6']); this.digit.animations.add('7', ['COMMON03_DIGIT_7']); this.digit.animations.add('8', ['COMMON03_DIGIT_8']); this.digit.animations.add('9', ['COMMON03_DIGIT_9']); this.digit.animations.add('go', ['COMMON03_TEXT_GO']); } BlueNumber.prototype = Object.create(Phaser.Group.prototype); BlueNumber.prototype.constructor = BlueNumber; Object.defineProperty(BlueNumber.prototype, 'width', { get: function() { return this.digit.width; } }); Object.defineProperty(BlueNumber.prototype, 'height', { get: function() { return this.digit.height; } }); BlueNumber.prototype.show = function(number) { this.digit.play(number + ''); this.pivot = { x: this.width / 2, y: this.height / 2 }; }; BlueNumber.prototype.playSound = function() { Util.playSfx(this.fx, 'SELECT2'); }; BlueNumber.prototype.playSoundGo = function() { Util.playSfx(this.fx, 'GO'); }; return BlueNumber; });
/** * == DOM == * The DOM section **/ /** * == ajax == * The AJAX section **/ /** * == lang == * The LANG section **/ /** section: DOM * class Element * The Element class **/ /** related to: Element * $(element) -> Element * the $ function **/ /** section: DOM * $$(selector) -> Array * the $$ function **/ /** * Element.setStyle(@element, styles) -> Element * - element (String | Element): an id or DOM node * - styles (String | Object | Hash): can be either a regular CSS string or * a hash or regular object, in which case, properties need to be camelized * * fires element:style:updated * * Sets the style of element * and returns it **/ /** * Element#foo() -> Element * a dummy non methodized method **/ /** alias of: Element#foo * Element#bar() -> Element * fires click **/ /** section: ajax * Ajax * All requester object in the Ajax namespace share a common set of options and callbacks. * Callbacks are called at various points in the life-cycle of a request, and always feature * the same list of arguments. They are passed to requesters right along with their other options. **/ var Ajax = { /** * Ajax.getTransport( ) -> XMLHttpRequest | ActiveXObject * returns: a new instance of the XMLHttpRequest object for * standard compliant browsers, the available ActiveXObject * counter part for IE. **/ getTransport: function() { return Try.these( function() {return new XMLHttpRequest()}, function() {return new ActiveXObject('Msxml2.XMLHTTP')}, function() {return new ActiveXObject('Microsoft.XMLHTTP')} ) || false; }, /** * Ajax.activeRequestCount -> 0 **/ activeRequestCount: 0, /** * Ajax.__private__() -> Boolean **/ __private__: function() { return true } }; /** section: ajax * Ajax.Responders * includes Enumerable **/ Ajax.Responders = { /** * Ajax.Responders.responders -> Array **/ responders: [], _each: function(iterator) { this.responders._each(iterator); }, /** * Ajax.Responders.register(responder) -> undefined * Registers a responder. **/ register: function(responder) { if (!this.include(responder)) this.responders.push(responder); }, /** * Ajax.Responders.unregister(responder) -> undefined * Unregisters a responder. **/ unregister: function(responder) { this.responders = this.responders.without(responder); }, /** * Ajax.Responders.dispatch(callback, request, transport, json) -> undefined * Dispatches a callback. **/ dispatch: function(callback, request, transport, json) { this.each(function(responder) { if (Object.isFunction(responder[callback])) { try { responder[callback].apply(responder, [request, transport, json]); } catch (e) { } } }); } }; Object.extend(Ajax.Responders, Enumerable); Ajax.Responders.register({ onCreate: function() { Ajax.activeRequestCount++ }, onComplete: function() { Ajax.activeRequestCount-- } }); /** * class Ajax.Base * Abstract class **/ Ajax.Base = Klass.create({ initialize: function(options) { this.options = { method: 'post', asynchronous: true, contentType: 'application/x-www-form-urlencoded', encoding: 'UTF-8', parameters: '', evalJSON: true, evalJS: true }; Object.extend(this.options, options || { }); this.options.method = this.options.method.toLowerCase(); if (Object.isString(this.options.parameters)) this.options.parameters = this.options.parameters.toQueryParams(); else if (Object.isHash(this.options.parameters)) this.options.parameters = this.options.parameters.toObject(); } }); /** * class Ajax.Request < Ajax.Base * Main Ajax class **/ /** * new Ajax.Request(url, options) * the Ajax Request constructor **/ Ajax.Request = Klass.create(Ajax.Base, { _complete: false, initialize: function($super, url, options) { $super(options); this.transport = Ajax.getTransport(); this.request(url); }, /** * Ajax.Request#request(url) -> undefined * instanciates the request * not to be confused with [[Ajax.Request foo bar]] **/ request: function(url) { this.url = url; this.method = this.options.method; var params = Object.clone(this.options.parameters); if (!['get', 'post'].include(this.method)) { // simulate other verbs over post params['_method'] = this.method; this.method = 'post'; } this.parameters = params; if (params = Object.toQueryString(params)) { // when GET, append parameters to URL if (this.method == 'get') this.url += (this.url.include('?') ? '&' : '?') + params; else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) params += '&_='; } try { var response = new Ajax.Response(this); if (this.options.onCreate) this.options.onCreate(response); Ajax.Responders.dispatch('onCreate', this, response); this.transport.open(this.method.toUpperCase(), this.url, this.options.asynchronous); if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1); this.transport.onreadystatechange = this.onStateChange.bind(this); this.setRequestHeaders(); this.body = this.method == 'post' ? (this.options.postBody || params) : null; this.transport.send(this.body); /* Force Firefox to handle ready state 4 for synchronous requests */ if (!this.options.asynchronous && this.transport.overrideMimeType) this.onStateChange(); } catch (e) { this.dispatchException(e); } }, /** * Ajax.Request#dummy -> "dummy" * a dummy instance property for the sake of testing **/ onStateChange: function() { var readyState = this.transport.readyState; if (readyState > 1 && !((readyState == 4) && this._complete)) this.respondToReadyState(this.transport.readyState); }, setRequestHeaders: function() { var headers = { 'X-Requested-With': 'XMLHttpRequest', 'X-Prototype-Version': Prototype.Version, 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*' }; if (this.method == 'post') { headers['Content-type'] = this.options.contentType + (this.options.encoding ? '; charset=' + this.options.encoding : ''); /* Force "Connection: close" for older Mozilla browsers to work * around a bug where XMLHttpRequest sends an incorrect * Content-length header. See Mozilla Bugzilla #246651. */ if (this.transport.overrideMimeType && (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005) headers['Connection'] = 'close'; } // user-defined headers if (typeof this.options.requestHeaders == 'object') { var extras = this.options.requestHeaders; if (Object.isFunction(extras.push)) for (var i = 0, length = extras.length; i < length; i += 2) headers[extras[i]] = extras[i+1]; else $H(extras).each(function(pair) { headers[pair.key] = pair.value }); } for (var name in headers) this.transport.setRequestHeader(name, headers[name]); }, /** * Ajax.Request#success() -> Boolean * verifies the status of the request **/ success: function() { var status = this.getStatus(); return !status || (status >= 200 && status < 300); }, getStatus: function() { try { return this.transport.status || 0; } catch (e) { return 0 } }, respondToReadyState: function(readyState) { var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this); if (state == 'Complete') { try { this._complete = true; (this.options['on' + response.status] || this.options['on' + (this.success() ? 'Success' : 'Failure')] || Prototype.emptyFunction)(response, response.headerJSON); } catch (e) { this.dispatchException(e); } var contentType = response.getHeader('Content-type'); if (this.options.evalJS == 'force' || (this.options.evalJS && this.isSameOrigin() && contentType && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i))) this.evalResponse(); } try { (this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON); Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON); } catch (e) { this.dispatchException(e); } if (state == 'Complete') { // avoid memory leak in MSIE: clean up this.transport.onreadystatechange = Prototype.emptyFunction; } }, isSameOrigin: function() { var m = this.url.match(/^\s*https?:\/\/[^\/]*/); return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({ protocol: location.protocol, domain: document.domain, port: location.port ? ':' + location.port : '' })); }, getHeader: function(name) { try { return this.transport.getResponseHeader(name) || null; } catch (e) { return null } }, evalResponse: function() { try { return eval((this.transport.responseText || '').unfilterJSON()); } catch (e) { this.dispatchException(e); } }, dispatchException: function(exception) { (this.options.onException || Prototype.emptyFunction)(this, exception); Ajax.Responders.dispatch('onException', this, exception); } }); /** * Ajax.Request.classProp -> "dummy" * a dummy class property for the sake of testing **/ /** * Ajax.Request.Events = ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'] * array of possible states of an xhr request **/ Ajax.Request.Events = ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete']; Ajax.Response = Klass.create({ initialize: function(request){ this.request = request; var transport = this.transport = request.transport, readyState = this.readyState = transport.readyState; if((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) { this.status = this.getStatus(); this.statusText = this.getStatusText(); this.responseText = String.interpret(transport.responseText); this.headerJSON = this._getHeaderJSON(); } if(readyState == 4) { var xml = transport.responseXML; this.responseXML = Object.isUndefined(xml) ? null : xml; this.responseJSON = this._getResponseJSON(); } }, status: 0, statusText: '', getStatus: Ajax.Request.prototype.getStatus, getStatusText: function() { try { return this.transport.statusText || ''; } catch (e) { return '' } }, getHeader: Ajax.Request.prototype.getHeader, getAllHeaders: function() { try { return this.getAllResponseHeaders(); } catch (e) { return null } }, getResponseHeader: function(name) { return this.transport.getResponseHeader(name); }, getAllResponseHeaders: function() { return this.transport.getAllResponseHeaders(); }, _getHeaderJSON: function() { var json = this.getHeader('X-JSON'); if (!json) return null; json = decodeURIComponent(escape(json)); try { return json.evalJSON(this.request.options.sanitizeJSON || !this.request.isSameOrigin()); } catch (e) { this.request.dispatchException(e); } }, _getResponseJSON: function() { var options = this.request.options; if (!options.evalJSON || (options.evalJSON != 'force' && !(this.getHeader('Content-type') || '').include('application/json')) || this.responseText.blank()) return null; try { return this.responseText.evalJSON(options.sanitizeJSON || !this.request.isSameOrigin()); } catch (e) { this.request.dispatchException(e); } } }); Ajax.Updater = Klass.create(Ajax.Request, { initialize: function($super, container, url, options) { this.container = { success: (container.success || container), failure: (container.failure || (container.success ? null : container)) }; options = Object.clone(options); var onComplete = options.onComplete; options.onComplete = (function(response, json) { this.updateContent(response.responseText); if (Object.isFunction(onComplete)) onComplete(response, json); }).bind(this); $super(url, options); }, updateContent: function(responseText) { var receiver = this.container[this.success() ? 'success' : 'failure'], options = this.options; if (!options.evalScripts) responseText = responseText.stripScripts(); if (receiver = $(receiver)) { if (options.insertion) { if (Object.isString(options.insertion)) { var insertion = { }; insertion[options.insertion] = responseText; receiver.insert(insertion); } else options.insertion(receiver, responseText); } else receiver.update(responseText); } } }); Ajax.PeriodicalUpdater = Klass.create(Ajax.Base, { initialize: function($super, container, url, options) { $super(options); this.onComplete = this.options.onComplete; this.frequency = (this.options.frequency || 2); this.decay = (this.options.decay || 1); this.updater = { }; this.container = container; this.url = url; this.start(); }, start: function() { this.options.onComplete = this.updateComplete.bind(this); this.onTimerEvent(); }, stop: function() { this.updater.options.onComplete = undefined; clearTimeout(this.timer); (this.onComplete || Prototype.emptyFunction).apply(this, arguments); }, updateComplete: function(response) { if (this.options.decay) { this.decay = (response.responseText == this.lastText ? this.decay * this.options.decay : 1); this.lastText = response.responseText; } this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency); }, onTimerEvent: function() { this.updater = new Ajax.Updater(this.container, this.url, this.options); } }); /** deprecated, section: DOM * Toggle **/ /** deprecated * Toggle.display() -> undefined **/ /** * Toggle.foo() -> undefined * Here is a paragraph. * * Another... and some code examples below: * * alert(Toggle.foo()); * // -> does nothing * * foo.show(); * * An HTML block * * language: html * <div id="my_div"></div> * * Now a title. * =========== * **/ /** section: lang * class String * the string class. **/ /** section: lang * String.interpret(obj) -> String * a foo bar baz **/ /** section: ajax * class Ajax.Namespace **/ /** * class Ajax.Namespace.Manager **/ /** section: lang * mixin Enumerable * ruby inspired niceness **/ var Enumerable = { /** * Enumerable#each(iterator[, context]) -> Enumerable * - iterator (Function): A `Function` that expects an item in the * collection as the first argument and a numerical index as the second. * - context (Object): The scope in which to call `iterator`. Affects what * the keyword `this` means inside `iterator`. * * Calls `iterator` for each item in the collection. **/ each: function(iterator, context) { var index = 0; iterator = iterator.bind(context); try { this._each(function(value) { iterator(value, index++); }); } catch (e) { if (e != $break) throw e; } return this; }, eachSlice: function(number, iterator, context) { iterator = iterator ? iterator.bind(context) : Prototype.K; var index = -number, slices = [], array = this.toArray(); if (number < 1) return array; while ((index += number) < array.length) slices.push(array.slice(index, index+number)); return slices.collect(iterator, context); }, all: function(iterator, context) { iterator = iterator ? iterator.bind(context) : Prototype.K; var result = true; this.each(function(value, index) { result = result && !!iterator(value, index); if (!result) throw $break; }); return result; }, any: function(iterator, context) { iterator = iterator ? iterator.bind(context) : Prototype.K; var result = false; this.each(function(value, index) { if (result = !!iterator(value, index)) throw $break; }); return result; }, collect: function(iterator, context) { iterator = iterator ? iterator.bind(context) : Prototype.K; var results = []; this.each(function(value, index) { results.push(iterator(value, index)); }); return results; }, detect: function(iterator, context) { iterator = iterator.bind(context); var result; this.each(function(value, index) { if (iterator(value, index)) { result = value; throw $break; } }); return result; }, findAll: function(iterator, context) { iterator = iterator.bind(context); var results = []; this.each(function(value, index) { if (iterator(value, index)) results.push(value); }); return results; }, grep: function(filter, iterator, context) { iterator = iterator ? iterator.bind(context) : Prototype.K; var results = []; if (Object.isString(filter)) filter = new RegExp(filter); this.each(function(value, index) { if (filter.match(value)) results.push(iterator(value, index)); }); return results; }, include: function(object) { if (Object.isFunction(this.indexOf)) if (this.indexOf(object) != -1) return true; var found = false; this.each(function(value) { if (value == object) { found = true; throw $break; } }); return found; }, inGroupsOf: function(number, fillWith) { fillWith = Object.isUndefined(fillWith) ? null : fillWith; return this.eachSlice(number, function(slice) { while(slice.length < number) slice.push(fillWith); return slice; }); }, inject: function(memo, iterator, context) { iterator = iterator.bind(context); this.each(function(value, index) { memo = iterator(memo, value, index); }); return memo; }, invoke: function(method) { var args = $A(arguments).slice(1); return this.map(function(value) { return value[method].apply(value, args); }); }, max: function(iterator, context) { iterator = iterator ? iterator.bind(context) : Prototype.K; var result; this.each(function(value, index) { value = iterator(value, index); if (result == null || value >= result) result = value; }); return result; }, min: function(iterator, context) { iterator = iterator ? iterator.bind(context) : Prototype.K; var result; this.each(function(value, index) { value = iterator(value, index); if (result == null || value < result) result = value; }); return result; }, partition: function(iterator, context) { iterator = iterator ? iterator.bind(context) : Prototype.K; var trues = [], falses = []; this.each(function(value, index) { (iterator(value, index) ? trues : falses).push(value); }); return [trues, falses]; }, pluck: function(property) { var results = []; this.each(function(value) { results.push(value[property]); }); return results; }, reject: function(iterator, context) { iterator = iterator.bind(context); var results = []; this.each(function(value, index) { if (!iterator(value, index)) results.push(value); }); return results; }, sortBy: function(iterator, context) { iterator = iterator.bind(context); return this.map(function(value, index) { return {value: value, criteria: iterator(value, index)}; }).sort(function(left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; }).pluck('value'); }, toArray: function() { return this.map(); }, zip: function() { var iterator = Prototype.K, args = $A(arguments); if (Object.isFunction(args.last())) iterator = args.pop(); var collections = [this].concat(args).map($A); return this.map(function(value, index) { return iterator(collections.pluck(index)); }); }, size: function() { return this.toArray().length; }, inspect: function() { return '#<Enumerable:' + this.toArray().inspect() + '>'; } }; Object.extend(Enumerable, { map: Enumerable.collect, find: Enumerable.detect, select: Enumerable.findAll, filter: Enumerable.findAll, member: Enumerable.include, entries: Enumerable.toArray, every: Enumerable.all, some: Enumerable.any });
CartesTXT = [ { _id: "oHrrKjiBHgjBPvLEY", carteId: "L1", intitule : {fr:"Lanceur léger #1", en:"Lightweight launcher #1"}, description : {fr:"Cette fusée, type Pegasus, lance des charges légères (maximum 400Kg, uniquement en orbite basse) depuis un avion. Elle est assez fiable (85%).", en:"This rocket , like Pegasus launches light loads (max 400Kg , only in low orbit) from an airplane . It is quite reliable (85%)"}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'"orbiteHaute"/"orbiteInterplanetaire"' }, tags: ["lanceur"], categorie: "L", valEur : 15000000, valNrg : 0, valPds : 400000, valVol : 0, valSci : 0, fiabilite: 0.85, active : true, cubesat: false, copyright: "NASA", ordre: 1 }, { _id: "ASqhegWKGTwtHcRtG", carteId: "L2", intitule : {fr:"Lanceur léger #2", en:"Lightweight launcher #2"}, description : {fr:"Cette fusée, type Shavit, lance des charges très légères (maximum 200Kg, uniquement en orbite basse). Elle est peu fiable (60%).", en:"This rocket , like Shavit launches very light loads (max 200Kg , only in low orbit). It is unreliable (60%)"}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'"orbiteHaute"/"orbiteInterplanetaire"' }, tags: ["lanceur"], categorie: "L", valEur : 10000000, valNrg : 0, valPds : 200000, valVol : 0, valSci : 0, fiabilite: 0.60, active : true, cubesat: false, copyright: "IAI", ordre: 2 }, { _id: "Yq2PG7v4RyYGBcBDh", carteId: "L3", intitule : {fr:"Lanceur moyen #1", en:"Medium launcher #1"}, description : {fr:"Cette fusée, type Soyouz-Fregat, lance des charges moyennes (5t en orbite basse, 3t en orbite haute, 1.6t sur une trajectoire interplanétaire.). Elle est assez fiable (80%).", en:"This rocket , Soyuz- kind Freyat launches medium loads (5t in low orbit , 3t in high orbit, 1.6t on an interplanetary trajectory. ) . It is quite reliable (80%)"}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["lanceur"], categorie: "L", valEur : 45000000, valNrg : 0, valPds : [{condition: '{"$or":[{"deck.cartes.carteId": "O1"},{"deck.cartes.carteId": "O2"}]}', valeur: 5000000}, {condition: '{"$or":[{"deck.cartes.carteId": "O3"},{"deck.cartes.carteId": "O4"}]}', valeur: 3000000}, {condition: '{"$or":[{"deck.cartes.carteId": "O5"},{"deck.cartes.carteId": "O6"}]}', valeur: 1600000}], valVol : 0, valSci : 0, fiabilite: 0.80, active : true, cubesat: false, copyright: "NASA", ordre: 3 }, { _id: "KSpCt3RCCFwEvjYhe", carteId: "L4", intitule : {fr:"Lanceur moyen #2", en:"Medium launcher #2"}, description : {fr:"Cette fusée, type GSLV, lance des charges moyennes (5t en orbite basse, 2.5t en orbite haute, 1t sur une trajectoire interplanétaire.). Elle est très peu fiable (40%).", en:"This rocket , like GSLV launches medium loads (5t in low orbit , 2.5t in high orbit, 1t on an interplanetary trajectory. ) . It is very unreliable (40%)"}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["lanceur"], categorie: "L", valEur : 30000000, valNrg : 0, valPds : [{condition: '{"$or":[{"deck.cartes.carteId": "O1"},{"deck.cartes.carteId": "O2"}]}', valeur: 5000000}, {condition: '{"$or":[{"deck.cartes.carteId": "O3"},{"deck.cartes.carteId": "O4"}]}', valeur: 2500000}, {condition: '{"$or":[{"deck.cartes.carteId": "O5"},{"deck.cartes.carteId": "O6"}]}', valeur: 1000000}], valVol : 0, valSci : 0, fiabilite: 0.40, active : true, cubesat: false, copyright: "ISRO", ordre: 4 }, { _id: "mqtyXCcJ6QkhZsgkj", carteId: "L5", intitule : {fr:"Lanceur lourd", en:"Heavy launcher"}, description : {fr:"Cette fusée, type Ariane V, lance des charges très lourdes (grosses missions avec beaucoup d\'instruments scientifiques) : max 20t en orbite basse, 10t en orbite haute et 4t sur une trajectoire interplanétaire. Très fiable, elle peut être partagée entre plusieurs missions.", en:"This rocket , like Arianne V is capable of launching heavy loads (large missions with a lot\'s scientific instruments ) : maximum 20t in low orbit , 10t high-orbit and 4t on an interplanetary trajectory. Its reliability is excellent (90%)"}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["lanceur","lanceurLourd"], categorie: "L", valEur : 150000000, valNrg : 0, valPds : [{condition: '{"$or":[{"deck.cartes.carteId": "O1"},{"deck.cartes.carteId": "O2"}]}', valeur: 20000000}, {condition: '{"$or":[{"deck.cartes.carteId": "O3"},{"deck.cartes.carteId": "O4"}]}', valeur: 10000000}, {condition: '{"$or":[{"deck.cartes.carteId": "O5"},{"deck.cartes.carteId": "O6"}]}', valeur: 4000000}], valVol : 0, valSci : 0, fiabilite: 0.90, active : true, cubesat: false, copyright: "ESA-David Ducros 2015", ordre: 5 }, { _id: "qgHyg474YQBmbFzeT", carteId: "O1", intitule : {fr:"Orbite basse équatoriale", en:"Equatorial Low Earth Orbit"}, description : {fr:"Le satellite tourne autour de la planète dans le plan de son équateur, ce qui ne permet pas de longues observations ni du sol ni de l'espace. Une telle orbite ne permet pas non plus d'étudier les régions à haute latitude ou proche des pôles (pour les missions planétaires).", en:"The satellite orbits the planet in the plane of its equator , which only allows short observations."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'O2/O3/O4' }, tags: ["orbite","orbiteBasse"], categorie: "O", valEur : 0, valNrg : 0, valPds : 0, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "IFRES", ordre: 1 }, { _id: "5HbrWaWTtWqdhMqdj", carteId: "O2", intitule : {fr:"Orbite basse polaire", en:"Polar low Earth orbit"}, description : {fr:"Après quelques manoeuvres, le satellite tourne autour de la planète dans un plan incliné par rapport à l'équateur, ce qui permet aisément de la cartographier complètement.", en:"After a few maneuvers, the satellite orbits the planet in a plane inclined to the equator , allowing the mapping completely easily."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'O1/O3/O4' }, tags: ["orbite","orbiteBasse"], categorie: "O", valEur : 5000000, valNrg : 0, valPds : 0, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "IFRES", ordre: 2 }, { _id: "GvwqHhHEgs9MXpoZ8", carteId: "O3", intitule : {fr:"Orbite moyenne ou haute", en:"Medium or high orbit"}, description : {fr:"Après quelques manoeuvres, le satellite s'installe sur une orbite plus distante de la planète, ce qui permet des observations du ciel plus longues ou une étude planétaire plus globale.", en:"After a few maneuvers , the satellite settles on a more distant orbit of the planet , allowing longer sky observations or a broader planetary study."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'O1/O2/O4' }, tags: ["orbite","orbiteHaute"], categorie: "O", valEur : 10000000, valNrg : 0, valPds : 0, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "IFRES", ordre: 3 }, { _id: "AFh9ci3WkfgYXd53X", carteId: "O4", intitule : {fr:"Orbite lagrangienne", en:"Lagrangian orbit"}, description : {fr:"Après quelques manoeuvres, le satellite s'installe en un point de Lagrange, ce qui lui permet d'observer le Soleil en continu (en L1) ou d'observer le ciel dans de meilleures conditions (en L2). Toutefois, le coût de la manoeuvre engendre une pénalité sur la masse embarquée.", en:"After several operations , the satellite is moved to a Lagrange point , which allows him to observe the sun continuously or observing the sky in better conditions."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'O1/O2/O3' }, tags: ["orbite","orbiteHaute"], categorie: "O", valEur : 20000000, valNrg : 0, valPds : 0, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "IFRES", ordre: 4 }, { _id: "BnqbJKHAsTdPPAkDz", carteId: "O5", intitule : {fr:"Transfert d'Hohmann", en:"Hohmann transfer"}, description : {fr:"Cette orbite est obligatoire pour passer facilement d'une planète à l'autre. Une fois la manoeuvre effectuée, le vaisseau fait un survol (flyby), se met en orbite autour de l'objet ou l'utilise pour aller plus loin (fronde gravitationnelle).", en:"This orbit allows to easily switch from one planet to another."}, tip: {fr:"<span class='mandatory'>Obligatoire si mission interplanétaire, ne peut être utilisée seule.</span>", en:"<span class='mandatory'>Required if interplanetary mission may not be used alone</span>"}, regles: { necessite:'O1/O2/O3/O4/O8/Z4', incompatible:'{"objectif": "espace"}/{"planete.distance": 0}' }, tags: ["orbite","orbiteHohmann","orbiteInterplanetaire"], categorie: "O", valEur : 0, valNrg : 0, valPds : 0, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "IFRES", ordre: 5 }, { _id: "C3QroWGgbFKumvAos", carteId: "O6", intitule : {fr:"Fronde gravitationnelle", en:"Gravitational slingshot"}, description : {fr:"Pour rejoindre Mercure ou les planètes géantes, cette manoeuvre permet d'économiser beaucoup de carburant en gagnant de la vitesse via un frôlement de planète intermédiaire, atteinte grâce à un transfert d'Hohmann.", en:"To join Mercury or the giant planets , this operation saves fuel by gaining speed through a world of touch."}, tip: {fr:"", en:""}, regles: { necessite:'O5', incompatible:'{"objectif": "espace"}/{"planete.distance": {"$lte": 1}}' }, tags: ["orbite","orbiteInterplanetaire"], categorie: "O", valEur : 0, valNrg : 0, valPds : 0, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "IFRES", ordre: 6 }, { _id: "C3QroWGgbFKumvAot", carteId: "O7", intitule : {fr:"Orbite SWStrek", en:"SWStrek slingshot"}, description : {fr:"Suite à une manoeuvre hyper précise, vous utilisez un trou de ver vous permettant de rejoindre une destination à une vitesse supraluminique mais sans pouvoir la choisir.", en:"Following a precise maneuver, using a wormhole connecting you to any destination."}, tip: {fr:"", en:""}, regles: { necessite:'O1/O2/O3', incompatible:'' }, tags: ["orbite","absurde"], categorie: "O", valEur : 20000000, valNrg : 0, valPds : 0, valVol : 0, valSci : 0, fiabilite: 0, active : true, cubesat: false, copyright: "NASA", ordre: 8 }, { _id: "C3QroWGgbFKumvAou", carteId: "O8", intitule : {fr:"Flyby", en:"Flyby"}, description : {fr:"Certaines missions interplanétaires consistent en un survol d'un ou plusieurs objets (lune, astéroïde ou planète). Les données sont alors recueillies pendant un temps court. Comme il n'y a pas besoin de manoeuvres pour se mettre en orbite, ce type de mission économise un peu de carburant (5%). Il faut néanmoins rejoindre la cible (Transfert d'Hohmann avec ou sans fronde gravitationnelle).", en:"Following a precise maneuver, using a wormhole connecting you to any destination."}, tip: {fr:"", en:""}, regles: { necessite:'O5', incompatible:'' }, tags: ["orbite","orbiteInterplanetaire"], categorie: "O", valEur : 0, valNrg : 0, valPds : 0, valVol : 0, valSci : 0, fiabilite: 0, active : true, cubesat: false, copyright: "NASA", ordre: 7 }, { _id: "rGGeZaj43FPcZLnCE", carteId: "S1", intitule : {fr:"Segment sol simple", en:"Segment single ground"}, description : {fr:"C'est une version basique du segment sol qui ne permet que des fonctionnalités simples: récoltes des données et mesures en cas d'urgence.", en:"Basic operation of the ground segment which allows only simple features."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'S2/S3' }, tags: ["segmentSol"], categorie: "S", valEur : 4000000, valNrg : 0, valPds : 0, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 1 }, { _id: "q6HuipTK4NMMvzD8f", carteId: "S2", intitule : {fr:"Segment sol observatoire", en:"Segment ground observatory"}, description : {fr:"Outre les fonctions de base, ce segment sol collecte les projets scientifiques et planifie les observations visant précisément une zone du ciel ou une région planétaire.", en:"Besides the basic functions, ground segment collects scientific projects and plans aimed specifically a zone observations of the sky or region of the planet."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'S1/S3' }, tags: ["segmentSol"], categorie: "S", valEur : 10000000, valNrg : 0, valPds : 0, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 2 }, { _id: "HL4TjtpyKBwuhpRJb", carteId: "S3", intitule : {fr:"Segment sol atterisseur", en:"Segment ground lander"}, description : {fr:"Outre les fonctions avancées, ce segment sol gère les délicates phases d'atterrissage et de travail au sol.", en:"In addition to the advanced functions, it manages the ground segment delicate floor landing and work phases."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'S1/S2' }, tags: ["segmentSol","segmentSolAtterrisseur"], categorie: "S", valEur : 35000000, valNrg : 0, valPds : 0, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 3 }, { _id: "HL4TjtpyKBwuhpRJc", carteId: "S4", intitule : {fr:"Segment sol H", en:"H Segment ground"}, description : {fr:"Grâce à une équipe de hackers, vous prenez le contrôle de n'importe quelle antenne. Ce segment sol convient à toutes les missions.", en:"Thanks to a team of hackers , you take control of any other antenna satelittes . This ground segment is suitable for all missions."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["segmentSol","absurde"], categorie: "S", valEur : 20000000, valNrg : 0, valPds : 0, valVol : 0, valSci : 0, fiabilite: 0, active : true, cubesat: false, copyright: "RG SYSTEM", ordre: 4 }, { _id: "DyLg4tEdwdRtvapbW", carteId: "Z1", intitule : {fr:"Petite structure", en:"Small strucutre"}, description : {fr:"Structure pour missions ne dépassant pas 500kg.", en:"Structure for assignments not exceeding 500kg."}, tip: {fr:"", en:""}, regles: { necessite:'"thermiquePassif"§ +"energieGenerateur"§ +"energieGestion"§ +"commandesCalculateur"§ + "orbite"§ + "instrument"§ +"attitudeMoteur"§ +"attitudeGestion"§ +"communicationsAntenne"§ +"communicationsGestion"§ +"propulsion"§', incompatible:'' }, tags: ["structure"], categorie: "Z", valEur : 10000000, valNrg : 10, valPds : 20000, valVol : 0, valSci : 0, fiabilite: 1, atterrisseur: false, composants: true, maxPds: 500000, active : true, cubesat: false, copyright: "ESA", ordre: 1 }, { _id: "SLBvDGHb7EdmcuAtN", carteId: "Z2", intitule : {fr:"Structure moyenne", en:"Medium strucutre"}, description : {fr:"Structure pour missions ne dépassant pas 2t.", en:"Structure for assignments not exceeding 2t."}, tip: {fr:"", en:""}, regles: { necessite:'"thermiquePassif"§ +"energieGenerateur"§ +"energieGestion"§ +"commandesCalculateur"§ +"orbite"§ + "instrument"§ +"attitudeMoteur"§ +"attitudeGestion"§ +"communicationsAntenne"§ +"communicationsGestion"§ +"propulsion"§', incompatible:'' }, tags: ["structure"], categorie: "Z", valEur : 15000000, valNrg : 10, valPds : 100000, valVol : 0, valSci : 0, fiabilite: 1, atterrisseur: false, composants: true, maxPds: 2000000, active : true, cubesat: false, copyright: "ESA", ordre: 2 }, { id: "3tKTNLTpARcgwCm9r", carteId: "Z3", intitule : {fr:"Grande structure", en:"Big strucutre"}, description : {fr:"Structure plus robuste pour missions de plus de 2t.", en:"More robust structure for assignments of more than 2t."}, tip: {fr:"", en:""}, regles: { necessite:'"thermiquePassif"§ +"energieGenerateur"§ +"energieGestion"§ +"commandesCalculateur"§ +"orbite"§ + "instrument"§ +"attitudeMoteur"§ +"attitudeGestion"§ +"communicationsAntenne"§ +"communicationsGestion"§ +"propulsion"§', incompatible:'' }, tags: ["structure"], categorie: "Z", valEur : 40000000, valNrg : 10, valPds : 300000, valVol : 0, valSci : 0, fiabilite: 1, atterrisseur: false, composants: true, maxPds: 20000000, active : true, cubesat: false, copyright: "ESA", ordre: 3 }, { _id: "eopXLzcZDBWqCgMPq", carteId: "Z4", intitule : {fr:"Module de croisière", en:"Cruise module"}, description : {fr:"Une mission composée uniquement d'un atterrisseur a besoin d'un tel module pour effectuer le trajet interplanétaire.", en:"Accompanying one lander (without associated orbiter ), it allows them to perform the interplanetary journey."}, tip: {fr:"Nécessaire si atterrisseur et aucune autre structure choisie", en:"Required if landing gear and no other structure chosen"}, regles: { necessite:'Z5 + O5 + "attitudeMoteur"§ +"attitudeGestion"§ +"propulsion"§ + "thermiquePassif"§', incompatible:'Z1/Z2/Z3' }, tags: ["structure"], categorie: "Z", valEur : 10000000, valNrg : 10, valPds : 20000, valVol : 0, valSci : 0, fiabilite: 1, atterrisseur: false, composants: false, maxPds: 4000000, active : true, cubesat: false, copyright: "NASA", ordre: 4 }, { _id: "aC4BNNbavcXJk5pP7", carteId: "Z5", intitule : {fr:"Plateforme atterrisseur", en:"Lander platform"}, description : {fr:"Les instruments des atterrisseurs sont disposés sur une plateforme, qui peut être fixe ou mobile. Cette plateforme possède un ordinateur simple et un module de gestion de l'énergie.", en:"The instruments of the undercarriages are arranged on a platform , which may be fixed or mobile."}, tip: {fr:"", en:""}, regles: { necessite:'(((C5§ / ("communicationsAntenne"§ + "communicationsGestion"§)) + (Z1/Z2/Z3/Z4)) / ("communicationsAntenne"§ + "communicationsGestion"§ + Z4)) + S3 + "energieGenerateur"§ + "atterrisseurInstrument"§', incompatible:'{"objectif": "espace"}/{"planete.atterrisseur": false}' }, tags: ["atterrisseur","atterrisseurPlateforme"], categorie: "Z", valEur : 35000000, valNrg : 10, valPds : 100000, valVol : 0, valSci : 0, fiabilite: 1, atterrisseur: true, composants: true, maxPds: 4000000, active : true, cubesat: false, copyright: "NASA", ordre: 5 }, { _id: "ybRXgA7WbDsjSAZkq", carteId: "T1", intitule : {fr:"Contrôle thermique passif", en:"Passive thermal control"}, description : {fr:"Le contrôle thermique passif, obligatoire, repose sur la simple isolation (couvertures, radiateurs, parasols). La température du vaisseau reste dans des marges acceptables pour un coût modique.", en:"The passive thermal control , mandatory, based on the basic insulation (blankets , heaters , parasols ) . The vessel temperature remains within acceptable margins for a small fee."}, tip: {fr:"<span class='mandatory'>Obligatoire</span>", en:"<span class='mandatory'>Mandatory</span>"}, regles: { necessite:'', incompatible:'' }, tags: ["thermique","thermiquePassif"], categorie: "T", valEur : 5000000, valNrg : 0, valPds : 10000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 1 }, { _id: "b4iNMzzGQkADKCbyQ", carteId: "T2", intitule : {fr:"Contrôle thermique actif", en:"Active thermal control"}, description : {fr:"Le contrôle thermique actif utilise des résistances chauffantes ou des systèmes refroidisseurs. La température du vaisseau est parfaitement stabilisée.", en:"The active thermal control uses heaters or coolers systems. The vessel is fully temperature stabilized."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["thermique"], categorie: "T", valEur : 15000000, valNrg : 40, valPds : 25000, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "NASA", ordre: 2 }, { _id: "JCP3Qpn9A7SuH7Jr5", carteId: "T3", intitule : {fr:"Refroidisseur pour IR", en:"Cooler IR"}, description : {fr:"Les téléscopes observant dans l'infrarouge (IR) lointain doivent être refroidis à des températures proches du zéro absolu, ce qui se fait avec de l'hélium liquide.", en:"Telescopes observing in the far IR must be cooled to temperatures close to absolute zero, which is done with liquid helium."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["thermique"], categorie: "T", valEur : 40000000, valNrg : 150, valPds : 70000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 3 }, { _id: "Yz2BkW7SKyjAtDZgX", carteId: "C1", intitule : {fr:"Antenne à haut gain", en:"High-gain antenna"}, description : {fr:"Elle envoie beaucoup de données en peu de temps et peut en outre servir pour des expériences scientifiques. Elle est par contre plus chère et nécessite d'être pointée vers la Terre.", en:"It sends a lot of data in a short time and may be further server for scientific experiments . It is against more expensive and needs to be pointed towards the Earth."}, tip: {fr:"Une antenne est obligatoire", en:"An antenna is required"}, regles: { necessite:'', incompatible:'' }, tags: ["communications", "communicationsAntenne"], categorie: "C", valEur : 3000000, valNrg : 30, valPds : 15000, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 2 }, { _id: "LhbPDXuPHAEma25dj", carteId: "C2", intitule : {fr:"Antenne à bas gain", en:"Low-gain antenna"}, description : {fr:"Elle envoie peu d'informations par seconde mais n'a pas besoin d'être dirigée vers la Terre. Elle peut servir de réserve en cas de problème.", en:"It sends bit of information per second , but does not need to be directed towards the Earth. It can serve as a reserve in case of problems."}, tip: {fr:"Une antenne est obligatoire", en:"An antenna is required"}, regles: { necessite:'', incompatible:'' }, tags: ["communications", "communicationsAntenne"], categorie: "C", valEur : 1000000, valNrg : 10, valPds : 1000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 1 }, { _id: "g5Y26PMbwSt2affeK", carteId: "C3", intitule : {fr:"Gestion des communications", en:"Communications Management"}, description : {fr:"Quelques systèmes additionnels (principalement électroniques) sont nécessaires pour gérer au mieux les communications. Ils s'occupent également de l'encodage des données.", en:"Some additional systems (mainly electronic ) are needed to better manage communications. They are also involved in data encoding."}, tip: {fr:"<span class='mandatory'>Obligatoire</span>", en:"<span class='mandatory'>Mandatory</span>"}, regles: { necessite:'', incompatible:'' }, tags: ["communications", "communicationsGestion"], categorie: "C", valEur : 5000000, valNrg : 10, valPds : 5000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 5 }, { _id: "g5Y26PMbwSt2affeL", carteId: "C4", intitule : {fr:"Module Aldis", en:"Aldis Module"}, description : {fr:"Ce système bien connu des marins a été amélioré, pour une communication avec la Terre via un faisceau laser rouge modulé par le code morse. Il nécessite d'être pointé très précisément vers la Terre, puisqu'il faut observer le clignotement du faisceau pour obtenir le message.", en:"This well-known marine system has been improved , for communication with the Earth using a red laser beam modulated by Morse code . It needs to be pointed precisely toward Earth , since we must observe the flashing to hear the message."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["communications", "absurde"], categorie: "C", valEur : 2000000, valNrg : 50, valPds : 50000, valVol : 0, valSci : 0, fiabilite: 0, active : true, cubesat: false, copyright: "Tucker M. Yates", ordre: 3 }, { _id: "g5Y26PMbwSt2affeM", carteId: "C5", intitule : {fr:"Antenne pour relais", en:"Antenna relay"}, description : {fr:"Lorsqu'un atterrisseur est combiné à un orbiteur, les données sont envoyées à la Terre par ce dernier, qui sert de relais. Seul un système de communication simple est donc nécessaire sur l'atterrisseur.", en:"When combined with a lander orbiter , the data is sent to Earth by the latter, which serves as a relay . Only a single communication system is needed on the lander."}, tip: {fr:"", en:""}, regles: { necessite:'Z5 + (Z1/Z2/Z3)', incompatible:'Z4' }, tags: ["communications", "communicationsAntenneAtterrisseur"], categorie: "C", valEur : 3000000, valNrg : 15, valPds : 3000, valVol : 0, valSci : 0, fiabilite: 0, active : true, cubesat: false, copyright: "NASA", ordre: 4 }, { _id: "GYvDuwzSp7Q7DndQH", carteId: "M1", intitule : {fr:"Mémoire standard", en:"Standard Memory"}, description : {fr:"Elle stocke 50Gb de données collectées jusqu'à ce qu'elles puissent être envoyées.", en:"Stores 50Gb of data collected until they can be sent."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["commandes","commandesMemoire"], categorie: "M", valEur : 300000, valNrg : 3, valPds : 1000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "SSTL", ordre: 1 }, { _id: "2Wo7amLvNB89MnHCJ", carteId: "M2", intitule : {fr:"Mémoire moyenne", en:"Medium Memory"}, description : {fr:"Elle stocke 200Gb de données collectées jusqu'à ce qu'elles puissent être envoyées.", en:"Stores 200Gb of data collected until they can be sent."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["commandes","commandesMemoire"], categorie: "M", valEur : 500000, valNrg : 4, valPds : 2000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "Airbus Defence and Space SAS", ordre: 2 }, { _id: "wF5zyJF74qFRShHqn", carteId: "M3", intitule : {fr:"Grosse Mémoire", en:"Big Memory"}, description : {fr:"Elle stocke 2Tb de données, en deux systèmes séparés, ce qui permet de conserver une certaine mémoire s'il y a un problème électronique.", en:"Stores 2Tb data in two separate systems , which allows to retain a certain memory if there is an electronic failure"}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["commandes","commandesMemoire"], categorie: "M", valEur : 1000000, valNrg : 7, valPds : 3000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "SSTL", ordre: 3 }, { _id: "36CjTZBcQEWvSSpRj", carteId: "M4", intitule : {fr:"Calculateur de bord simple", en:"Single board computer"}, description : {fr:"Il s'agit d'un calculateur minimal, sans redondance.", en:"Minimum computer without redundancy"}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["commandes","commandesCalculateur"], categorie: "M", valEur : 8000000, valNrg : 25, valPds : 4000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "Airbus Defence and Space SAS", ordre: 4 }, { _id: "XqG3hk5pkapA27Kmo", carteId: "M5", intitule : {fr:"Calculateur de bord standard", en:"Standard board computer"}, description : {fr:"Il s'agit d'un calculateur qui effectue les opérations standards et possède des systèmes de réserve, activés en cas de problème, permettant d'éviter la perte de la mission.", en:"Calculator that performs standard operations and has reserve systems , activated in case of trouble , avoiding the loss of the mission."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["commandes","commandesCalculateur"], categorie: "M", valEur : 10000000, valNrg : 30, valPds : 5000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 5 }, { _id: "4a3mF7ZiSic242bAW", carteId: "M6", intitule : {fr:"Calculateur de bord avancé", en:"Advanced board computer"}, description : {fr:"En plus des opérations standards et des systèmes de réserve, il peut prendre des décisions simples sans devoir communiquer avec la Terre.", en:"In addition standrads operations and reserves , it can make simple decisions without having to communicate with Earth."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["commandes","commandesCalculateur"], categorie: "M", valEur : 20000000, valNrg : 50, valPds : 6000, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 6 }, { _id: "EBtFYf6esMBNavhEg", carteId: "E1", intitule : {fr:"Panneau solaire de faible puissance", en:"Low power solar panel"}, description : {fr:"Ils fournissent 150W quand ils sont éclairés non loin de la Terre, 300W près de Vénus, 900W près de Mercure et 75W près de Mars. Ils ne sont pas utilisables au-delà de l'orbite de Mars.", en:"They provide 150W when illuminated near the Earth, Venus nearly 300W , 1kW near Mercure."}, tip: {fr:"", en:""}, regles: { necessite:'"energieBatterie"', incompatible:'{"planete.rayonnement": {"$lt": 0.5} }' }, tags: ["energie","energieGenerateur","energieSolaire"], categorie: "E", valEur : 2000000, valNrg : 150, valPds : 10000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 1 }, { _id: "J6CPuaXhjvdWkpp8J", carteId: "E2", intitule : {fr:"Panneau solaire de moyenne puissance", en:"Medium power solar panel"}, description : {fr:"Ils fournissent 600W quand ils sont éclairés non loin de la Terre, 300W près de Mars. Ils ne sont pas utilisables au-delà de l'orbite de Mars.", en:"They provide 600W when illuminated near the Earth, Mars nearly 300W."}, tip: {fr:"", en:""}, regles: { necessite:'"energieBatterie"', incompatible:'{"planete.rayonnement": {"$lt": 0.5} }' }, tags: ["energie","energieGenerateur","energieSolaire"], categorie: "E", valEur : 6000000, valNrg : 600, valPds : 30000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 2 }, { _id: "cLnuDTL7LJ5XFbdhA", carteId: "E3", intitule : {fr:"Panneau solaire de grande puissance", en:"High power solar panel"}, description : {fr:"Ils fournissent 1kW quand ils sont éclairés non loin de la Terre, 2kW près de Vénus, 6kW près de Mercure, 500W près de Mars et, après traitement spécial, 100W aux alentours de Jupiter et des astéroïdes.", en:"They provide 1kW when illuminated near the Earth and 500W near Mars and after special treatment, 100W near Jupiter."}, tip: {fr:"", en:""}, regles: { necessite:'"energieBatterie"', incompatible:'' }, tags: ["energie","energieGenerateur","energieSolaire"], categorie: "E", valEur : 10000000, valNrg : 1000, valPds : 50000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 3 }, { _id: "ZY9RhiAC2NXYgvf2z", carteId: "E4", intitule : {fr:"Générateur thermoélectrique", en:"Thermoelectric generator"}, description : {fr:"Le RTG fournit 165W quelles que soient les conditions et ce durant des années. Il est indispensable pour les missions au-delà de Jupiter.", en:"RTG provides 165W whatever the conditions and this for years. It is essential for missions beyond Jupiter."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["energie","energieThermo","energieGenerateur"], categorie: "E", valEur : 140000000, valNrg : 165, valPds : 50000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "NASA", ordre: 4 }, { _id: "rjiEha33XBRjMX5tm", carteId: "E5", intitule : {fr:"Pile à combustible", en:"Fuel cell"}, description : {fr:"La pile fournit 1kW quelles que soient les conditions, mais seulement durant quelques mois. Elle a été utilisée lors de nombreuses missions de la navette américaine.", en:"The battery provides what 1kW all conditions , but only for a few months . It has been used in numerous missions of the Space Shuttle."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["energie","energieGenerateur"], categorie: "E", valEur : 10000000, valNrg : 1000, valPds : 20000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "NASA", ordre: 5 }, { _id: "HYbsrh7X5tJwvxJRo", carteId: "E6", intitule : {fr:"Batterie rechargeable", en:"Rechargeable Battery"}, description : {fr:"La batterie stocke l'énergie fournie par ailleurs, pour la restituer en cas d'obscurité (pour les panneaux solaires) et/ou en cas de pic d'utilisation (pour les RTG).", en:"The battery stores the energy supplied also to restore it in case of darkness ( for solar panels ) and / or in case of peak usage (for RTG )."}, tip: {fr:"<span class='mandatory'>Obligatoire si panneau solaire</span>", en:"<span class='mandatory'>Mandatory if solar panel</span>"}, regles: { necessite:'', incompatible:'' }, tags: ["energie","energieBatterie"], categorie: "E", valEur : 1000000, valNrg : 5, valPds : 40000, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 6 }, { _id: "XbDKuyS5jcPd9H7rX", carteId: "E7", intitule : {fr:"Gestion de l'énergie", en:"Energy management"}, description : {fr:"Ces systèmes électroniques indispensables contrôlent la fourniture d'énergie électrique au vaisseau.", en:"These indispensable electronic systems control the supply of electronic energy to the ship."}, tip: {fr:"<span class='mandatory'>Obligatoire</span>", en:"<span class='mandatory'>Mandatory</span>"}, regles: { necessite:'', incompatible:'' }, tags: ["energie","energieGestion"], categorie: "E", valEur : 5000000, valNrg : 10, valPds : 10000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 7 }, { _id: "rDyvk76zf9vt4MCEc", carteId: "A1", intitule : {fr:"Senseurs solaires", en:"Sun sensors"}, description : {fr:"Pour la stabilisation 3 axes, les senseurs solaires estiment approximativement l'attitude du vaisseau en utilisant la direction du Soleil.", en:"Stabilization 3-axis solar sensors say about the attitude of the ship using the direction of the sun."}, tip: {fr:"", en:""}, regles: { necessite:'S2/S3', incompatible:'' }, tags: ["attitude","attitudeCapteur"], categorie: "A", valEur : 1000000, valNrg : 2, valPds : 1000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 1 }, { _id: "XXe5EGLAynHrJCWxm", carteId: "A2", intitule : {fr:"Senseurs stellaires", en:"Stellar sensors"}, description : {fr:"Pour la stabilisation 3 axes, ce système mesure précisément l'attitude du vaisseau en utilisant la position d'étoiles brillantes.", en:"Stabilization 3-axis , the system accurately measures the attitude of the vessel using the bright stars position."}, tip: {fr:"", en:""}, regles: { necessite:'S2/S3', incompatible:'' }, tags: ["attitude","attitudeCapteur"], categorie: "A", valEur : 5000000, valNrg : 10, valPds : 5000, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 2 }, { _id: "K2eRAMcET2tmbfBbp", carteId: "A3", intitule : {fr:"Centrale inertielle", en:"Inertial Central"}, description : {fr:"Pour la stabilisation 3 axes, la centrale inertielle mesure précisément l'attitude du vaisseau grâce à une référence interne stable. Cette référence dérive cependant au cours du temps, mais cela peut être (en grande partie) calibré.", en:"Stabilization 3-axis inertial measurement centralle precisely the attitude of vaiseau through stable internal reference. This reference drift with time, but this can be calibrated."}, tip: {fr:"", en:""}, regles: { necessite:'S2/S3', incompatible:'' }, tags: ["attitude","attitudeCapteur"], categorie: "A", valEur : 7000000, valNrg : 10, valPds : 7000, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 3 }, { _id: "c3PYq92BnsmtjfRtu", carteId: "A4", intitule : {fr:"Petites roues à réaction", en:"Small reaction wheels"}, description : {fr:"Les petites roues à réaction permettent une stabilisation 3 axes des structures légères et un pointage précis vers n'importe quelle direction si l'attitude est mesurée par ailleurs.", en:"Small reaction wheels allow a 3-axis stabilization lightweight structures and a precise pointing to any direction if the attitude is measured elsewhere."}, tip: {fr:"", en:""}, regles: { necessite:'"propulsion"§ + (S2/S3) + "attitudeCapteur"§ + (Z1/Z4)', incompatible:'Z2/Z3/Z5/A6§' }, tags: ["attitude","attitudeRoues","attitudeMoteur"], categorie: "A", valEur : 2000000, valNrg : 10, valPds : 5000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 5 }, { _id: "SZn7CPFBN4HMcq9jM", carteId: "A5", intitule : {fr:"Grosses roues à réaction", en:"Big reaction wheels"}, description : {fr:"Les grosses roues à réaction permettent une stabilisation 3 axes des structures moyennes ou lourdes, et un pointage précis vers n'importe quelle direction si l'attitude est mesurée par ailleurs.", en:"Large reaction wheels allow a 3-axis stabilization means or heavy structures , and a precise pointing to any direction if the attitude is measured elsewhere."}, tip: {fr:"", en:""}, regles: { necessite:'"propulsion"§ + (S2/S3) + "attitudeCapteur"§ + Z3', incompatible:'Z1/Z2/Z4/Z5/A6§' }, tags: ["attitude","attitudeRoues","attitudeMoteur"], categorie: "A", valEur : 5000000, valNrg : 40, valPds : 30000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 7 }, { _id: "wBK7xhARTxY5xBo3c", carteId: "A6", intitule : {fr:"Stabilisation par rotation", en:"Stabilization rotation"}, description : {fr:"Le vaisseau est stabilisé suivant un axe par sa propre rotation, ce qui facilite les scans du ciel ou du sol planétaire, ainsi que les mesures environnementales (champ magnétique, particules). On ne peut par contre pointer où l'on veut, donc c'est inutilisable pour les observations d'une zone précise du ciel ou du sol.", en:"The vessel is stabilized in an axis by its own rotation , which facilitates the scans of the sky and of global soil and environmental measures ( magnetic field, particles). One can against by pointing where you want , so it's unusable for observations of a specific area of ​​the sky or ground."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'I21§ / I5§ / I7§ / I8§ / I12§ / I16§ / A9§ / A4§ / A5§ / S2' }, tags: ["attitude","attitudeMoteur","propulsion"], categorie: "A", valEur : 100000, valNrg : 0, valPds : 1000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "ESA/NASA", ordre: 9 }, { _id: "oELLENbJm4EpTYSyJ", carteId: "A7", intitule : {fr:"Gestion de l'attitude", en:"Management attitude"}, description : {fr:"Ces systèmes électroniques sont indispensables pour gérer l'attitude du vaisseau et corriger l'orbite si nécessaire.", en:"These electronic systems are essential to handle the attitude of the spacecraft 's orbit and correct if necessary."}, tip: {fr:"<span class='mandatory'>Obligatoire</span>", en:"<span class='mandatory'>Mandatory</span>"}, regles: { necessite:'', incompatible:'' }, tags: ["attitude","attitudeGestion"], categorie: "A", valEur : 5000000, valNrg : 5, valPds : 5000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 10 }, { _id: "SZn7CPFBN4HMcq9jN", carteId: "A8", intitule : {fr:"Roues Rodent", en:"Rodent wheels"}, description : {fr:"Une souris, un hamster et un cochon d'inde actionnent des roues gyroscopiques pour maintenir l'attitude du vaisseau, un système économe mais de durée de vie faible. Attention à l'accumulation de fèces pouvant conduire au blocage des roues.", en:"Mouse, hamster and guinea pig operate gyroscopic wheels to maintain the attitude of the vessel, an efficient system but low life. Attention to life module necessary for the survival of animals."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["attitude","attitudeRoues","absurde"], categorie: "A", valEur : 500000, valNrg : 4, valPds : 3000, valVol : 0, valSci : 1, fiabilite: 0, active : true, cubesat: false, copyright: "statestreetanimalhospital.com", ordre: 8 }, { _id: "SZn7CPFBN4HMcq9jO", carteId: "A9", intitule : {fr:"Moyennes roues à réaction", en:"Middle reaction wheels"}, description : {fr:"Les moyennes roues à réaction permettent une stabilisation 3 axes des structures moyennes, et un pointage précis vers n'importe quelle direction si l'attitude est mesurée par ailleurs.", en:"Large reaction wheels allow a 3-axis stabilization means or heavy structures , and a precise pointing to any direction if the attitude is measured elsewhere."}, tip: {fr:"", en:""}, regles: { necessite:'"propulsion"§ + (S2/S3) + "attitudeCapteur"§ + Z2', incompatible:'Z1/Z3/Z4/Z5/A6§' }, tags: ["attitude","attitudeRoues","attitudeMoteur"], categorie: "A", valEur : 3500000, valNrg : 25, valPds : 15000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "NASA", ordre: 6 }, { _id: "K2eRAMcET2tmbfBbq", carteId: "A10", intitule : {fr:"Capteur de pointage fin (FGS)", en:"Fine Guidance Sensor"}, description : {fr:"Pour les bons observatoires, ce système de guidage fin complète les senseurs stellaires et roues à réactions. Il permet d'obtenir des données de qualité inégalée grâce à un pointage extrêmement précis contrôlé en continu.", en:"Stabilization 3-axis inertial measurement centralle precisely the attitude of vaiseau through stable internal reference. This reference drift with time, but this can be calibrated."}, tip: {fr:"", en:""}, regles: { necessite:'{"objectif": "espace"} + "attitudeCapteur"§ + "attitudeRoues"§', incompatible:'A6§' }, tags: ["attitude"], categorie: "A", valEur : 2000000, valNrg : 2, valPds : 2000, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 4 }, { _id: "ro9HmSYbgvrmza4Gx", carteId: "P1", intitule : {fr:"Gros Moteurs d'appoint", en:"Big Extra motors"}, description : {fr:"Ces mini-fusées permettent de rester sur l'orbite choisie, d'ajuster finement les manoeuvres de pointage en cas de stabilisation 3 axes pour structures moyennes et grandes, et de retrouver la Terre en cas de problème. Ils fonctionnent à l'hydrazine.", en:"These mini- rockets used to stay on the orbit chosen , finely adjust poitage maneuvers in case of 3-axis stabilization , and find Earth in case of problems . They operate hydrazine."}, tip: {fr:"", en:""}, regles: { necessite:'S2/S3', incompatible:'{"planete.distance": {"$gte": 1}}' }, tags: ["propulsion","propulsionMoteur","propulsionMoteurP1"], categorie: "P", valEur : 5000000, valNrg : 0, valPds : 100000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "CNES", ordre: 2 }, { _id: "kwKpYWTSP8tTLLQ58", carteId: "P2", intitule : {fr:"Propulsion biergol Vénus/Mars", en:"Bipropellant Engine Venus/March"}, description : {fr:"Par une poussée forte mais courte, cette propulsion met le vaisseau sur une trajectoire d'Hohmann vers Vénus ou Mars. Elle comprend moteurs et réservoirs pour deux ergols, et assure en outre les petites manoeuvres (pointage).", en:"By a strong but short spurt, this propulsion puts the ship on a trajectory to Venus or Mars Hohmann . It includes engines and propellant tanks for two , and further ensures small maneuvers ( score ) ."}, tip: {fr:"", en:""}, regles: { necessite:'O5', incompatible:'{"planete.distance": {"$gt": 1}}' }, tags: ["propulsion", "propulsionInterplanetaire"], categorie: "P", valEur : [{condition: '{"objectif": {"$exists": true}}', valeur: 30000000}, {condition: '{"deck.cartes": {"$elemMatch": {"carteId": "O8", "active": true}}}', valeur: 25000000}], valNrg : 0, valPds : 400000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 3 }, { _id: "aQDRZzaF7zQgdxykp", carteId: "P3", intitule : {fr:"Propulsion biergol autres objets", en:"Propulsion bipropellant other items"}, description : {fr:"Par une poussée forte mais courte, cette propulsion met le vaisseau sur une trajectoire interplanétaire vers Mercure, les astéroïdes ou les planètes géantes. Elle comprend moteurs et réservoirs pour deux ergols, et assure en outre les petites manoeuvres (pointage).", en:"By a strong but short spurt, this propulsion puts the ship on interplanetary trajectory to Mercury , asteroids or giant planets . It includes engines and propellant tanks for two , and further ensures small maneuvers ( score ) ."}, tip: {fr:"", en:""}, regles: { necessite:'O5', incompatible:'{"planete.distance": {"$lt": 2}}' }, tags: ["propulsion", "propulsionInterplanetaire"], categorie: "P", valEur : [{condition: '{"deck.cartes": {"$exists": true}}', valeur: 70000000}, {condition: '{"deck.cartes": {"$elemMatch": {"carteId": "O8", "active": true}}}', valeur: 66500000}, {condition: '{"deck.cartes": {"$elemMatch": {"carteId": "O6", "active": true}}}', valeur: 35000000}, {condition: '{"deck.cartes": {"$elemMatch": {"$and": [{"carteId": "O6", "active": true},{"carteId": "O8", "active": true}]}}}', valeur: 33250000}], valNrg : 0, valPds : [{condition: '{"deck.cartes": {"$exists": true}}', valeur: 850000}, {condition: '{"deck.cartes": {"$elemMatch": {"carteId": "O6", "active": true}}}', valeur: 425000}], valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "NASA", ordre: 4 }, { _id: "mopMkJJJNbfWqYaDH", carteId: "P4", intitule : {fr:"Propulsion électrique", en:"Electric propulsion"}, description : {fr:"Cette propulsion met le vaiseau sur une trajectoire interplanétaire. Elle utilise un moteur électrique, qui fournit une poussée faible mais continue. Le temps pour rejoindre la cible est cependant très long.", en:"This puts the propulsion vaiseau on an interplanetary trajectory. It uses an electric motor , which provides a low thrust but continues . The time to reach the target is long."}, tip: {fr:"", en:""}, regles: { necessite:'O5', incompatible:'' }, tags: ["propulsion", "propulsionInterplanetaire"], categorie: "P", valEur : [{condition: '{"deck.cartes": {"$exists": true}}', valeur: 50000000}, {condition: '{"deck.cartes": {"$elemMatch": {"carteId": "O8", "active": true}}}', valeur: 47500000}, {condition: '{"deck.cartes": {"$elemMatch": {"carteId": "O6", "active": true}}}', valeur: 25000000}, {condition: '{"deck.cartes": {"$elemMatch": {"$and": [{"carteId": "O6", "active": true},{"carteId": "O8", "active": true}]}}}', valeur: 23750000}], valNrg : 500, valPds : [{condition: '{"deck.cartes": {"$exists": true}}', valeur: 150000}, {condition: '{"deck.cartes": {"$elemMatch": {"carteId": "O6", "active": true}}}', valeur: 75000}], valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 5 }, { _id: "mopMkJJJNbfWqYaDI", carteId: "P5", intitule : {fr:"Propulsion C&V", en:"Steam coal propulsion"}, description : {fr:"Cette propulsion repose sur la combustion de charbon pour chauffer de l'eau, de manière à créer un jet de vapeur dans l'air.", en:"This propulsion is based on coal combustion for heating water , so as to create a jet of steam in the air."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["propulsion","absurde"], categorie: "P", valEur : 20000000, valNrg : 0, valPds : 1000000, valVol : 0, valSci : 0, fiabilite: 0, active : true, cubesat: false, copyright: "timerime.com", ordre: 6 }, { _id: "ro9HmSYbgvrmza4Gy", carteId: "P6", intitule : {fr:"Petits moteurs d'appoint", en:"Extra motors"}, description : {fr:"Ces mini-fusées permettent de rester sur l'orbite choisie, d'ajuster approximativement les manoeuvres de pointage en cas de stabilisation 3 axes pour petites structures, et de retrouver la Terre en cas de problème. Ils fonctionnent à l'hydrazine.", en:"These mini- rockets used to stay on the orbit chosen , finely adjust poitage maneuvers in case of 3-axis stabilization , and find Earth in case of problems . They operate hydrazine."}, tip: {fr:"", en:""}, regles: { necessite:'S2', incompatible:'{"planete.distance": {"$gte": 1}}' }, tags: ["propulsion","propulsionMoteur"], categorie: "P", valEur : 2000000, valNrg : 0, valPds : 20000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 1 }, { _id: "p2NABZpZE6RnBPMcH", carteId: "I1", intitule : {fr:"Petit télescope", en:"Small telescope"}, description : {fr:"Il permet de construire un observatoire spatial simple. Comme tout téléscope, il doit être complété par un imageur ou un spectromètre.", en:"Lets build a simple space observatory , eg . for scans of the sky or the low-resolution mapping."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["instrument", "instrumentTelescope", "instrumentEspace"], categorie: "I", valEur : 53000000, valNrg : 10, valPds : 215000, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 1 }, { _id: "N87ziA7X8j4jMuaaC", carteId: "I2", intitule : {fr:"Télescope moyen", en:"Medium telescope"}, description : {fr:"Il permet de construire un observatoire spatial standard.", en:"Lets build a standard space observatory."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["instrument", "instrumentTelescope", "instrumentEspace"], categorie: "I", valEur : 150000000, valNrg : 10, valPds : 750000, valVol : 0, valSci : 2, fiabilite: 1, active : true, cubesat: false, copyright: "NASA", ordre: 2 }, { _id: "H2KJyjDzYifTfEyGn", carteId: "I3", intitule : {fr:"Gros télescope", en:"Big telescope"}, description : {fr:"Il permet de construire un observatoire spatial de pointe, tels Hubble ou Herschel, fournissant des données en haute résolution. Son attitude doit être parfaitement contrôlée.", en:"Allows building advanced space observatory , Hubble and Herschel tls , providing high resolution data. His attitude must be perfectly controlled."}, tip: {fr:"", en:""}, regles: { necessite:'"attitudeRoues"§', incompatible:'' }, tags: ["instrument", "instrumentTelescope", "instrumentEspace"], categorie: "I", valEur : 200000000, valNrg : 10, valPds : 2000000, valVol : 0, valSci : 4, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 3 }, { _id: "NTtptTDCikwKjjefh", carteId: "I4", intitule : {fr:"Imageur visible basse résolution", en:"Visible detector low resolution"}, description : {fr:"Disposé à la sortie d'un télescope simple, il prend des images du ciel peu détaillées et monochromes, correspondant à toute la gamme visible. Il est utilisé pour des scans ou avec un pointage précis.", en:"Disposed at the outlet of a telescope , it allows to make images of the sky in the range of visible light . It is used for scans or with a specific score."}, tip: {fr:"", en:""}, regles: { necessite:'I1§ / I2§', incompatible:'I3§' }, tags: ["instrument", "instrumentScan", "instrumentEspace"], categorie: "I", valEur : 2000000, valNrg : 3, valPds : 4000, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "HST", ordre: 4 }, { _id: "s5t2WLRcYe6hy82Ey", carteId: "I5", intitule : {fr:"Spectromètre visible basse résolution", en:"Visible spectrometer low resolution"}, description : {fr:"Disposé à la sortie d'un télescope, il permet d'avoir une première idée de nombreuses propriétés des astres observés (composition, vitesse, ...) mais il nécessite un pointage précis.", en:"Disposed at the outlet of a telescope , it allows to evaluate many properties observed stars (composition, speed , ...) but it requires a precise pointing."}, tip: {fr:"", en:""}, regles: { necessite:'(I1§ / I2§ ) + "attitudeRoues"§', incompatible:'I3§' }, tags: ["instrument", "instrumentScan", "instrumentEspace"], categorie: "I", valEur : 7000000, valNrg : 15, valPds : 40000, valVol : 0, valSci : 2, fiabilite: 1, active : true, cubesat: false, copyright: "ESO", ordre: 6 }, { _id: "MJA9sZoR8F62CkpsE", carteId: "I6", intitule : {fr:"Imageur IR", en:"IR Detector"}, description : {fr:"Disposé à la sortie d'un télescope, il produit des cartes de température ou des cartes associées à la signature de certaines molécules, mais il doit être refroidi. il est utilisé pour des scans ou avec un pointage précis.", en:"Disposed at the outlet of a telescope , it produces temperature card or cards associated with the signing of certain molecules , but it must be cooled . it is used for scans or with a specific score."}, tip: {fr:"", en:""}, regles: { necessite:'T3§ + (I1§ / I2§ / I3§)', incompatible:'' }, tags: ["instrument", "instrumentScan", "instrumentEspace"], categorie: "I", valEur : 5000000, valNrg : 20, valPds : 10000, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 8 }, { _id: "bNe3YcTzcbW5MR23t", carteId: "I7", intitule : {fr:"Spectro IR", en:"IR Spectrometer"}, description : {fr:"Disposé à la sortie d'un télescope, il permet d'étudier en détail la composition moléculaire des objets observés mais il nécessite un pointage précis et un refroidissement spécifique.", en:"Located at the outlet of a telescope he used to study in detail the molecular composition of the objects observed but it requires precise aiming and additional cooling."}, tip: {fr:"", en:""}, regles: { necessite:'T3§ + "attitudeRoues"§ + (I1§ / I2§ / I3§)', incompatible:'' }, tags: ["instrument", "instrumentScan", "instrumentEspace"], categorie: "I", valEur : 10000000, valNrg : 30, valPds : 20000, valVol : 0, valSci : 2, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 9 }, { _id: "JZyJBX8693nmkznMF", carteId: "I8", intitule : {fr:"Spectro-imageur UV", en:"UV Spectral imager"}, description : {fr:"Disposé à la sortie d'un télescope, il permet d'étudier en détail la composition atomique de toute une zone du ciel mais il nécessite un pointage précis.", en:"Located at the outlet of a telescope he used to study in detail the atomic composition of a whole area of ​​the sky but it requires precise pointing."}, tip: {fr:"", en:""}, regles: { necessite:'"attitudeRoues"§ + (I1§ / I2§ / I3§)', incompatible:'' }, tags: ["instrument", "instrumentScan", "instrumentEspace"], categorie: "I", valEur : 30000000, valNrg : 25, valPds : 30000, valVol : 0, valSci : 2, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 10 }, { _id: "bbuH4rNeTteSERysK", carteId: "I9", intitule : {fr:"Polariseur visible", en:"Visible polarizer"}, description : {fr:"Disposé à la sortie d'un télescope et devant un détecteur ou un spectromètre visible, il permet d'étudier la polarisation de la lumière, liée par ex. à la présence de champ magnétique dans les astres.", en:"Disposed at the outlet of a telescope and a front sensor or a visible spectrometer , it allows to study the polarization of light , due eg . in the presence of magnetic field in the stars."}, tip: {fr:"", en:""}, regles: { necessite:'(I1§ / I2§ / I3§) + (I4§ / I5§ / I20§ / I21§)', incompatible:'' }, tags: ["instrument", "instrumentScan", "instrumentEspace"], categorie: "I", valEur : 30000000, valNrg : 40, valPds : 20000, valVol : 0, valSci : 2, fiabilite: 1, active : true, cubesat: false, copyright: "Espadons/Narval", ordre: 11 }, { _id: "S6NQtMAdSTi8ujNRf", carteId: "I10", intitule : {fr:"Imageur planétaire basse résolution", en:"Planet Imager low resolution"}, description : {fr:"Il fournit des images peu détaillées, mais d'une zone très étendue. Il est utilisé en vol (pour des scans ou avec un pointage précis) ou après atterrissage (seul ou en complément du microscope).", en:"It provides low-detail images, but a very large area. It is used in flight (for scans or with a precise pointing ) or after landing ( alone or with the microscope )."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["instrument", "instrumentPlanete"], categorie: "I", valEur : 3000000, valNrg : 5, valPds : 7000, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "NASA", ordre: 12 }, { _id: "ffPtA9FZLnoRyCGpZ", carteId: "I11", intitule : {fr:"Imageur planétaire moyenne résolution", en:"Planet Imager medium resolution"}, description : {fr:"Il fournit des images détaillées d'une zone de taille moyenne. Il est utilisé en vol (pour des scans ou avec un pointage précis) ou après atterrissage.", en:"It provides detailed images of a medium sized area. It is used in flight (for scans or with a precise pointing ) or after landing."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["instrument", "instrumentPlanete"], categorie: "I", valEur : 7000000, valNrg : 10, valPds : 15000, valVol : 0, valSci : 2, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 13 }, { _id: "qHiPo43Dm98vq4LyF", carteId: "I12", intitule : {fr:"Imageur planétaire haute résolution", en:"Planet Imager high resolution"}, description : {fr:"Il fournit des images très détaillées, mais d'une zone de très petite taille. Un contrôle précis de l'attitude est nécessaire.", en:"It provides very detailed images, but in a very waist area. Precise control of attitude is necessary."}, tip: {fr:"", en:""}, regles: { necessite:'"attitudeRoues"§', incompatible:'Z5§' }, tags: ["instrument", "instrumentPlanete"], categorie: "I", valEur : 10000000, valNrg : 20, valPds : 20000, valVol : 0, valSci : 3, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 14 }, { id: "iL5KYTNJhbiKdzYT9", carteId: "I13", intitule : {fr:"Imageur planétaire IR", en:"IR Planet Imager"}, description : {fr:"Il produit des cartes de température ou des cartes associées à la signature de certaines molécules. Il est utilisé en vol (pour des scans ou avec un pointage précis) ou après atterrissage.", en:"It produces temperature maps or maps associated with the signing of certain molecules . It is used in flight (for scans or with a precise pointing ) or after landing."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["instrument", "instrumentPlanete"], categorie: "I", valEur : 5000000, valNrg : 20, valPds : 10000, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 15 }, { _id: "Yt4Y5AwiPo2wyxfJJ", carteId: "I14", intitule : {fr:"Spectro planétaire haute énergie", en:"Spectro planetary high energy"}, description : {fr:"Ce spectromètre permet de caractériser la surface planétaire (ou lunaire) depuis l'orbite en y détectant la signature de certains atomes (ex. H, partie de l'eau, Fe, K,...). Il est utilisé pour des scans ou avec un pointage précis.", en:"This spectrometer used to characterize the planetary surface ( or lunar ) y detecting the signature of certain atoms (eg . H, part of the water , Fe, K , ...). It is used for scans or with a specific score."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'Z5§' }, tags: ["instrument", "instrumentPlanete"], categorie: "I", valEur : 50000000, valNrg : 30, valPds : 50000, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "NASA", ordre: 16 }, { _id: "R9zRRXpCNP5sLz4K5", carteId: "I15", intitule : {fr:"Altimètre radar", en:"Radar altimeter"}, description : {fr:"Il caractérise la surface planétaire (ou lunaire) depuis l'orbite en mesurant l'altitude du sol dans de grandes zones. La technique radar permet aussi de sonder sous la surface. Il est utilisé pour des scans ou avec un pointage précis.", en:"It characterizes the planetary surface ( or lunar ) measuring the altitude of the ground in large areas . The technique also allows radar probe beneath the surface. It is used for scans or with a specific score."}, tip: {fr:"", en:""}, regles: { necessite:'{"planete.atterrisseur": true }', incompatible:'Z5§' }, tags: ["instrument", "instrumentPlanete"], categorie: "I", valEur : 25000000, valNrg : 30, valPds : 7000, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 17 }, { _id: "nzqtS5CCiw4NGJ6Y3", carteId: "I16", intitule : {fr:"Altimètre laser", en:"Laser altimeter"}, description : {fr:"Il mesure très précisément l'altitude de petites zones du sol planétaire ou lunaire depuis l'orbite mais il doit être utilisé avec un pointage précis.", en:"It precisely measures the altitude of small areas of the planetary or lunar soil but must be used with a specific score."}, tip: {fr:"", en:""}, regles: { necessite:'{"planete.atterrisseur": true } + "attitudeRoues"§', incompatible:'Z5§' }, tags: ["instrument", "instrumentPlanete"], categorie: "I", valEur : 10000000, valNrg : 15, valPds : 6000, valVol : 0, valSci : 2, fiabilite: 1, active : true, cubesat: false, copyright: "MPG/ESA", ordre: 18 }, { _id: "EpzLc7Ph9aYgvfBT3", carteId: "I17", intitule : {fr:"Détecteur de particules", en:"Particle detector"}, description : {fr:"Ce capteur mesure la vitesse, la composition et la densité des particules et des poussières environnant le vaisseau, tant en vol (de préférence pour les vaisseaux stabilisés par rotation) qu'après atterrissage.", en:"This sensor measures the speed , the composition and density of the particles and dust surrounding the vessel , both in the air (preferably for vessels spin stabilized ) after landing."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["instrument", "instrumentPlanete"], categorie: "I", valEur : 10000000, valNrg : 10, valPds : 10000, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 19 }, { _id: "7zjwoHrnippb8sjN3", carteId: "I18", intitule : {fr:"Analyseur de plasma", en:"Plasma Analyser"}, description : {fr:"Ce capteur mesure la vitesse, la composition et la densité du plasma environnant le vaisseau (vent solaire, magnétosphère planétaire). Il fonctionne mieux pour les vaisseaux stabilisés par rotation.", en:"This sensor measures the speed , composition and density of the plasma surrounding the vessel ( solar wind , planetary magnetosphere ) . It works best for vessels stabilized by rotation."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'Z5§' }, tags: ["instrument", "instrumentPlanete"], categorie: "I", valEur : 10000000, valNrg : 10, valPds : 10000, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 20 }, { _id: "WpAHsahE3wLTgT2YC", carteId: "I19", intitule : {fr:"Magnétomètre", en:"Magnetometer"}, description : {fr:"Ce capteur mesure le champ magnétique (inter)planétaire depuis le sol ou l'orbite. Dans ce dernier cas, il fonctionne mieux pour les vaisseaux stabilisés par rotation.", en:"This sensor measures the magnetic field (inter) worldwide . It works best for vessels stabilized by rotation."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'Z5§' }, tags: ["instrument", "instrumentPlanete"], categorie: "I", valEur : 3000000, valNrg : 2, valPds : 3000, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "ESA", ordre: 21 }, { _id: "NTtptTDCikwKjjefi", carteId: "I20", intitule : {fr:"Imageur visible haute résolution", en:"Visible detector high resolution"}, description : {fr:"Combiné à un télescope, il permet de faire des images du ciel très détaillées et ce, dans plusieurs couleurs pour obtenir plus d'informations. Il est utilisé pour des scans ou avec un pointage précis.", en:"Disposed at the outlet of a telescope , it allows to make images of the sky in the range of visible light . It is used for scans or with a specific score."}, tip: {fr:"", en:""}, regles: { necessite:'I1§ / I2§ / I3§', incompatible:'' }, tags: ["instrument", "instrumentScan", "instrumentEspace"], categorie: "I", valEur : 4000000, valNrg : 6, valPds : 7000, valVol : 0, valSci : 2, fiabilite: 1, active : true, cubesat: false, copyright: "HST", ordre: 5 }, { _id: "s5t2WLRcYe6hy82Ez", carteId: "I21", intitule : {fr:"Spectromètre visible haute résolution", en:"Visible spectrometer high resolution"}, description : {fr:"Ce spectromètre travaille à haute résolution, fournissant des informations très précises sur les propriétés des objets célestes. Il nécessite un pointage précis.", en:"Disposed at the outlet of a telescope , it allows to evaluate many properties observed stars (composition, speed , ...) but it requires a precise pointing."}, tip: {fr:"", en:""}, regles: { necessite:'"attitudeRoues"§ + (I1§ / I2§ / I3§)', incompatible:'' }, tags: ["instrument", "instrumentScan", "instrumentEspace"], categorie: "I", valEur : 11000000, valNrg : 20, valPds : 50000, valVol : 0, valSci : 3, fiabilite: 1, active : true, cubesat: false, copyright: "ESO", ordre: 7 }, { _id: "rd5RBMhMadX6d7aBJ", carteId: "J2", intitule : {fr:"Bouclier thermique", en:"Heat shield"}, description : {fr:"Le bouclier thermique protège les atterrisseurs lorsqu'ils traversent une atmosphère.", en:"The heat shield protects the undercarriages during their passage through the atmosphere."}, tip: {fr:"", en:""}, regles: { necessite:'Z5§ + {"planete.atmosphere": true}', incompatible:'' }, tags: ["atterrisseur","atterrisseurBouclier"], categorie: "J", valEur : 50000000, valNrg : 0, valPds : 200000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "NASA", ordre: 1 }, { _id: "2uopeLjqeAjSSf28f", carteId: "J3", intitule : {fr:"Parachute", en:"Parachute"}, description : {fr:"Le parachute permet de ralentir l'atterrisseur. Il ne fonctionne que pour les lunes (ex: Titan) et planètes (ex: Mars, Vénus) possédant une atmosphère.", en:"The parachute slows the lander . It only works for the moons and planets with an atmosphere."}, tip: {fr:"", en:""}, regles: { necessite:'J2§ + Z5§ + {"planete.atmosphere": true}', incompatible:'' }, tags: ["atterrisseur","atterrisseurFrein","atterrisseurParachute"], categorie: "J", valEur : 10000000, valNrg : 0, valPds : 10000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "NASA", ordre: 2 }, { _id: "swHuu9BxkfW55yucr", carteId: "J4", intitule : {fr:"Airbags", en:"Airbags"}, description : {fr:"Ce système ralentit les vaisseaux pas trop lourds pour un atterrissage dans une zone choisie. Il protège le vaisseau en cas de terrain caillouteux.", en:"This system slows down too heavy vessels for landing in a selected area . It protects the ship in case of stony ground."}, tip: {fr:"", en:""}, regles: { necessite:'Z5§', incompatible:'' }, tags: ["atterrisseur","atterrisseurFrein"], categorie: "J", valEur : 40000000, valNrg : 0, valPds : 75000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "NASA", ordre: 3 }, { _id: "Ehc9tGQHFriHFrjBQ", carteId: "J5", intitule : {fr:"Rétrofusées", en:"Retro rockets"}, description : {fr:"Ce système ralentit n'importe quel vaisseau pour un atterrissage contrôlé en un lieu précis. Le site d'atterrissage doit cependant être assez lisse.", en:"This system slows down all the vessels for a controlled landing in a specific place . The landing site should however be fairly smooth."}, tip: {fr:"", en:""}, regles: { necessite:'Z5§', incompatible:'' }, tags: ["atterrisseur","atterrisseurFrein"], categorie: "J", valEur : 50000000, valNrg : 0, valPds : 100000, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: false, copyright: "NASA", ordre: 4 }, { _id: "pZWpTdAAChayp99PL", carteId: "J6", intitule : {fr:"Roues", en:"Wheels"}, description : {fr:"Les roues permettent de déplacer le vaisseau à la surface solide d'une lune ou planète. Elles travaillent en terrain rocailleux.", en:"The wheels can move the ship to the solid surface of a moon or planet. They work in rocky terrain."}, tip: {fr:"", en:""}, regles: { necessite:'Z5§', incompatible:'' }, tags: ["atterrisseur"], categorie: "J", valEur : 50000000, valNrg : 50, valPds : 30000, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "NASA", ordre: 5 }, { _id: "qt7ZeE4y9wNzR7c5H", carteId: "J7", intitule : {fr:"Chenilles", en:"Tracks"}, description : {fr:"Les chenilles permettent de déplacer le vaisseau à la surface solide d'une lune ou planète. Comparées aux roues, leurs manoeuvres sont moins précises et il leur est plus difficile de grimper sur un obstacle.", en:"The caterpillars can move the ship to the solid surface of a moon or planet. Compared to the wheels, their operations are less accurate and they find it more difficult to climb an obstacle."}, tip: {fr:"", en:""}, regles: { necessite:'Z5§', incompatible:'' }, tags: ["atterrisseur"], categorie: "J", valEur : 50000000, valNrg : 40, valPds : 50000, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "NASA", ordre: 6 }, { _id: "LisFt46Sq2DQRGrtk", carteId: "J8", intitule : {fr:"Bras mécanique et pelle de collecte", en:"Mechanical arm and shovel collection"}, description : {fr:"Le bras et la pelle permetent de récolter des échantillons d'air ou de sol autour de l'atterrisseur.", en:"Arm and shovel permetent to collect air samples or soil around the undercarriage."}, tip: {fr:"", en:""}, regles: { necessite:'Z5§', incompatible:'' }, tags: ["atterrisseur","atterrisseurInstrument"], categorie: "J", valEur : 20000000, valNrg : 7, valPds : 20000, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "NASA", ordre: 7 }, { _id: "xgaJa53iR8pvLFfWp", carteId: "J9", intitule : {fr:"Foreuse", en:"Drill"}, description : {fr:"La foreuse permet de forer le sol ou les roches exposées, de manière à collecter des couches plus profondes et les analyser ensuite.", en:"Drill allows to drill soil or rocks exposed , so as to collect and then analyze the deeper layers."}, tip: {fr:"", en:""}, regles: { necessite:'Z5§ + J8§', incompatible:'' }, tags: ["atterrisseur","atterrisseurInstrument"], categorie: "J", valEur : 20000000, valNrg : 50, valPds : 5000, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "NASA", ordre: 8 }, { _id: "aijS5DBTofHEPD2kN", carteId: "J10", intitule : {fr:"Senseur thermique", en:"Thermal sensor"}, description : {fr:"Ce capteur permet de relever la température et l'ensoleillement quand on se trouve à la surface d'une lune ou planète.", en:"Ce capteur permet de relever la température et l'ensoleillement quand on se trouve à la surface d'une lune ou planète."}, tip: {fr:"", en:""}, regles: { necessite:'Z5§', incompatible:'' }, tags: ["atterrisseur","atterrisseurInstrument"], categorie: "J", valEur : 1000000, valNrg : 1, valPds : 1000, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "NASA", ordre: 9 }, { _id: "uF5vu42MGZNwg6YvG", carteId: "J11", intitule : {fr:"Capteur atmosphérique", en:"Atmospheric sensor"}, description : {fr:"Ce capteur mesure la pression atmosphérique, la vitesse des vents et la composition de l'atmosphère. Il ne fonctionne que pour les lunes et les planètes possédant une atmosphère.", en:"This sensor measures the atmospheric pressure , wind speed and atmospheric composition . It only works for the moons and planets with an atmosphere."}, tip: {fr:"", en:""}, regles: { necessite:'Z5§ + {"planete.atmosphere": true}', incompatible:'' }, tags: ["atterrisseur","atterrisseurInstrument"], categorie: "J", valEur : 1000000, valNrg : 1, valPds : 1000, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "NASA", ordre: 10 }, { _id: "Q4GToBrgXwoSfEGK2", carteId: "J12", intitule : {fr:"Microscope", en:"Microscope"}, description : {fr:"Le microscope permet de compléter un imageur simple pour étudier en détail le sol ou des échantillons collectés.", en:"The microscope allows to complete a simple imaging to study in detail the ground or samples collected."}, tip: {fr:"", en:""}, regles: { necessite:'Z5§ + I10§ + J8§', incompatible:'' }, tags: ["atterrisseur","atterrisseurInstrument"], categorie: "J", valEur : 1000000, valNrg : 1, valPds : 1000, valVol : 0, valSci : 1, fiabilite: 1, active : true, cubesat: false, copyright: "NASA", ordre: 11 }, { _id: "W4DMJpbnX3mhDpFoa", carteId: "J13", intitule : {fr:"Laboratoire biologique", en:"Biological laboratory"}, description : {fr:"Ce laboratoire permet de chercher des signes de vie microbienne (passée ou présente) dans les échantillons collectés avec la pelle.", en:"This laboratory allows to look for signs of microbial life ( past or present) in the samples collected with the shovel."}, tip: {fr:"", en:""}, regles: { necessite:'J8§ + Z5§', incompatible:'' }, tags: ["atterrisseur","atterrisseurInstrument"], categorie: "J", valEur : 50000000, valNrg : 15, valPds : 15000, valVol : 0, valSci : 4, fiabilite: 1, active : true, cubesat: false, copyright: "NASA", ordre: 12 }, { _id: "W4DMJpbnX3mhDpFob", carteId: "J14", intitule : {fr:"Dispositif à rebond", en:"Device bounced"}, description : {fr:"Ce module semblable à un trampoline vous permet d'étudier l'atmosphère à différentes hauteurs de manière répétitive. Attention toutefois à son déploiement.", en:"This module like a trampoline allows you to study the atmosphere at different heights repeatedly. But be careful deployment"}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["atterrisseur","absurde"], categorie: "J", valEur : 2000000, valNrg : 0, valPds : 10000, valVol : 0, valSci : 2, fiabilite: 0, active : true, cubesat: false, copyright: "", ordre: 13 }, { _id: "MfyJsijytAvvQxfZi", carteId: "CL1", intitule : {fr:"Lancement 1U", en:"Launching 1U"}, description : {fr:"Lancement d'une unité, comprend l'adaptateur permettant d'éjecter les CubeSats en orbite.", en:"Launch of a unit includes the adapter to eject the CubeSats in orbit."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["lanceur","lanceur1U"], categorie: "L", valEur : 75000, valNrg : 0, valPds : 1300, valVol : 100, valSci : 0, fiabilite: 1, active : true, cubesat: true, copyright: "ESA", ordre: 1 }, { _id: "2TF8g3h2ZML2kS968", carteId: "CL2", intitule : {fr:"Lancement 3U", en:"Launching 3U"}, description : {fr:"Lancement d'un bloc de trois unités, comprend l'adaptateur permettant d'éjecter les CubeSats en orbite.", en:"Launch of three units includes the adapter to eject the CubeSats in orbit."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["lanceur","lanceur3U"], categorie: "L", valEur : 225000, valNrg : 0, valPds : 3900, valVol : 300, valSci : 0, fiabilite: 1, active : true, cubesat: true, copyright: "ESA", ordre: 2 }, { _id: "biuak89xSDZ63ENrR", carteId: "CZ1", intitule : {fr:"Structure 1U", en:"Structure 1U"}, description : {fr:"La structure, ou plateforme, est le squelette du vaisseau. Elle assure sa rigidité et contient tous les connecteurs où fixer les cartes-équipements.", en:"The structure or platform, the vessel is backbone. It provides rigidity and contains all the connectors that attach the card-equipment."}, tip: {fr:"Cette structure doit être utilisée pour un projet 1U.", en:"This structure must be used for a 1U project."}, regles: { necessite:'CL1 +"energieGenerateur"§ +"energieGestion"§ +"commandesProcesseur"§ + "instrument"§ +"attitudeMesure"§ +"communicationsAntenne"§ +"communicationsTelecom"§', incompatible:'CL2' }, tags: ["structure","structure1U"], categorie: "Z", valEur : 2500, valNrg : 0, valPds : 200, valVol : 0, valSci : 0, fiabilite: 1, atterrisseur: false, composants: true, maxPds: 1300, active : true, cubesat: true, copyright: "www.cubesatshop.com", ordre: 1 }, { _id: "KgDdevKLNXETjmKBp", carteId: "CZ2", intitule : {fr:"Structure 3U", en:"Structure 3U"}, description : {fr:"La structure, ou plateforme, est le squelette du vaisseau. Elle assure sa rigidité et contient tous les connecteurs où fixer les cartes-équipements.", en:"The structure or platform, the vessel is backbone. It provides rigidity and contains all the connectors that attach the card-equipment."}, tip: {fr:"Cette structure doit être utilisée pour un projet 3U.", en:"This structure must be used for a 3U project."}, regles: { necessite:'CL2 +"energieGenerateur"§ +"energieGestion"§ +"commandesProcesseur"§ + "instrument"§ +"attitudeMesure"§ +"communicationsAntenne"§ +"communicationsTelecom"§', incompatible:'CL1' }, tags: ["structure","structure3U"], categorie: "Z", valEur : 4000, valNrg : 0, valPds : 600, valVol : 0, valSci : 0, fiabilite: 1, atterrisseur: false, composants: true, maxPds: 3900, active : true, cubesat: true, copyright: "www.cubesatshop.com", ordre: 2 }, { _id: "qN32jNgPbDHXiPyji", carteId: "CC1", intitule : {fr:"Système Télécom Simple", en:"Simple Telecom System"}, description : {fr:"Ce système intégré permet de communiquer avec la Terre. Il contient le récepteur et l'émetteur. Il fonctionne avec des débits de 10kb/s (envoi) et 1kb/s (réception) aux fréquences VHF/UHF (~150MHz).", en:"This integrated system enables communication with Earth. It contains the receiver and the transmitter. It works with bit rates of 10kb / s (send) and 1 kb / s ( reception) VHF / UHF frequency (~ 150MHz )."}, tip: {fr:"", en:""}, regles: { necessite:'CC3 / CC4', incompatible:'' }, tags: ["communications","communicationsTelecom"], categorie: "C", valEur : 7000, valNrg : 1.5, valPds : 85, valVol : 15, valSci : 0, fiabilite: 1, active : true, cubesat: true, copyright: "www.cubesatshop.com", ordre: 1 }, { _id: "PuqwGJfLomrBPFGER", carteId: "CC2", intitule : {fr:"Système Télécom Rapide", en:"Rapid Telecom System"}, description : {fr:"Ce système intégré permet d'envoyer rapidement (100kb/s) un volume important de données, grâce à l'utilisation d'une fréquence différente (bande S, ~2GHz). Il ne contient pas de récepteur, uniquement un émetteur.", en:"This integrated system allows to send quickly ( 100kb / s) a large volume of data through the use of a different frequency (S band, ~ 2GHz ) . It does not contain a receiver , only a transmitter."}, tip: {fr:"", en:""}, regles: { necessite:'CC3 / CC4', incompatible:'' }, tags: ["communications","communicationsTelecom"], categorie: "C", valEur : 8500, valNrg : 3, valPds : 65, valVol : 25, valSci : 1, fiabilite: 1, active : true, cubesat: true, copyright: "www.cubesatshop.com", ordre: 2 }, { _id: "mJdBZQfEd8NTifmoL", carteId: "CC3", intitule : {fr:"Antenne #1", en:"Antenna #1"}, description : {fr:"Cette antenne se place sur un côté du CubeSat et est déployée après le lancement.", en:"This antenna is located on one side of CubeSat and is deployed after launch."}, tip: {fr:"", en:""}, regles: { necessite:'CC1 / CC2', incompatible:'' }, tags: ["communications","communicationsAntenne"], categorie: "C", valEur : 4000, valNrg : 0, valPds : 100, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: true, copyright: "www.cubesatshop.com", ordre: 3 }, { _id: "42iHfh8uHpWJchCQn", carteId: "CC4", intitule : {fr:"Antenne #2", en:"Antenna #2"}, description : {fr:"Cette antenne se place sur un côté du CubeSat. Elle ne fonctionne que pour certaines fréquences (Bande S) et nécessite un système Télécom rapide.", en:"This antenna is located on one side of CubeSat . It only works for certain frequencies ( Band S)."}, tip: {fr:"", en:""}, regles: { necessite:'CC2', incompatible:'' }, tags: ["communications","communicationsAntenne"], categorie: "C", valEur : 5000, valNrg : 0, valPds : 80, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: true, copyright: "spacedev.com", ordre: 4 }, { _id: "LSwd5uL3rMtxkCiuy", carteId: "CE1", intitule : {fr:"Gestion de l'énergie", en:"Energy management"}, description : {fr:"Ce système électronique gère la fourniture d'énergie.", en:"This electronic system manages the energy supply."}, tip: {fr:"<span class='mandatory'>Obligatoire</span>", en:"<span class='mandatory'>Mandatory</span>"}, regles: { necessite:'', incompatible:'' }, tags: ["energie","energieGestion"], categorie: "E", valEur : 3000, valNrg : 0, valPds : 90, valVol : 15, valSci : 0, fiabilite: 1, active : true, cubesat: true, copyright: "www.cubesatshop.com", ordre: 1 }, { _id: "5nP62vR7HkRne4iHj", carteId: "CE2", intitule : {fr:"Panneau solaire 1U", en:"Solar panel 1U"}, description : {fr:"Les panneaux solaires se fixent sur 5 côtés des unités (la 6éme face étant utilisée pour l'antenne). Quand le CubeSat 1U est éclairé, l'ensemble de ces panneaux fournit 3W.", en:"Solar panels are fixed on 5 sides of the units ( the 6th face being used for the antenna) . When the CubeSat is illuminated , the set of these panels provides 3W."}, tip: {fr:"<span class='mandatory'>Obligatoire pour 1U</span>", en:"<span class='mandatory'>Mandatory for 1U</span>"}, regles: { necessite:'', incompatible:'' }, tags: ["energie","energie1U","energieGenerateur"], categorie: "E", valEur : 10000, valNrg : 3, valPds : 300, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: true, copyright: "Oufti I - ULg", ordre: 2 }, { _id: "eEZdewaYekNi6H5WB", carteId: "CE3", intitule : {fr:"Panneau solaire 3U", en:"Solar panel 3U"}, description : {fr:"Les panneaux solaires se fixent sur 4 long côtés du CubeSat 3U. Quand ils sont éclairés, l'ensemble de ces panneaux fournit 6W.", en:"Solar panels are fixed on four long sides of the CubeSat . When the latter is illuminated , the set of these panels provides 6W."}, tip: {fr:"<span class='mandatory'>Obligatoire pour 3U</span>", en:"<span class='mandatory'>Mandatory for 3U</span>"}, regles: { necessite:'', incompatible:'' }, tags: ["energie","energie3U","energieGenerateur"], categorie: "E", valEur : 20000, valNrg : 6, valPds : 700, valVol : 0, valSci : 0, fiabilite: 1, active : true, cubesat: true, copyright: "www.cubesatshop.com", ordre: 3 }, { _id: "C5fD6zmdRT9AxhXB6", carteId: "CE4", intitule : {fr:"Batterie", en:"Battery"}, description : {fr:"Cette batterie 10W permet au CubeSat de fonctionner même s'il n'est pas éclairé. Ce système n'est pas obligatoire (on peut éteindre le satellite durant chaque éclipse) mais il est fortement recommandé.", en:"This 10W battery allows the CubeSat to operate even if it is not informed . This system is not compulsory (the satellite can be put out during each eclipse ) but is highly recommended."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["energie"], categorie: "E", valEur : 700, valNrg : 0, valPds : 100, valVol : 7, valSci : 1, fiabilite: 1, active : true, cubesat: true, copyright: "www.cubesatshop.com", ordre: 4 }, { _id: "NuL9rkXbTPyyTjt2W", carteId: "CA1", intitule : {fr:"Détecteur de limbe terrestre", en:"Earth limb detector"}, description : {fr:"Ce capteur estime approximativement (à 0.5° près) l'attitude du CubeSat en mesurant la direction du limbe terrestre.", en:"This sensor is estimated approximately (0.5 ° near ) CubeSat attitude by measuring the direction of the Earth's limb."}, tip: {fr:"Au moins un système de mesure d'attitude est obligatoire.", en:"At least one attitude measurement system is required."}, regles: { necessite:'', incompatible:'' }, tags: ["attitude","attitudeMesure"], categorie: "A", valEur : 10000, valNrg : 0.4, valPds : 100, valVol : 1, valSci : 0, fiabilite: 1, active : true, cubesat: true, copyright: "www.cubesatshop.com", ordre: 1 }, { _id: "qAgeYWkkz5KJmAfkG", carteId: "CA2", intitule : {fr:"Senseur solaire", en:"Solar sensor"}, description : {fr:"Le senseur solaire estime approximativement l'attitude du CubeSat en utilisant la direction du Soleil. Leur précision est faible, mais ils s'avèrent très utiles en cas de perte de stabilité du vaisseau.", en:"The solar sensor feels about the attitude of the CubeSat using the direction of the sun."}, tip: {fr:"Au moins un système de mesure d'attitude est obligatoire.", en:"At least one attitude measurement system is required."}, regles: { necessite:'', incompatible:'' }, tags: ["attitude","attitudeMesure"], categorie: "A", valEur : 10000, valNrg : 0.2, valPds : 40, valVol : 2, valSci : 0, fiabilite: 1, active : true, cubesat: true, copyright: "www.cubesatshop.com", ordre: 2 }, { _id: "62euak4E9Zik3ufyA", carteId: "CA3", intitule : {fr:"Récepteur GPS", en:"GPS receiver"}, description : {fr:"Ce capteur utilise la constellation GPS pour déterminer la position du CubeSat.", en:"This sensor uses the GPS constellation for determining the position of CubeSat."}, tip: {fr:"Au moins un système de mesure d'attitude est obligatoire.", en:"At least one attitude measurement system is required."}, regles: { necessite:'', incompatible:'' }, tags: ["attitude","attitudeMesure"], categorie: "A", valEur : 12000, valNrg : 1, valPds : 30, valVol : 1, valSci : 0, fiabilite: 1, active : true, cubesat: true, copyright: "www.cubesatshop.com", ordre: 3 }, { _id: "hj4okxKegqoCCdfm8", carteId: "CA4", intitule : {fr:"µPropulsion", en:"Propulsion µ"}, description : {fr:"Ces mini-fusées situées aux coins du CubeSat permettent une stabilisation 3 axes et un pointage précis vers n'importe quelle direction.", en:"These mini- rockets at the corners of the CubeSat enable 3-axis stabilization and precise pointing towards any direction."}, tip: {fr:"", en:""}, regles: { necessite:'CA1/CA2/CA3', incompatible:'' }, tags: ["attitude","attitudeControle"], categorie: "A", valEur : 80000, valNrg : 1.5, valPds : 300, valVol : 20, valSci : 1, fiabilite: 1, active : true, cubesat: true, copyright: "www.cubesatshop.com", ordre: 4 }, { _id: "6bkwwfssiQjLJqjHW", carteId: "CA5", intitule : {fr:"Roues à réaction", en:"Reaction wheels"}, description : {fr:"Les roues à réaction permettent une stabilisation 3 axes et un pointage vers n'importe quelle direction.", en:"The reaction wheels allow a 3-axis stabilization and pointing towards any direction."}, tip: {fr:"", en:""}, regles: { necessite:'CA1/CA2/CA3', incompatible:'' }, tags: ["attitude","attitudeControle"], categorie: "A", valEur : 15000, valNrg : 2.5, valPds : 700, valVol : 70, valSci : 1, fiabilite: 1, active : true, cubesat: true, copyright: "www.cubesatshop.com", ordre: 5 }, { carteId: "CA6", intitule : {fr:"Stabilisateur magnétique", en:"Magnetic stabilizer"}, description : {fr:"Ce système collé sur les arêtes est composé d'un aimant et de quatre barreaux métalliques. il aligne grossièrement le CubeSat sur le champ magnétique de la Terre.", en:"This system stuck on the edges is composed of a magnet and of four metal bars . CubeSat it roughly aligns with the magnetic field of the Earth."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["attitude","attitudeMesure","attitudeControle"], categorie: "A", valEur : 350, valNrg : 0, valPds : 5, valVol : 1, valSci : 0, fiabilite: 1, active : true, cubesat: true, copyright: "Oufti I - ULg", ordre: 6 }, { _id: "bAsqo6d9cEnCAgFuF", carteId: "CM1", intitule : {fr:"µProcesseur", en:"µProcessor"}, description : {fr:"Cerveau du vaisseau, il commande tous les sytèmes grâce aux ordres reçus de la Terre et il prépare l'envoi des données. Il travaille avec une mémoire vive de 4Mb et une vitesse maximale de 50MHz.", en:"Brain vessel, it controls all Shopsystems through orders received from Earth and is preparing to send data . He works with 4Mb of RAM and a maximum speed of 50MHz."}, tip: {fr:"<span class='mandatory'>Obligatoire</span>", en:"<span class='mandatory'>Mandatory</span>"}, regles: { necessite:'', incompatible:'' }, tags: ["commandes","commandesProcesseur"], categorie: "M", valEur : 1500, valNrg : 0.3, valPds : 40, valVol : 7, valSci : 0, fiabilite: 1, active : true, cubesat: true, copyright: "www.cubesatshop.com", ordre: 1 }, { _id: "LuodyNxkJ55R78bey", carteId: "CM2", intitule : {fr:"Carte mémoire", en:"Memory Card"}, description : {fr:"Le CubeSat ne pouvant communiquer continuellement avec la Terre, ce système stocke 2Gb de données collectées jusqu'à ce qu'elles puissent être envoyées.", en:"The CubeSat that can continuously communicate with Earth, this system stores 2Gb of data collected until they can be sent."}, tip: {fr:"<span class='mandatory'>Obligatoire</span>", en:"<span class='mandatory'>Mandatory</span>"}, regles: { necessite:'', incompatible:'' }, tags: ["commandes","commandesMemoire"], categorie: "M", valEur : 1500, valNrg : 0.1, valPds : 20, valVol : 5, valSci : 1, fiabilite: 1, active : true, cubesat: true, copyright: "www.cubesatshop.com", ordre: 2 }, { _id: "o7u6orrgeScgnBzmZ", carteId: "CI1", intitule : {fr:"Démonstration technologique", en:"Technology demonstration"}, description : {fr:"Ce système permet de tester le comportement de nouvelles technologies spatiales (composants électroniques, propulsion, ...) en situation réelle.", en:"This system can test the behavior of new space technologies ( electronics , propulsion, ... ) in real situations."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["instrument"], categorie: "I", valEur : 5000, valNrg : 0.5, valPds : 100, valVol : 10, valSci : 1, fiabilite: 1, active : true, cubesat: true, copyright: "ESA", ordre: 1 }, { _id: "ruQPNwrjjxiPxpgoh", carteId: "CI2", intitule : {fr:"Essai biologique", en:"Biological test"}, description : {fr:"Cette expérience permet d'étudier le comportement de petits êtres vivants (microbes, algues) dans l'environnement spatial.", en:"This experiment allows us to study the comportement small living things ( microbes, algae) in the space environment."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["instrument"], categorie: "I", valEur : 30000, valNrg : 0.8, valPds : 250, valVol : 40, valSci : 1, fiabilite: 1, active : true, cubesat: true, copyright: "wikipedia", ordre: 2 }, { _id: "DCrfATacsc95G7YdC", carteId: "CI3", intitule : {fr:"Imageur", en:"imager"}, description : {fr:"Cet imageur fournit des images de petite taille (3Mpx), donc peu détaillées, dans des filtres visibles (ou proches du visible), mais il observe une zone très étendue (9°, soit la taille d'un poing tenu à bout de bras).", en:"This imager provides small images ( 3mpx ), so little detail in the visible filters ( or close to the visible) , but observe a wide area (9 ° , the size of a fist held at arm's length )."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["instrument"], categorie: "I", valEur : 10000, valNrg : 0.6, valPds : 100, valVol : 40, valSci : 1, fiabilite: 1, active : true, cubesat: true, copyright: "www.cubesatshop.com", ordre: 3 }, { _id: "EwTtqLdhXbnYQfDnq", carteId: "CI4", intitule : {fr:"Spectro IR", en:"Spectro IR"}, description : {fr:"Ce spectromètre permet d'étudier la composition moléculaire des terrains observés. Il observe dans la gamme 1-1.7 µm avec une résolution faible (6nm).", en:"This spectrometer allows to study the molecular composition of the observed fields. He observes in the range 1-1.7 microns with a low resolution ( 6 nm )."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["instrument"], categorie: "I", valEur : 20000, valNrg : 1.4, valPds : 200, valVol : 40, valSci : 1, fiabilite: 1, active : true, cubesat: true, copyright: "www.cubesatshop.com", ordre: 4 }, { _id: "sKAmKu7Lrosa6MSfs", carteId: "CI5", intitule : {fr:"Magnétomètre", en:"Magnetometer"}, description : {fr:"Ce capteur mesure le champ magnétique terrestre dix fois par seconde au plus, avec une précision de 10nT (50000 fois plus faible que l'intensité du champ terrestre mesuré au sol).", en:"This sensor measures the earth's magnetic field ten times per second at most, with an accuracy of 10nT (50000 times lower than the intensity of the earth's field measured on the ground )."}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["instrument"], categorie: "I", valEur : 10000, valNrg : 0.4, valPds : 150, valVol : 10, valSci : 1, fiabilite: 1, active : true, cubesat: true, copyright: "www.cubesatshop.com", ordre: 5 }, { _id: "b8y8BXCJ2LLcHy8vc", carteId: "CI6", intitule : {fr:"Instrument original", en:"Original instrument"}, description : {fr:"Imaginez votre propre expérience!", en:"Imagine your own experience !"}, tip: {fr:"", en:""}, regles: { necessite:'', incompatible:'' }, tags: ["instrument"], categorie: "I", valEur : 15000, valNrg : 1, valPds : 150, valVol : 30, valSci : 1, fiabilite: 1, active : true, cubesat: true, copyright: "", ordre: 6 } ];
angular.module('hello-oauth-angular-example-app').controller('LoginController', function ($q, helloOauth) { 'use strict'; var vm = this; vm.loginResponses = {}; vm.logoutResponses = {}; vm.services = ['facebook', 'google']; vm.loginWithService = function loginWithService(service) { return helloOauth(service).login().then(function (response) { vm.loginResponses[service] = response; vm.logoutResponses[service] = null; return response; }); }; vm.logoutWithService = function logoutWithService(service) { return helloOauth(service).logout().then(function (response) { vm.logoutResponses[service] = response; vm.loginResponses[service] = null; return response; }); }; });
import Controller from '@ember/controller'; import { text } from '../utils/samples'; export default class TestController extends Controller { text = text; }
/*! * d3pie * @author Ben Keen * @version 0.1.9 * @date June 17th, 2015 * @repo http://github.com/benkeen/d3pie */ // UMD pattern from https://github.com/umdjs/umd/blob/master/returnExports.js (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module define([], factory); } else if (typeof exports === 'object') { // Node. Does not work with strict CommonJS, but only CommonJS-like environments that support module.exports, // like Node module.exports = factory(); } else { // browser globals (root is window) root.d3pie = factory(root); } }(this, function() { var _scriptName = "d3pie"; var _version = "0.1.6"; // used to uniquely generate IDs and classes, ensuring no conflict between multiple pies on the same page var _uniqueIDCounter = 0; // this section includes all helper libs on the d3pie object. They're populated via grunt-template. Note: to keep // the syntax highlighting from getting all messed up, I commented out each line. That REQUIRES each of the files // to have an empty first line. Crumby, yes, but acceptable. //<%=_defaultSettings%> //<%=_validate%> //<%=_helpers%> //<%=_math%> //<%=_labels%> //<%=_segments%> //<%=_text%> //<%=_tooltips%> // -------------------------------------------------------------------------------------------- // our constructor var d3pie = function(element, options) { // element can be an ID or DOM element this.element = element; if (typeof element === "string") { var el = element.replace(/^#/, ""); // replace any jQuery-like ID hash char this.element = document.getElementById(el); } var opts = {}; extend(true, opts, defaultSettings, options); this.options = opts; // if the user specified a custom CSS element prefix (ID, class), use it if (this.options.misc.cssPrefix !== null) { this.cssPrefix = this.options.misc.cssPrefix; } else { this.cssPrefix = "p" + _uniqueIDCounter + "_"; _uniqueIDCounter++; } // now run some validation on the user-defined info if (!validate.initialCheck(this)) { return; } // add a data-role to the DOM node to let anyone know that it contains a d3pie instance, and the d3pie version d3.select(this.element).attr(_scriptName, _version); // things that are done once this.options.data.content = math.sortPieData(this); if (this.options.data.smallSegmentGrouping.enabled) { this.options.data.content = helpers.applySmallSegmentGrouping(this.options.data.content, this.options.data.smallSegmentGrouping); } this.options.colors = helpers.initSegmentColors(this); this.totalSize = math.getTotalPieSize(this.options.data.content); _init.call(this); }; d3pie.prototype.recreate = function() { // now run some validation on the user-defined info if (!validate.initialCheck(this)) { return; } this.options.data.content = math.sortPieData(this); if (this.options.data.smallSegmentGrouping.enabled) { this.options.data.content = helpers.applySmallSegmentGrouping(this.options.data.content, this.options.data.smallSegmentGrouping); } this.options.colors = helpers.initSegmentColors(this); this.totalSize = math.getTotalPieSize(this.options.data.content); _init.call(this); }; d3pie.prototype.redraw = function() { this.element.innerHTML = ""; _init.call(this); }; d3pie.prototype.destroy = function() { this.element.innerHTML = ""; // clear out the SVG d3.select(this.element).attr(_scriptName, null); // remove the data attr }; /** * Returns all pertinent info about the current open info. Returns null if nothing's open, or if one is, an object of * the following form: * { * element: DOM NODE, * index: N, * data: {} * } */ d3pie.prototype.getOpenSegment = function() { var segment = this.currentlyOpenSegment; if (segment !== null && typeof segment !== "undefined") { var index = parseInt(d3.select(segment).attr("data-index"), 10); return { element: segment, index: index, data: this.options.data.content[index] }; } else { return null; } }; d3pie.prototype.openSegment = function(index) { index = parseInt(index, 10); if (index < 0 || index > this.options.data.content.length-1) { return; } segments.openSegment(this, d3.select("#" + this.cssPrefix + "segment" + index).node()); }; d3pie.prototype.closeSegment = function() { var segment = this.currentlyOpenSegment; if (segment) { segments.closeSegment(this, segment); } }; // this let's the user dynamically update aspects of the pie chart without causing a complete redraw. It // intelligently re-renders only the part of the pie that the user specifies. Some things cause a repaint, others // just redraw the single element d3pie.prototype.updateProp = function(propKey, value) { switch (propKey) { case "header.title.text": var oldVal = helpers.processObj(this.options, propKey); helpers.processObj(this.options, propKey, value); d3.select("#" + this.cssPrefix + "title").html(value); if ((oldVal === "" && value !== "") || (oldVal !== "" && value === "")) { this.redraw(); } break; case "header.subtitle.text": var oldValue = helpers.processObj(this.options, propKey); helpers.processObj(this.options, propKey, value); d3.select("#" + this.cssPrefix + "subtitle").html(value); if ((oldValue === "" && value !== "") || (oldValue !== "" && value === "")) { this.redraw(); } break; case "callbacks.onload": case "callbacks.onMouseoverSegment": case "callbacks.onMouseoutSegment": case "callbacks.onClickSegment": case "effects.pullOutSegmentOnClick.effect": case "effects.pullOutSegmentOnClick.speed": case "effects.pullOutSegmentOnClick.size": case "effects.highlightSegmentOnMouseover": case "effects.highlightLuminosity": helpers.processObj(this.options, propKey, value); break; // everything else, attempt to update it & do a repaint default: helpers.processObj(this.options, propKey, value); this.destroy(); this.recreate(); break; } }; // ------------------------------------------------------------------------------------------------ var _init = function() { // prep-work this.svg = helpers.addSVGSpace(this); // store info about the main text components as part of the d3pie object instance this.textComponents = { headerHeight: 0, title: { exists: this.options.header.title.text !== "", h: 0, w: 0 }, subtitle: { exists: this.options.header.subtitle.text !== "", h: 0, w: 0 }, footer: { exists: this.options.footer.text !== "", h: 0, w: 0 } }; this.outerLabelGroupData = []; // add the key text components offscreen (title, subtitle, footer). We need to know their widths/heights for later computation if (this.textComponents.title.exists) { text.addTitle(this); } if (this.textComponents.subtitle.exists) { text.addSubtitle(this); } text.addFooter(this); // the footer never moves. Put it in place now var self = this; helpers.whenIdExists(this.cssPrefix + "footer", function() { text.positionFooter(self); var d3 = helpers.getDimensions(self.cssPrefix + "footer"); self.textComponents.footer.h = d3.h; self.textComponents.footer.w = d3.w; }); // now create the pie chart and position everything accordingly var reqEls = []; if (this.textComponents.title.exists) { reqEls.push(this.cssPrefix + "title"); } if (this.textComponents.subtitle.exists) { reqEls.push(this.cssPrefix + "subtitle"); } if (this.textComponents.footer.exists) { reqEls.push(this.cssPrefix + "footer"); } helpers.whenElementsExist(reqEls, function() { if (self.textComponents.title.exists) { var d1 = helpers.getDimensions(self.cssPrefix + "title"); self.textComponents.title.h = d1.h; self.textComponents.title.w = d1.w; } if (self.textComponents.subtitle.exists) { var d2 = helpers.getDimensions(self.cssPrefix + "subtitle"); self.textComponents.subtitle.h = d2.h; self.textComponents.subtitle.w = d2.w; } // now compute the full header height if (self.textComponents.title.exists || self.textComponents.subtitle.exists) { var headerHeight = 0; if (self.textComponents.title.exists) { headerHeight += self.textComponents.title.h; if (self.textComponents.subtitle.exists) { headerHeight += self.options.header.titleSubtitlePadding; } } if (self.textComponents.subtitle.exists) { headerHeight += self.textComponents.subtitle.h; } self.textComponents.headerHeight = headerHeight; } // at this point, all main text component dimensions have been calculated math.computePieRadius(self); // this value is used all over the place for placing things and calculating locations. We figure it out ONCE // and store it as part of the object math.calculatePieCenter(self); // position the title and subtitle text.positionTitle(self); text.positionSubtitle(self); // now create the pie chart segments, and gradients if the user desired if (self.options.misc.gradient.enabled) { segments.addGradients(self); } segments.create(self); // also creates this.arc labels.add(self, "inner", self.options.labels.inner.format); labels.add(self, "outer", self.options.labels.outer.format); // position the label elements relatively within their individual group (label, percentage, value) labels.positionLabelElements(self, "inner", self.options.labels.inner.format); labels.positionLabelElements(self, "outer", self.options.labels.outer.format); labels.computeOuterLabelCoords(self); // this is (and should be) dumb. It just places the outer groups at their calculated, collision-free positions labels.positionLabelGroups(self, "outer"); // we use the label line positions for many other calculations, so ALWAYS compute them labels.computeLabelLinePositions(self); // only add them if they're actually enabled if (self.options.labels.lines.enabled && self.options.labels.outer.format !== "none") { labels.addLabelLines(self); } labels.positionLabelGroups(self, "inner"); labels.fadeInLabelsAndLines(self); // add and position the tooltips if (self.options.tooltips.enabled) { tt.addTooltips(self); } segments.addSegmentEventHandlers(self); }); }; return d3pie; }));
angular.module('quiz', [ 'templates-app', 'templates-common', 'quiz.home', 'quiz.quiz', 'quiz.login', 'quiz.info', 'ui.router' ]).config([ '$stateProvider', '$urlRouterProvider', '$locationProvider', function myAppConfig($stateProvider, $urlRouterProvider, $locationProvider) { $urlRouterProvider.otherwise('/'); } ]).run(function run() { }).controller('AppCtrl', [ '$scope', '$location', function AppCtrl($scope, $location) { $scope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) { if (angular.isDefined(toState.data.pageTitle)) { $scope.pageTitle = toState.data.pageTitle + ' | Auth0 Quiz'; } $scope.bodyClass = toState.data.bodyClass || ''; }); } ]); ;
var PORT = process.env.PORT || 8080, http = require("http"), https = require("https"), express = require('express'), app = express(), server = http.createServer(app), WebSocketServer = require('ws').Server, wss = new WebSocketServer({ server: server }); // Serve static HTML and JS files from the "public" dir. app.use(express.static('public')); // The stocks to follow are in an array. var stocksArray = [ {name: 'AAPL', data: []}, {name: 'QQQ', data: []}, {name: 'MSFT', data: []} ]; var getStockHistory = function(stock, callback) { var date = new Date(); var lastYear = (date.getFullYear() - 1).toString(); var thisYear = date.getFullYear().toString(); var month = ('0' + (date.getMonth() + 1).toString()).slice(-2); var day = ('0' + date.getDate().toString()).slice(-2); var options = { host: 'query.yahooapis.com', path: '/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20%3D%20%22' + stock + '%22%20and%20startDate%20%3D%20%22' + lastYear + '-' + month + '-' + day + '%22%20and%20endDate%20%3D%20%22' + thisYear + '-' + month + '-' + day + '%22&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys' }; https.get(options, function(res) { var body = ''; res.on('data', function(chunk) { body += chunk; }).on('end', function() { var sendArray; var data = JSON.parse(body); if (data.query.results) { sendArray = []; data.query.results.quote.forEach(function(each) { sendArray.unshift([new Date(each.Date).getTime(), parseFloat(each.Close)]); }); } else { sendArray = false; } callback(sendArray); }); }); }; var refreshStockInfo = function(callback) { var newStocksArray = []; var count = 0; stocksArray.forEach(function(element, index, array) { getStockHistory(element.name, function(stockHistoryArray) { if (stockHistoryArray) { newStocksArray.push({name: element.name, data: stockHistoryArray}); } count++; if (count == array.length) { stocksArray = newStocksArray.slice(0); callback(); } }); }); } wss.on('connection', function connection(ws) { ws.on('message', function incoming(message) { var data = JSON.parse(message); var index = -1; stocksArray.forEach(function(element, localIndex, array) { if (element.name == data.stock) { index = localIndex; } }); if (data.add) { if (index == -1) { getStockHistory(data.stock, function(stockHistoryArray) { if (stockHistoryArray) { stocksArray.push({name: data.stock, data: stockHistoryArray}); wss.broadcast(); } else { sendError('Stock ' + data.stock + ' not found'); } }); } else { sendError('Stock ' + data.stock + ' is already being watched'); } } if (data.remove) { if (index != -1) { stocksArray.splice(index, 1); } wss.broadcast(); } if (data.refresh) { refreshStockInfo(function() { wss.broadcast(); }); } }); wss.broadcast = function broadcast() { wss.clients.forEach(function each(client) { client.send(JSON.stringify({ error: false, stocks: stocksArray })); }); }; var sendError = function(err) { ws.send(JSON.stringify({ error: true, message: err })); }; wss.broadcast(); }); // Get stock history data and, when done, start listening to connections refreshStockInfo(function() { server.listen(PORT, function() { console.log('Listening on ' + server.address().port) }); });
/* global API_HOST */ import fetch from 'isomorphic-fetch'; import { player } from 'reducers'; const url = '/api/players'; const REQUEST = 'player/REQUEST'; const OK = 'player/OK'; const ERROR = 'player/ERROR'; export const playerActions = { REQUEST, OK, ERROR, }; const getPlayerRequest = id => ({ type: REQUEST, id }); const getPlayerOk = (payload, id) => ({ type: OK, payload, id, }); const getPlayerError = (payload, id) => ({ type: ERROR, payload, id, }); export const getPlayer = accountId => (dispatch, getState) => { // we are checking to see if the player object exists here. if (player.isLoaded(getState(), accountId)) { dispatch(getPlayerOk(player.getPlayer(getState(), accountId), accountId)); } else { dispatch(getPlayerRequest(accountId)); } return fetch(`${API_HOST}${url}/${accountId}`) .then(response => response.json(accountId)) .then((json) => { dispatch(getPlayerOk(json, accountId)); }) .catch((error) => { dispatch(getPlayerError(error, accountId)); }); };
/** * Created by viatsyshyn on 24.10.13. */ NAMESPACE('ria.dom', function () { "use strict"; function def(data, def) { return ria.__API.merge(data || {}, def); } var window = _GLOBAL; var Node = _BROWSER ? _GLOBAL.Node : Object; /** @class ria.dom.Events */ CLASS( FINAL, 'Events', [ READONLY, String, 'clazz', READONLY, String, 'type', READONLY, Object, 'data', [[String, String, Object]], function $(clazz, type, data_) { BASE(); this.clazz = clazz; this.type = type; this.data = def(data_, {}); }, [[Node]], function triggerOn(node) { try { if (document.createEvent) { try { var event = new (window[this.clazz])(this.type, this.data); } catch (e) { // this is ms ie 10+ way event = document.createEvent(this.clazz); event.initEvent(this.type, !!this.data.bubbles, !!this.data.cancelable); } node.dispatchEvent(event); } else { // this is IE9- way var evt = document.createEventObject(); node.fireEvent("on" + evt.type, evt); } } catch (e) { Assert(true, e.toString()); } }, SELF, function CLICK(data_) { return new SELF('MouseEvent', 'click', def(data_, { 'view': window, 'bubbles': true, 'cancelable': true })) }, SELF, function FOCUS(data_) { return new SELF('FocusEvent', 'focus', def(data_, { 'view': window, 'bubbles': true, 'cancelable': true })); }, SELF, function BLUR(data_) { return new SELF('FocusEvent', 'blur', def(data_, { 'view': window, 'bubbles': true, 'cancelable': true })); }, SELF, function CHANGE(data_) { return new SELF('UIEvent', 'change', def(data_, { 'view': window, 'bubbles': true, 'cancelable': true })); }, SELF, function KEY_UP(data_) { return new SELF('KeyboardEvent', 'keyup', def(data_, { 'view': window, 'bubbles': true, 'cancelable': true })); }, SELF, function KEY_DOWN(data_) { return new SELF('KeyboardEvent', 'keydown', def(data_, { 'view': window, 'bubbles': true, 'cancelable': true })); }, SELF, function SUBMIT(data_) { return new SELF('UIEvent', 'submit', def(data_, { 'view': window, 'bubbles': true, 'cancelable': true })); } ]) });
import * as React from 'react'; function ArrowCircleUpIcon(props) { return ( <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" {...props} > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 11l3-3m0 0l3 3m-3-3v8m0-13a9 9 0 110 18 9 9 0 010-18z" /> </svg> ); } export default ArrowCircleUpIcon;
(function (angular) { "use strict"; angular .module('content.core') .directive('uiSelect', UiSelectDirective) .controller('UiSelectCtrl', UiSelectCtrl); UiSelectDirective.$inject = []; function UiSelectDirective() { return { restrict: 'E', require: 'ngModel', scope: { ngModel: '=ngModel', items: '=items', trackBy: '@trackBy', showBy: '@showBy' }, templateUrl: 'ui-select-directive.html', controller: UiSelectCtrl } } UiSelectCtrl.$inject = [ '$scope', '$element', '$document', '_' ]; function UiSelectCtrl( $scope, $element, $document, _ ) { var isInitDirective = false; $scope.selectedItem = null; $scope.$watch('items', function (items) { if (isInitDirective || !items) { return; } _.forEach(items, function (item) { if (item[$scope.trackBy] == $scope.ngModel) { $scope.selectedItem = item; return; } }); isInitDirective = true; }); $scope.$watch('ngModel', function (newVal) { _.forEach($scope.items, function (item) { if (item[$scope.trackBy] == newVal) { $scope.selectedItem = item; return; } }); }); $scope.selectItem = function (item) { $scope.ngModel = item[$scope.trackBy]; $scope.selectedItem = item; }; function clickToUiSelect (e) { if (!$element.has(e.target).length) { $scope.toggleUiSelectOptions = false; $scope.$apply(); } } $document.on('click', clickToUiSelect); $scope.$on('$destroy', function () { $document.off('click', clickToUiSelect); }); } })(angular);
'use strict'; const { expect } = require('chai'); const { infoReducer } = require('../src/components/info_window/reducers'); describe('interface.components.character_sheet.reducer', function() { describe('.infoReducer', function() { let initial_state; let action; context('on a INFO_WINDOW_ALERT event', function() { beforeEach(function() { initial_state = [{old: 'state'}]; action = { type: 'INFO_WINDOW_ALERT', payload: { id: 'fake id', type: 'FAKE_TYPE', message: 'fake message', category: 'error', }, }; }); it('pushes the message on to the the queue', function() { let new_state = infoReducer(initial_state, action); expect(new_state).to.deep.equal([ { id: 'fake id', type: 'FAKE_TYPE', message: 'fake message', category: 'error', }, { old: 'state', } ]); }); context('when the same message is in the first place of the queue', function() { beforeEach(function() { initial_state = [ { id: 'ID_ONE', message: 'old-fake-message' }, { id: 'ID_TWO', message: 'another-fake-message' }, { id: 'ID_THREE', message: 'yet another message' }, ]; action = { type: 'INFO_WINDOW_ALERT', payload: { id: 'ID_FOUR', message: 'old-fake-message', }, }; }); it('updates that messages id with the new one', function() { let new_state = infoReducer(initial_state, action); expect(new_state).to.deep.equal([ { id: 'ID_FOUR', message: 'old-fake-message' }, { id: 'ID_TWO', message: 'another-fake-message' }, { id: 'ID_THREE', message: 'yet another message' }, ]); }); }); }); context('on an INFO_WINDOW_CLEAR_TYPE action', function() { beforeEach(function() { initial_state = [ { type: 'TYPE_ONE' }, { type: 'TYPE_TWO' }, { type: 'TYPE_ONE' }, { type: 'TYPE_THREE' }, ]; action = { type: 'INFO_WINDOW_CLEAR_TYPE', payload: { type: 'TYPE_ONE', }, }; }); it('removes those types from the queue', function() { let new_state = infoReducer(initial_state, action); expect(new_state).to.deep.equal([ { type: 'TYPE_TWO' }, { type: 'TYPE_THREE' }, ]); }); }); context('on an INFO_WINDOW_CLEAR_ID action', function() { beforeEach(function() { initial_state = [ { id: 'ID_ONE' }, { id: 'ID_TWO' }, { id: 'ID_THREE' }, ]; action = { type: 'INFO_WINDOW_CLEAR_ID', payload: { id: 'ID_ONE', }, }; }); it('removes those types from the queue', function() { let new_state = infoReducer(initial_state, action); expect(new_state).to.deep.equal([ { id: 'ID_TWO' }, { id: 'ID_THREE' }, ]); }); }); }); });
(function ajaxClientInit(module) { 'use strict'; var _ = require('underscore'); module.exports = { init: function ($, undefined) { var isJson = function (text) { return (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, ''))); }; var makeRequest = function (options, cb) { cb = cb || function(err, data){}; request = new XMLHttpRequest; request.open(options.type, options.url, true); request.onreadystatechange = function() { if (this.readyState === 4){ if (this.status >= 200 && this.status < 400){ // Success! resp = this.responseText; if(options.dataType === 'json'){ } } else { // Error :( } } } if(options.data){ request.send(options.data); } else { request.send(); } request = null; $.ajax(_.defaults(options, { headers: {}, dataType: 'json', cache: false, success: function (response) { if (cb && typeof cb === 'function') { cb(null, response); } }, error: function (error) { if (cb && typeof cb === 'function') { cb(error, null); } } })); }; var ajax = { 'get': function (options, cb) { makeRequest({ url: options.url, data: options.data, contentType: options.contentType || 'application/json;charset=utf-8', type: 'get' }, cb); }, 'post': function (options, cb) { makeRequest({ url: options.url, data: options.data, contentType: options.contentType || 'application/x-www-form-urlencoded; charset=UTF-8', type: 'post' }, cb); }, 'delete': function (options, cb) { makeRequest({ url: options.url, data: options.data, contentType: options.contentType || 'application/x-www-form-urlencoded; charset=UTF-8', type: 'delete' }, cb); } }; /* enable support of CORS */ $.support.cors = true; return ajax; } }; })(module);
window.__imported__ = window.__imported__ || {}; window.__imported__["afsafdsasdgc/layers.json.js"] = [ { "maskFrame" : null, "id" : "7373D5FE-CB1D-4B96-B571-CDD2D6F0AD2A", "visible" : true, "children" : [ { "maskFrame" : null, "id" : "F334880F-CA47-4914-8E59-5DD840494EF7", "visible" : true, "children" : [ ], "image" : { "path" : "images\/back-F334880F-CA47-4914-8E59-5DD840494EF7.png", "frame" : { "y" : 44, "x" : -46, "width" : 685, "height" : 993 } }, "imageType" : "png", "layerFrame" : { "y" : 44, "x" : -46, "width" : 685, "height" : 993 }, "name" : "back" }, { "maskFrame" : null, "id" : "9B27C354-0182-47D7-B00B-2DC9262D3C01", "visible" : true, "children" : [ { "maskFrame" : null, "id" : "D75AEA01-D5B3-4616-A9D1-7B448D239997", "visible" : true, "children" : [ ], "image" : { "path" : "images\/greenButton-D75AEA01-D5B3-4616-A9D1-7B448D239997.png", "frame" : { "y" : 829, "x" : 426, "width" : 73, "height" : 73 } }, "imageType" : "png", "layerFrame" : { "y" : 829, "x" : 426, "width" : 73, "height" : 73 }, "name" : "greenButton" }, { "maskFrame" : null, "id" : "89700287-3B27-419B-A054-5E16DEC8C599", "visible" : true, "children" : [ ], "image" : { "path" : "images\/backgroundThree-89700287-3B27-419B-A054-5E16DEC8C599.png", "frame" : { "y" : 140, "x" : 49, "width" : 502, "height" : 810 } }, "imageType" : "png", "layerFrame" : { "y" : 140, "x" : 49, "width" : 502, "height" : 810 }, "name" : "backgroundThree" } ], "image" : { "path" : "images\/cardThree-9B27C354-0182-47D7-B00B-2DC9262D3C01.png", "frame" : { "y" : 140, "x" : 49, "width" : 502, "height" : 812 } }, "imageType" : "png", "layerFrame" : { "y" : 140, "x" : 49, "width" : 502, "height" : 812 }, "name" : "cardThree" }, { "maskFrame" : null, "id" : "0DEE2B72-FECB-4433-8909-AC66A71CEA90", "visible" : true, "children" : [ { "maskFrame" : null, "id" : "6C3156D1-A3ED-4E7C-90C7-EC43828A124A", "visible" : true, "children" : [ ], "image" : { "path" : "images\/blueButton-6C3156D1-A3ED-4E7C-90C7-EC43828A124A.png", "frame" : { "y" : 829, "x" : 426, "width" : 73, "height" : 73 } }, "imageType" : "png", "layerFrame" : { "y" : 829, "x" : 426, "width" : 73, "height" : 73 }, "name" : "blueButton" }, { "maskFrame" : null, "id" : "4F0AE044-7A34-48B7-9592-3EA4DF7A20A7", "visible" : true, "children" : [ ], "image" : { "path" : "images\/backgroundTwo-4F0AE044-7A34-48B7-9592-3EA4DF7A20A7.png", "frame" : { "y" : 140, "x" : 49, "width" : 502, "height" : 810 } }, "imageType" : "png", "layerFrame" : { "y" : 140, "x" : 49, "width" : 502, "height" : 810 }, "name" : "backgroundTwo" } ], "image" : { "path" : "images\/cardTwo-0DEE2B72-FECB-4433-8909-AC66A71CEA90.png", "frame" : { "y" : 140, "x" : 49, "width" : 502, "height" : 810 } }, "imageType" : "png", "layerFrame" : { "y" : 140, "x" : 49, "width" : 502, "height" : 810 }, "name" : "cardTwo" }, { "maskFrame" : null, "id" : "DB696886-046A-4CB0-A34D-76F40159E574", "visible" : true, "children" : [ { "maskFrame" : null, "id" : "7019098B-FB01-4596-B76E-C1299AD780B3", "visible" : true, "children" : [ ], "image" : { "path" : "images\/aquaButton-7019098B-FB01-4596-B76E-C1299AD780B3.png", "frame" : { "y" : 829, "x" : 426, "width" : 73, "height" : 73 } }, "imageType" : "png", "layerFrame" : { "y" : 829, "x" : 426, "width" : 73, "height" : 73 }, "name" : "aquaButton" } ], "image" : { "path" : "images\/cardOne-DB696886-046A-4CB0-A34D-76F40159E574.png", "frame" : { "y" : 140, "x" : 49, "width" : 502, "height" : 810 } }, "imageType" : "png", "layerFrame" : { "y" : 140, "x" : 49, "width" : 502, "height" : 810 }, "name" : "cardOne" }, { "maskFrame" : null, "id" : "3994F428-641F-4147-9007-46F1F63FFA90", "visible" : true, "children" : [ ], "image" : { "path" : "images\/background-3994F428-641F-4147-9007-46F1F63FFA90.png", "frame" : { "y" : 0, "x" : 0, "width" : 640, "height" : 1136 } }, "imageType" : "png", "layerFrame" : { "y" : 0, "x" : 0, "width" : 640, "height" : 1136 }, "name" : "background" } ], "image" : { "path" : "images\/Portrait-7373D5FE-CB1D-4B96-B571-CDD2D6F0AD2A.png", "frame" : { "y" : 0, "x" : 0, "width" : 640, "height" : 1136 } }, "imageType" : "png", "layerFrame" : { "y" : 0, "x" : 0, "width" : 640, "height" : 1136 }, "name" : "Portrait" } ]
/*! * Bootstrap v3.3.7 (http://getbootstrap.com) * Copyright 2011-2016 Twitter, Inc. * Licensed under the MIT license */ if (typeof jQuery === 'undefined') { throw new Error('Bootstrap\'s JavaScript requires jQuery') } +function ($) { 'use strict'; var version = $.fn.jquery.split(' ')[0].split('.'); if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1) || (version[0] > 3)) { throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4') } }(jQuery); /* ======================================================================== * Bootstrap: transition.js v3.3.7 * http://getbootstrap.com/javascript/#transitions * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/) // ============================================================ function transitionEnd() { var el = document.createElement('bootstrap'); var transEndEventNames = { WebkitTransition : 'webkitTransitionEnd', MozTransition : 'transitionend', OTransition : 'oTransitionEnd otransitionend', transition : 'transitionend' }; for (var name in transEndEventNames) { if (el.style[name] !== undefined) { return { end: transEndEventNames[name] } } } return false; // explicit for ie8 ( ._.) } // http://blog.alexmaccaw.com/css-transitions $.fn.emulateTransitionEnd = function (duration) { var called = false; var $el = this; $(this).one('bsTransitionEnd', function () { called = true }); var callback = function () { if (!called) $($el).trigger($.support.transition.end) }; setTimeout(callback, duration); return this }; $(function () { $.support.transition = transitionEnd(); if (!$.support.transition) return; $.event.special.bsTransitionEnd = { bindType: $.support.transition.end, delegateType: $.support.transition.end, handle: function (e) { if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments) } } }) }(jQuery); /* ======================================================================== * Bootstrap: alert.js v3.3.7 * http://getbootstrap.com/javascript/#alerts * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // ALERT CLASS DEFINITION // ====================== var dismiss = '[data-dismiss="alert"]'; var Alert = function (el) { $(el).on('click', dismiss, this.close) }; Alert.VERSION = '3.3.7'; Alert.TRANSITION_DURATION = 150; Alert.prototype.close = function (e) { var $this = $(this); var selector = $this.attr('data-target'); if (!selector) { selector = $this.attr('href'); selector = selector && selector.replace(/.*(?=#[^\s]*$)/, ''); // strip for ie7 } var $parent = $(selector === '#' ? [] : selector); if (e) e.preventDefault(); if (!$parent.length) { $parent = $this.closest('.alert') } $parent.trigger(e = $.Event('close.bs.alert')); if (e.isDefaultPrevented()) return; $parent.removeClass('in'); function removeElement() { // detach from parent, fire event then clean up data $parent.detach().trigger('closed.bs.alert').remove() } $.support.transition && $parent.hasClass('fade') ? $parent .one('bsTransitionEnd', removeElement) .emulateTransitionEnd(Alert.TRANSITION_DURATION) : removeElement() }; // ALERT PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function () { var $this = $(this); var data = $this.data('bs.alert'); if (!data) $this.data('bs.alert', (data = new Alert(this))); if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.alert; $.fn.alert = Plugin; $.fn.alert.Constructor = Alert; // ALERT NO CONFLICT // ================= $.fn.alert.noConflict = function () { $.fn.alert = old; return this }; // ALERT DATA-API // ============== $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close) }(jQuery); /* ======================================================================== * Bootstrap: button.js v3.3.7 * http://getbootstrap.com/javascript/#buttons * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // BUTTON PUBLIC CLASS DEFINITION // ============================== var Button = function (element, options) { this.$element = $(element); this.options = $.extend({}, Button.DEFAULTS, options); this.isLoading = false }; Button.VERSION = '3.3.7'; Button.DEFAULTS = { loadingText: 'loading...' }; Button.prototype.setState = function (state) { var d = 'disabled'; var $el = this.$element; var val = $el.is('input') ? 'val' : 'html'; var data = $el.data(); state += 'Text'; if (data.resetText == null) $el.data('resetText', $el[val]()); // push to event loop to allow forms to submit setTimeout($.proxy(function () { $el[val](data[state] == null ? this.options[state] : data[state]); if (state == 'loadingText') { this.isLoading = true; $el.addClass(d).attr(d, d).prop(d, true) } else if (this.isLoading) { this.isLoading = false; $el.removeClass(d).removeAttr(d).prop(d, false) } }, this), 0) }; Button.prototype.toggle = function () { var changed = true; var $parent = this.$element.closest('[data-toggle="buttons"]'); if ($parent.length) { var $input = this.$element.find('input'); if ($input.prop('type') == 'radio') { if ($input.prop('checked')) changed = false; $parent.find('.active').removeClass('active'); this.$element.addClass('active') } else if ($input.prop('type') == 'checkbox') { if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false; this.$element.toggleClass('active') } $input.prop('checked', this.$element.hasClass('active')); if (changed) $input.trigger('change') } else { this.$element.attr('aria-pressed', !this.$element.hasClass('active')); this.$element.toggleClass('active') } }; // BUTTON PLUGIN DEFINITION // ======================== function Plugin(option) { return this.each(function () { var $this = $(this); var data = $this.data('bs.button'); var options = typeof option == 'object' && option; if (!data) $this.data('bs.button', (data = new Button(this, options))); if (option == 'toggle') data.toggle(); else if (option) data.setState(option) }) } var old = $.fn.button; $.fn.button = Plugin; $.fn.button.Constructor = Button; // BUTTON NO CONFLICT // ================== $.fn.button.noConflict = function () { $.fn.button = old; return this }; // BUTTON DATA-API // =============== $(document) .on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) { var $btn = $(e.target).closest('.btn'); Plugin.call($btn, 'toggle'); if (!($(e.target).is('input[type="radio"], input[type="checkbox"]'))) { // Prevent double click on radios, and the double selections (so cancellation) on checkboxes e.preventDefault(); // The target component still receive the focus if ($btn.is('input,button')) $btn.trigger('focus'); else $btn.find('input:visible,button:visible').first().trigger('focus') } }) .on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) { $(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type)) }) }(jQuery); /* ======================================================================== * Bootstrap: carousel.js v3.3.7 * http://getbootstrap.com/javascript/#carousel * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // CAROUSEL CLASS DEFINITION // ========================= var Carousel = function (element, options) { this.$element = $(element); this.$indicators = this.$element.find('.carousel-indicators'); this.options = options; this.paused = null; this.sliding = null; this.interval = null; this.$active = null; this.$items = null; this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this)); this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element .on('mouseenter.bs.carousel', $.proxy(this.pause, this)) .on('mouseleave.bs.carousel', $.proxy(this.cycle, this)) }; Carousel.VERSION = '3.3.7'; Carousel.TRANSITION_DURATION = 600; Carousel.DEFAULTS = { interval: 5000, pause: 'hover', wrap: true, keyboard: true }; Carousel.prototype.keydown = function (e) { if (/input|textarea/i.test(e.target.tagName)) return; switch (e.which) { case 37: this.prev(); break; case 39: this.next(); break; default: return } e.preventDefault() }; Carousel.prototype.cycle = function (e) { e || (this.paused = false); this.interval && clearInterval(this.interval); this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)); return this }; Carousel.prototype.getItemIndex = function (item) { this.$items = item.parent().children('.item'); return this.$items.index(item || this.$active) }; Carousel.prototype.getItemForDirection = function (direction, active) { var activeIndex = this.getItemIndex(active); var willWrap = (direction == 'prev' && activeIndex === 0) || (direction == 'next' && activeIndex == (this.$items.length - 1)); if (willWrap && !this.options.wrap) return active; var delta = direction == 'prev' ? -1 : 1; var itemIndex = (activeIndex + delta) % this.$items.length; return this.$items.eq(itemIndex) }; Carousel.prototype.to = function (pos) { var that = this; var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active')); if (pos > (this.$items.length - 1) || pos < 0) return; if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }); // yes, "slid" if (activeIndex == pos) return this.pause().cycle(); return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos)) }; Carousel.prototype.pause = function (e) { e || (this.paused = true); if (this.$element.find('.next, .prev').length && $.support.transition) { this.$element.trigger($.support.transition.end); this.cycle(true) } this.interval = clearInterval(this.interval); return this }; Carousel.prototype.next = function () { if (this.sliding) return; return this.slide('next') }; Carousel.prototype.prev = function () { if (this.sliding) return; return this.slide('prev') }; Carousel.prototype.slide = function (type, next) { var $active = this.$element.find('.item.active'); var $next = next || this.getItemForDirection(type, $active); var isCycling = this.interval; var direction = type == 'next' ? 'left' : 'right'; var that = this; if ($next.hasClass('active')) return (this.sliding = false); var relatedTarget = $next[0]; var slideEvent = $.Event('slide.bs.carousel', { relatedTarget: relatedTarget, direction: direction }); this.$element.trigger(slideEvent); if (slideEvent.isDefaultPrevented()) return; this.sliding = true; isCycling && this.pause(); if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active'); var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)]); $nextIndicator && $nextIndicator.addClass('active') } var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }); // yes, "slid" if ($.support.transition && this.$element.hasClass('slide')) { $next.addClass(type); $next[0].offsetWidth; // force reflow $active.addClass(direction); $next.addClass(direction); $active .one('bsTransitionEnd', function () { $next.removeClass([type, direction].join(' ')).addClass('active'); $active.removeClass(['active', direction].join(' ')); that.sliding = false; setTimeout(function () { that.$element.trigger(slidEvent) }, 0) }) .emulateTransitionEnd(Carousel.TRANSITION_DURATION) } else { $active.removeClass('active'); $next.addClass('active'); this.sliding = false; this.$element.trigger(slidEvent) } isCycling && this.cycle(); return this }; // CAROUSEL PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this); var data = $this.data('bs.carousel'); var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option); var action = typeof option == 'string' ? option : options.slide; if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))); if (typeof option == 'number') data.to(option); else if (action) data[action](); else if (options.interval) data.pause().cycle() }) } var old = $.fn.carousel; $.fn.carousel = Plugin; $.fn.carousel.Constructor = Carousel; // CAROUSEL NO CONFLICT // ==================== $.fn.carousel.noConflict = function () { $.fn.carousel = old; return this }; // CAROUSEL DATA-API // ================= var clickHandler = function (e) { var href; var $this = $(this); var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')); // strip for ie7 if (!$target.hasClass('carousel')) return; var options = $.extend({}, $target.data(), $this.data()); var slideIndex = $this.attr('data-slide-to'); if (slideIndex) options.interval = false; Plugin.call($target, options); if (slideIndex) { $target.data('bs.carousel').to(slideIndex) } e.preventDefault() }; $(document) .on('click.bs.carousel.data-api', '[data-slide]', clickHandler) .on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler); $(window).on('load', function () { $('[data-ride="carousel"]').each(function () { var $carousel = $(this); Plugin.call($carousel, $carousel.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: collapse.js v3.3.7 * http://getbootstrap.com/javascript/#collapse * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ /* jshint latedef: false */ +function ($) { 'use strict'; // COLLAPSE PUBLIC CLASS DEFINITION // ================================ var Collapse = function (element, options) { this.$element = $(element); this.options = $.extend({}, Collapse.DEFAULTS, options); this.$trigger = $('[data-toggle="collapse"][href="#' + element.id + '"],' + '[data-toggle="collapse"][data-target="#' + element.id + '"]'); this.transitioning = null; if (this.options.parent) { this.$parent = this.getParent() } else { this.addAriaAndCollapsedClass(this.$element, this.$trigger) } if (this.options.toggle) this.toggle() }; Collapse.VERSION = '3.3.7'; Collapse.TRANSITION_DURATION = 350; Collapse.DEFAULTS = { toggle: true }; Collapse.prototype.dimension = function () { var hasWidth = this.$element.hasClass('width'); return hasWidth ? 'width' : 'height' }; Collapse.prototype.show = function () { if (this.transitioning || this.$element.hasClass('in')) return; var activesData; var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing'); if (actives && actives.length) { activesData = actives.data('bs.collapse'); if (activesData && activesData.transitioning) return } var startEvent = $.Event('show.bs.collapse'); this.$element.trigger(startEvent); if (startEvent.isDefaultPrevented()) return; if (actives && actives.length) { Plugin.call(actives, 'hide'); activesData || actives.data('bs.collapse', null) } var dimension = this.dimension(); this.$element .removeClass('collapse') .addClass('collapsing')[dimension](0) .attr('aria-expanded', true); this.$trigger .removeClass('collapsed') .attr('aria-expanded', true); this.transitioning = 1; var complete = function () { this.$element .removeClass('collapsing') .addClass('collapse in')[dimension](''); this.transitioning = 0; this.$element .trigger('shown.bs.collapse') }; if (!$.support.transition) return complete.call(this); var scrollSize = $.camelCase(['scroll', dimension].join('-')); this.$element .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize]) }; Collapse.prototype.hide = function () { if (this.transitioning || !this.$element.hasClass('in')) return; var startEvent = $.Event('hide.bs.collapse'); this.$element.trigger(startEvent); if (startEvent.isDefaultPrevented()) return; var dimension = this.dimension(); this.$element[dimension](this.$element[dimension]())[0].offsetHeight; this.$element .addClass('collapsing') .removeClass('collapse in') .attr('aria-expanded', false); this.$trigger .addClass('collapsed') .attr('aria-expanded', false); this.transitioning = 1; var complete = function () { this.transitioning = 0; this.$element .removeClass('collapsing') .addClass('collapse') .trigger('hidden.bs.collapse') }; if (!$.support.transition) return complete.call(this); this.$element [dimension](0) .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(Collapse.TRANSITION_DURATION) }; Collapse.prototype.toggle = function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() }; Collapse.prototype.getParent = function () { return $(this.options.parent) .find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]') .each($.proxy(function (i, element) { var $element = $(element); this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element) }, this)) .end() }; Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) { var isOpen = $element.hasClass('in'); $element.attr('aria-expanded', isOpen); $trigger .toggleClass('collapsed', !isOpen) .attr('aria-expanded', isOpen) }; function getTargetFromTrigger($trigger) { var href; var target = $trigger.attr('data-target') || (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, ''); // strip for ie7 return $(target) } // COLLAPSE PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this); var data = $this.data('bs.collapse'); var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option); if (!data && options.toggle && /show|hide/.test(option)) options.toggle = false; if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))); if (typeof option == 'string') data[option]() }) } var old = $.fn.collapse; $.fn.collapse = Plugin; $.fn.collapse.Constructor = Collapse; // COLLAPSE NO CONFLICT // ==================== $.fn.collapse.noConflict = function () { $.fn.collapse = old; return this }; // COLLAPSE DATA-API // ================= $(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) { var $this = $(this); if (!$this.attr('data-target')) e.preventDefault(); var $target = getTargetFromTrigger($this); var data = $target.data('bs.collapse'); var option = data ? 'toggle' : $this.data(); Plugin.call($target, option) }) }(jQuery); /* ======================================================================== * Bootstrap: dropdown.js v3.3.7 * http://getbootstrap.com/javascript/#dropdowns * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // DROPDOWN CLASS DEFINITION // ========================= var backdrop = '.dropdown-backdrop'; var toggle = '[data-toggle="dropdown"]'; var Dropdown = function (element) { $(element).on('click.bs.dropdown', this.toggle) }; Dropdown.VERSION = '3.3.7'; function getParent($this) { var selector = $this.attr('data-target'); if (!selector) { selector = $this.attr('href'); selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, ''); // strip for ie7 } var $parent = selector && $(selector); return $parent && $parent.length ? $parent : $this.parent() } function clearMenus(e) { if (e && e.which === 3) return; $(backdrop).remove(); $(toggle).each(function () { var $this = $(this); var $parent = getParent($this); var relatedTarget = { relatedTarget: this }; if (!$parent.hasClass('open')) return; if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return; $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget)); if (e.isDefaultPrevented()) return; $this.attr('aria-expanded', 'false'); $parent.removeClass('open').trigger($.Event('hidden.bs.dropdown', relatedTarget)) }) } Dropdown.prototype.toggle = function (e) { var $this = $(this); if ($this.is('.disabled, :disabled')) return; var $parent = getParent($this); var isActive = $parent.hasClass('open'); clearMenus(); if (!isActive) { if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) { // if mobile we use a backdrop because click events don't delegate $(document.createElement('div')) .addClass('dropdown-backdrop') .insertAfter($(this)) .on('click', clearMenus) } var relatedTarget = { relatedTarget: this }; $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget)); if (e.isDefaultPrevented()) return; $this .trigger('focus') .attr('aria-expanded', 'true'); $parent .toggleClass('open') .trigger($.Event('shown.bs.dropdown', relatedTarget)) } return false }; Dropdown.prototype.keydown = function (e) { if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return; var $this = $(this); e.preventDefault(); e.stopPropagation(); if ($this.is('.disabled, :disabled')) return; var $parent = getParent($this); var isActive = $parent.hasClass('open'); if (!isActive && e.which != 27 || isActive && e.which == 27) { if (e.which == 27) $parent.find(toggle).trigger('focus'); return $this.trigger('click') } var desc = ' li:not(.disabled):visible a'; var $items = $parent.find('.dropdown-menu' + desc); if (!$items.length) return; var index = $items.index(e.target); if (e.which == 38 && index > 0) index--; // up if (e.which == 40 && index < $items.length - 1) index++; // down if (!~index) index = 0; $items.eq(index).trigger('focus') }; // DROPDOWN PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this); var data = $this.data('bs.dropdown'); if (!data) $this.data('bs.dropdown', (data = new Dropdown(this))); if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.dropdown; $.fn.dropdown = Plugin; $.fn.dropdown.Constructor = Dropdown; // DROPDOWN NO CONFLICT // ==================== $.fn.dropdown.noConflict = function () { $.fn.dropdown = old; return this }; // APPLY TO STANDARD DROPDOWN ELEMENTS // =================================== $(document) .on('click.bs.dropdown.data-api', clearMenus) .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle) .on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown) .on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown) }(jQuery); /* ======================================================================== * Bootstrap: modal.js v3.3.7 * http://getbootstrap.com/javascript/#modals * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // MODAL CLASS DEFINITION // ====================== var Modal = function (element, options) { this.options = options; this.$body = $(document.body); this.$element = $(element); this.$dialog = this.$element.find('.modal-dialog'); this.$backdrop = null; this.isShown = null; this.originalBodyPad = null; this.scrollbarWidth = 0; this.ignoreBackdropClick = false; if (this.options.remote) { this.$element .find('.modal-content') .load(this.options.remote, $.proxy(function () { this.$element.trigger('loaded.bs.modal') }, this)) } }; Modal.VERSION = '3.3.7'; Modal.TRANSITION_DURATION = 300; Modal.BACKDROP_TRANSITION_DURATION = 150; Modal.DEFAULTS = { backdrop: true, keyboard: true, show: true }; Modal.prototype.toggle = function (_relatedTarget) { return this.isShown ? this.hide() : this.show(_relatedTarget) }; Modal.prototype.show = function (_relatedTarget) { var that = this; var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget }); this.$element.trigger(e); if (this.isShown || e.isDefaultPrevented()) return; this.isShown = true; this.checkScrollbar(); this.setScrollbar(); this.$body.addClass('modal-open'); this.escape(); this.resize(); this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this)); this.$dialog.on('mousedown.dismiss.bs.modal', function () { that.$element.one('mouseup.dismiss.bs.modal', function (e) { if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true }) }); this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade'); if (!that.$element.parent().length) { that.$element.appendTo(that.$body); // don't move modals dom position } that.$element .show() .scrollTop(0); that.adjustDialog(); if (transition) { that.$element[0].offsetWidth; // force reflow } that.$element.addClass('in'); that.enforceFocus(); var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget }); transition ? that.$dialog // wait for modal to slide in .one('bsTransitionEnd', function () { that.$element.trigger('focus').trigger(e) }) .emulateTransitionEnd(Modal.TRANSITION_DURATION) : that.$element.trigger('focus').trigger(e) }) }; Modal.prototype.hide = function (e) { if (e) e.preventDefault(); e = $.Event('hide.bs.modal'); this.$element.trigger(e); if (!this.isShown || e.isDefaultPrevented()) return; this.isShown = false; this.escape(); this.resize(); $(document).off('focusin.bs.modal'); this.$element .removeClass('in') .off('click.dismiss.bs.modal') .off('mouseup.dismiss.bs.modal'); this.$dialog.off('mousedown.dismiss.bs.modal'); $.support.transition && this.$element.hasClass('fade') ? this.$element .one('bsTransitionEnd', $.proxy(this.hideModal, this)) .emulateTransitionEnd(Modal.TRANSITION_DURATION) : this.hideModal() }; Modal.prototype.enforceFocus = function () { $(document) .off('focusin.bs.modal') // guard against infinite focus loop .on('focusin.bs.modal', $.proxy(function (e) { if (document !== e.target && this.$element[0] !== e.target && !this.$element.has(e.target).length) { this.$element.trigger('focus') } }, this)) }; Modal.prototype.escape = function () { if (this.isShown && this.options.keyboard) { this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) { e.which == 27 && this.hide() }, this)) } else if (!this.isShown) { this.$element.off('keydown.dismiss.bs.modal') } }; Modal.prototype.resize = function () { if (this.isShown) { $(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this)) } else { $(window).off('resize.bs.modal') } }; Modal.prototype.hideModal = function () { var that = this; this.$element.hide(); this.backdrop(function () { that.$body.removeClass('modal-open'); that.resetAdjustments(); that.resetScrollbar(); that.$element.trigger('hidden.bs.modal') }) }; Modal.prototype.removeBackdrop = function () { this.$backdrop && this.$backdrop.remove(); this.$backdrop = null }; Modal.prototype.backdrop = function (callback) { var that = this; var animate = this.$element.hasClass('fade') ? 'fade' : ''; if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate; this.$backdrop = $(document.createElement('div')) .addClass('modal-backdrop ' + animate) .appendTo(this.$body); this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) { if (this.ignoreBackdropClick) { this.ignoreBackdropClick = false; return } if (e.target !== e.currentTarget) return; this.options.backdrop == 'static' ? this.$element[0].focus() : this.hide() }, this)); if (doAnimate) this.$backdrop[0].offsetWidth; // force reflow this.$backdrop.addClass('in'); if (!callback) return; doAnimate ? this.$backdrop .one('bsTransitionEnd', callback) .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in'); var callbackRemove = function () { that.removeBackdrop(); callback && callback() }; $.support.transition && this.$element.hasClass('fade') ? this.$backdrop .one('bsTransitionEnd', callbackRemove) .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : callbackRemove() } else if (callback) { callback() } }; // these following methods are used to handle overflowing modals Modal.prototype.handleUpdate = function () { this.adjustDialog() }; Modal.prototype.adjustDialog = function () { var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight; this.$element.css({ paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '', paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : '' }) }; Modal.prototype.resetAdjustments = function () { this.$element.css({ paddingLeft: '', paddingRight: '' }) }; Modal.prototype.checkScrollbar = function () { var fullWindowWidth = window.innerWidth; if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8 var documentElementRect = document.documentElement.getBoundingClientRect(); fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left) } this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth; this.scrollbarWidth = this.measureScrollbar() }; Modal.prototype.setScrollbar = function () { var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10); this.originalBodyPad = document.body.style.paddingRight || ''; if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth) }; Modal.prototype.resetScrollbar = function () { this.$body.css('padding-right', this.originalBodyPad) }; Modal.prototype.measureScrollbar = function () { // thx walsh var scrollDiv = document.createElement('div'); scrollDiv.className = 'modal-scrollbar-measure'; this.$body.append(scrollDiv); var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth; this.$body[0].removeChild(scrollDiv); return scrollbarWidth }; // MODAL PLUGIN DEFINITION // ======================= function Plugin(option, _relatedTarget) { return this.each(function () { var $this = $(this); var data = $this.data('bs.modal'); var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option); if (!data) $this.data('bs.modal', (data = new Modal(this, options))); if (typeof option == 'string') data[option](_relatedTarget); else if (options.show) data.show(_relatedTarget) }) } var old = $.fn.modal; $.fn.modal = Plugin; $.fn.modal.Constructor = Modal; // MODAL NO CONFLICT // ================= $.fn.modal.noConflict = function () { $.fn.modal = old; return this }; // MODAL DATA-API // ============== $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this); var href = $this.attr('href'); var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))); // strip for ie7 var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data()); if ($this.is('a')) e.preventDefault(); $target.one('show.bs.modal', function (showEvent) { if (showEvent.isDefaultPrevented()) return; // only login focus restorer if modal will actually get shown $target.one('hidden.bs.modal', function () { $this.is(':visible') && $this.trigger('focus') }) }); Plugin.call($target, option, this) }) }(jQuery); /* ======================================================================== * Bootstrap: tooltip.js v3.3.7 * http://getbootstrap.com/javascript/#tooltip * Inspired by the original jQuery.tipsy by Jason Frame * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // TOOLTIP PUBLIC CLASS DEFINITION // =============================== var Tooltip = function (element, options) { this.type = null; this.options = null; this.enabled = null; this.timeout = null; this.hoverState = null; this.$element = null; this.inState = null; this.init('tooltip', element, options) }; Tooltip.VERSION = '3.3.7'; Tooltip.TRANSITION_DURATION = 150; Tooltip.DEFAULTS = { animation: true, placement: 'top', selector: false, template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>', trigger: 'hover focus', title: '', delay: 0, html: false, container: false, viewport: { selector: 'body', padding: 0 } }; Tooltip.prototype.init = function (type, element, options) { this.enabled = true; this.type = type; this.$element = $(element); this.options = this.getOptions(options); this.$viewport = this.options.viewport && $($.isFunction(this.options.viewport) ? this.options.viewport.call(this, this.$element) : (this.options.viewport.selector || this.options.viewport)); this.inState = { click: false, hover: false, focus: false }; if (this.$element[0] instanceof document.constructor && !this.options.selector) { throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!') } var triggers = this.options.trigger.split(' '); for (var i = triggers.length; i--;) { var trigger = triggers[i]; if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin'; var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'; this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)); this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) } } this.options.selector ? (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) : this.fixTitle() }; Tooltip.prototype.getDefaults = function () { return Tooltip.DEFAULTS }; Tooltip.prototype.getOptions = function (options) { options = $.extend({}, this.getDefaults(), this.$element.data(), options); if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay, hide: options.delay } } return options }; Tooltip.prototype.getDelegateOptions = function () { var options = {}; var defaults = this.getDefaults(); this._options && $.each(this._options, function (key, value) { if (defaults[key] != value) options[key] = value }); return options }; Tooltip.prototype.enter = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type); if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()); $(obj.currentTarget).data('bs.' + this.type, self) } if (obj instanceof $.Event) { self.inState[obj.type == 'focusin' ? 'focus' : 'hover'] = true } if (self.tip().hasClass('in') || self.hoverState == 'in') { self.hoverState = 'in'; return } clearTimeout(self.timeout); self.hoverState = 'in'; if (!self.options.delay || !self.options.delay.show) return self.show(); self.timeout = setTimeout(function () { if (self.hoverState == 'in') self.show() }, self.options.delay.show) }; Tooltip.prototype.isInStateTrue = function () { for (var key in this.inState) { if (this.inState[key]) return true } return false }; Tooltip.prototype.leave = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type); if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()); $(obj.currentTarget).data('bs.' + this.type, self) } if (obj instanceof $.Event) { self.inState[obj.type == 'focusout' ? 'focus' : 'hover'] = false } if (self.isInStateTrue()) return; clearTimeout(self.timeout); self.hoverState = 'out'; if (!self.options.delay || !self.options.delay.hide) return self.hide(); self.timeout = setTimeout(function () { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) }; Tooltip.prototype.show = function () { var e = $.Event('show.bs.' + this.type); if (this.hasContent() && this.enabled) { this.$element.trigger(e); var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0]); if (e.isDefaultPrevented() || !inDom) return; var that = this; var $tip = this.tip(); var tipId = this.getUID(this.type); this.setContent(); $tip.attr('id', tipId); this.$element.attr('aria-describedby', tipId); if (this.options.animation) $tip.addClass('fade'); var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement; var autoToken = /\s?auto?\s?/i; var autoPlace = autoToken.test(placement); if (autoPlace) placement = placement.replace(autoToken, '') || 'top'; $tip .detach() .css({ top: 0, left: 0, display: 'block' }) .addClass(placement) .data('bs.' + this.type, this); this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element); this.$element.trigger('inserted.bs.' + this.type); var pos = this.getPosition(); var actualWidth = $tip[0].offsetWidth; var actualHeight = $tip[0].offsetHeight; if (autoPlace) { var orgPlacement = placement; var viewportDim = this.getPosition(this.$viewport); placement = placement == 'bottom' && pos.bottom + actualHeight > viewportDim.bottom ? 'top' : placement == 'top' && pos.top - actualHeight < viewportDim.top ? 'bottom' : placement == 'right' && pos.right + actualWidth > viewportDim.width ? 'left' : placement == 'left' && pos.left - actualWidth < viewportDim.left ? 'right' : placement; $tip .removeClass(orgPlacement) .addClass(placement) } var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight); this.applyPlacement(calculatedOffset, placement); var complete = function () { var prevHoverState = that.hoverState; that.$element.trigger('shown.bs.' + that.type); that.hoverState = null; if (prevHoverState == 'out') that.leave(that) }; $.support.transition && this.$tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : complete() } }; Tooltip.prototype.applyPlacement = function (offset, placement) { var $tip = this.tip(); var width = $tip[0].offsetWidth; var height = $tip[0].offsetHeight; // manually read margins because getBoundingClientRect includes difference var marginTop = parseInt($tip.css('margin-top'), 10); var marginLeft = parseInt($tip.css('margin-left'), 10); // we must check for NaN for ie 8/9 if (isNaN(marginTop)) marginTop = 0; if (isNaN(marginLeft)) marginLeft = 0; offset.top += marginTop; offset.left += marginLeft; // $.fn.offset doesn't round pixel values // so we use setOffset directly with our own function B-0 $.offset.setOffset($tip[0], $.extend({ using: function (props) { $tip.css({ top: Math.round(props.top), left: Math.round(props.left) }) } }, offset), 0); $tip.addClass('in'); // check to see if placing tip in new offset caused the tip to resize itself var actualWidth = $tip[0].offsetWidth; var actualHeight = $tip[0].offsetHeight; if (placement == 'top' && actualHeight != height) { offset.top = offset.top + height - actualHeight } var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight); if (delta.left) offset.left += delta.left; else offset.top += delta.top; var isVertical = /top|bottom/.test(placement); var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight; var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight'; $tip.offset(offset); this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical) }; Tooltip.prototype.replaceArrow = function (delta, dimension, isVertical) { this.arrow() .css(isVertical ? 'left' : 'top', 50 * (1 - delta / dimension) + '%') .css(isVertical ? 'top' : 'left', '') }; Tooltip.prototype.setContent = function () { var $tip = this.tip(); var title = this.getTitle(); $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title); $tip.removeClass('fade in top bottom left right') }; Tooltip.prototype.hide = function (callback) { var that = this; var $tip = $(this.$tip); var e = $.Event('hide.bs.' + this.type); function complete() { if (that.hoverState != 'in') $tip.detach(); if (that.$element) { // TODO: Check whether guarding this code with this `if` is really necessary. that.$element .removeAttr('aria-describedby') .trigger('hidden.bs.' + that.type) } callback && callback() } this.$element.trigger(e); if (e.isDefaultPrevented()) return; $tip.removeClass('in'); $.support.transition && $tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : complete(); this.hoverState = null; return this }; Tooltip.prototype.fixTitle = function () { var $e = this.$element; if ($e.attr('title') || typeof $e.attr('data-original-title') != 'string') { $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } }; Tooltip.prototype.hasContent = function () { return this.getTitle() }; Tooltip.prototype.getPosition = function ($element) { $element = $element || this.$element; var el = $element[0]; var isBody = el.tagName == 'BODY'; var elRect = el.getBoundingClientRect(); if (elRect.width == null) { // width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093 elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top }) } var isSvg = window.SVGElement && el instanceof window.SVGElement; // Avoid using $.offset() on SVGs since it gives incorrect results in jQuery 3. // See https://github.com/twbs/bootstrap/issues/20280 var elOffset = isBody ? { top: 0, left: 0 } : (isSvg ? null : $element.offset()); var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() }; var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null; return $.extend({}, elRect, scroll, outerDims, elOffset) }; Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) { return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } : /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width } }; Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) { var delta = { top: 0, left: 0 }; if (!this.$viewport) return delta; var viewportPadding = this.options.viewport && this.options.viewport.padding || 0; var viewportDimensions = this.getPosition(this.$viewport); if (/right|left/.test(placement)) { var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll; var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight; if (topEdgeOffset < viewportDimensions.top) { // top overflow delta.top = viewportDimensions.top - topEdgeOffset } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset } } else { var leftEdgeOffset = pos.left - viewportPadding; var rightEdgeOffset = pos.left + viewportPadding + actualWidth; if (leftEdgeOffset < viewportDimensions.left) { // left overflow delta.left = viewportDimensions.left - leftEdgeOffset } else if (rightEdgeOffset > viewportDimensions.right) { // right overflow delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset } } return delta }; Tooltip.prototype.getTitle = function () { var title; var $e = this.$element; var o = this.options; title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title); return title }; Tooltip.prototype.getUID = function (prefix) { do prefix += ~~(Math.random() * 1000000); while (document.getElementById(prefix)); return prefix }; Tooltip.prototype.tip = function () { if (!this.$tip) { this.$tip = $(this.options.template); if (this.$tip.length != 1) { throw new Error(this.type + ' `template` option must consist of exactly 1 top-level element!') } } return this.$tip }; Tooltip.prototype.arrow = function () { return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow')) }; Tooltip.prototype.enable = function () { this.enabled = true }; Tooltip.prototype.disable = function () { this.enabled = false }; Tooltip.prototype.toggleEnabled = function () { this.enabled = !this.enabled }; Tooltip.prototype.toggle = function (e) { var self = this; if (e) { self = $(e.currentTarget).data('bs.' + this.type); if (!self) { self = new this.constructor(e.currentTarget, this.getDelegateOptions()); $(e.currentTarget).data('bs.' + this.type, self) } } if (e) { self.inState.click = !self.inState.click; if (self.isInStateTrue()) self.enter(self); else self.leave(self) } else { self.tip().hasClass('in') ? self.leave(self) : self.enter(self) } }; Tooltip.prototype.destroy = function () { var that = this; clearTimeout(this.timeout); this.hide(function () { that.$element.off('.' + that.type).removeData('bs.' + that.type); if (that.$tip) { that.$tip.detach() } that.$tip = null; that.$arrow = null; that.$viewport = null; that.$element = null }) }; // TOOLTIP PLUGIN DEFINITION // ========================= function Plugin(option) { return this.each(function () { var $this = $(this); var data = $this.data('bs.tooltip'); var options = typeof option == 'object' && option; if (!data && /destroy|hide/.test(option)) return; if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options))); if (typeof option == 'string') data[option]() }) } var old = $.fn.tooltip; $.fn.tooltip = Plugin; $.fn.tooltip.Constructor = Tooltip; // TOOLTIP NO CONFLICT // =================== $.fn.tooltip.noConflict = function () { $.fn.tooltip = old; return this } }(jQuery); /* ======================================================================== * Bootstrap: popover.js v3.3.7 * http://getbootstrap.com/javascript/#popovers * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // POPOVER PUBLIC CLASS DEFINITION // =============================== var Popover = function (element, options) { this.init('popover', element, options) }; if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js'); Popover.VERSION = '3.3.7'; Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, { placement: 'right', trigger: 'click', content: '', template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' }); // NOTE: POPOVER EXTENDS tooltip.js // ================================ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype); Popover.prototype.constructor = Popover; Popover.prototype.getDefaults = function () { return Popover.DEFAULTS }; Popover.prototype.setContent = function () { var $tip = this.tip(); var title = this.getTitle(); var content = this.getContent(); $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title); $tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text' ](content); $tip.removeClass('fade top bottom left right in'); // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do // this manually by checking the contents. if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide() }; Popover.prototype.hasContent = function () { return this.getTitle() || this.getContent() }; Popover.prototype.getContent = function () { var $e = this.$element; var o = this.options; return $e.attr('data-content') || (typeof o.content == 'function' ? o.content.call($e[0]) : o.content) }; Popover.prototype.arrow = function () { return (this.$arrow = this.$arrow || this.tip().find('.arrow')) }; // POPOVER PLUGIN DEFINITION // ========================= function Plugin(option) { return this.each(function () { var $this = $(this); var data = $this.data('bs.popover'); var options = typeof option == 'object' && option; if (!data && /destroy|hide/.test(option)) return; if (!data) $this.data('bs.popover', (data = new Popover(this, options))); if (typeof option == 'string') data[option]() }) } var old = $.fn.popover; $.fn.popover = Plugin; $.fn.popover.Constructor = Popover; // POPOVER NO CONFLICT // =================== $.fn.popover.noConflict = function () { $.fn.popover = old; return this } }(jQuery); /* ======================================================================== * Bootstrap: scrollspy.js v3.3.7 * http://getbootstrap.com/javascript/#scrollspy * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // SCROLLSPY CLASS DEFINITION // ========================== function ScrollSpy(element, options) { this.$body = $(document.body); this.$scrollElement = $(element).is(document.body) ? $(window) : $(element); this.options = $.extend({}, ScrollSpy.DEFAULTS, options); this.selector = (this.options.target || '') + ' .nav li > a'; this.offsets = []; this.targets = []; this.activeTarget = null; this.scrollHeight = 0; this.$scrollElement.on('scroll.bs.scrollspy', $.proxy(this.process, this)); this.refresh(); this.process() } ScrollSpy.VERSION = '3.3.7'; ScrollSpy.DEFAULTS = { offset: 10 }; ScrollSpy.prototype.getScrollHeight = function () { return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight) }; ScrollSpy.prototype.refresh = function () { var that = this; var offsetMethod = 'offset'; var offsetBase = 0; this.offsets = []; this.targets = []; this.scrollHeight = this.getScrollHeight(); if (!$.isWindow(this.$scrollElement[0])) { offsetMethod = 'position'; offsetBase = this.$scrollElement.scrollTop() } this.$body .find(this.selector) .map(function () { var $el = $(this); var href = $el.data('target') || $el.attr('href'); var $href = /^#./.test(href) && $(href); return ($href && $href.length && $href.is(':visible') && [[$href[offsetMethod]().top + offsetBase, href]]) || null }) .sort(function (a, b) { return a[0] - b[0] }) .each(function () { that.offsets.push(this[0]); that.targets.push(this[1]) }) }; ScrollSpy.prototype.process = function () { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset; var scrollHeight = this.getScrollHeight(); var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height(); var offsets = this.offsets; var targets = this.targets; var activeTarget = this.activeTarget; var i; if (this.scrollHeight != scrollHeight) { this.refresh() } if (scrollTop >= maxScroll) { return activeTarget != (i = targets[targets.length - 1]) && this.activate(i) } if (activeTarget && scrollTop < offsets[0]) { this.activeTarget = null; return this.clear() } for (i = offsets.length; i--;) { activeTarget != targets[i] && scrollTop >= offsets[i] && (offsets[i + 1] === undefined || scrollTop < offsets[i + 1]) && this.activate(targets[i]) } }; ScrollSpy.prototype.activate = function (target) { this.activeTarget = target; this.clear(); var selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]'; var active = $(selector) .parents('li') .addClass('active'); if (active.parent('.dropdown-menu').length) { active = active .closest('li.dropdown') .addClass('active') } active.trigger('activate.bs.scrollspy') }; ScrollSpy.prototype.clear = function () { $(this.selector) .parentsUntil(this.options.target, '.active') .removeClass('active') }; // SCROLLSPY PLUGIN DEFINITION // =========================== function Plugin(option) { return this.each(function () { var $this = $(this); var data = $this.data('bs.scrollspy'); var options = typeof option == 'object' && option; if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options))); if (typeof option == 'string') data[option]() }) } var old = $.fn.scrollspy; $.fn.scrollspy = Plugin; $.fn.scrollspy.Constructor = ScrollSpy; // SCROLLSPY NO CONFLICT // ===================== $.fn.scrollspy.noConflict = function () { $.fn.scrollspy = old; return this }; // SCROLLSPY DATA-API // ================== $(window).on('load.bs.scrollspy.data-api', function () { $('[data-spy="scroll"]').each(function () { var $spy = $(this); Plugin.call($spy, $spy.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: tab.js v3.3.7 * http://getbootstrap.com/javascript/#tabs * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // TAB CLASS DEFINITION // ==================== var Tab = function (element) { // jscs:disable requireDollarBeforejQueryAssignment this.element = $(element); // jscs:enable requireDollarBeforejQueryAssignment }; Tab.VERSION = '3.3.7'; Tab.TRANSITION_DURATION = 150; Tab.prototype.show = function () { var $this = this.element; var $ul = $this.closest('ul:not(.dropdown-menu)'); var selector = $this.data('target'); if (!selector) { selector = $this.attr('href'); selector = selector && selector.replace(/.*(?=#[^\s]*$)/, ''); // strip for ie7 } if ($this.parent('li').hasClass('active')) return; var $previous = $ul.find('.active:last a'); var hideEvent = $.Event('hide.bs.tab', { relatedTarget: $this[0] }); var showEvent = $.Event('show.bs.tab', { relatedTarget: $previous[0] }); $previous.trigger(hideEvent); $this.trigger(showEvent); if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return; var $target = $(selector); this.activate($this.closest('li'), $ul); this.activate($target, $target.parent(), function () { $previous.trigger({ type: 'hidden.bs.tab', relatedTarget: $this[0] }); $this.trigger({ type: 'shown.bs.tab', relatedTarget: $previous[0] }) }) }; Tab.prototype.activate = function (element, container, callback) { var $active = container.find('> .active'); var transition = callback && $.support.transition && ($active.length && $active.hasClass('fade') || !!container.find('> .fade').length); function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') .end() .find('[data-toggle="tab"]') .attr('aria-expanded', false); element .addClass('active') .find('[data-toggle="tab"]') .attr('aria-expanded', true); if (transition) { element[0].offsetWidth; // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if (element.parent('.dropdown-menu').length) { element .closest('li.dropdown') .addClass('active') .end() .find('[data-toggle="tab"]') .attr('aria-expanded', true) } callback && callback() } $active.length && transition ? $active .one('bsTransitionEnd', next) .emulateTransitionEnd(Tab.TRANSITION_DURATION) : next(); $active.removeClass('in') }; // TAB PLUGIN DEFINITION // ===================== function Plugin(option) { return this.each(function () { var $this = $(this); var data = $this.data('bs.tab'); if (!data) $this.data('bs.tab', (data = new Tab(this))); if (typeof option == 'string') data[option]() }) } var old = $.fn.tab; $.fn.tab = Plugin; $.fn.tab.Constructor = Tab; // TAB NO CONFLICT // =============== $.fn.tab.noConflict = function () { $.fn.tab = old; return this }; // TAB DATA-API // ============ var clickHandler = function (e) { e.preventDefault(); Plugin.call($(this), 'show') }; $(document) .on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler) .on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler) }(jQuery); /* ======================================================================== * Bootstrap: affix.js v3.3.7 * http://getbootstrap.com/javascript/#affix * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // AFFIX CLASS DEFINITION // ====================== var Affix = function (element, options) { this.options = $.extend({}, Affix.DEFAULTS, options); this.$target = $(this.options.target) .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this)); this.$element = $(element); this.affixed = null; this.unpin = null; this.pinnedOffset = null; this.checkPosition() }; Affix.VERSION = '3.3.7'; Affix.RESET = 'affix affix-top affix-bottom'; Affix.DEFAULTS = { offset: 0, target: window }; Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) { var scrollTop = this.$target.scrollTop(); var position = this.$element.offset(); var targetHeight = this.$target.height(); if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false; if (this.affixed == 'bottom') { if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'; return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom' } var initializing = this.affixed == null; var colliderTop = initializing ? scrollTop : position.top; var colliderHeight = initializing ? targetHeight : height; if (offsetTop != null && scrollTop <= offsetTop) return 'top'; if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'; return false }; Affix.prototype.getPinnedOffset = function () { if (this.pinnedOffset) return this.pinnedOffset; this.$element.removeClass(Affix.RESET).addClass('affix'); var scrollTop = this.$target.scrollTop(); var position = this.$element.offset(); return (this.pinnedOffset = position.top - scrollTop) }; Affix.prototype.checkPositionWithEventLoop = function () { setTimeout($.proxy(this.checkPosition, this), 1) }; Affix.prototype.checkPosition = function () { if (!this.$element.is(':visible')) return; var height = this.$element.height(); var offset = this.options.offset; var offsetTop = offset.top; var offsetBottom = offset.bottom; var scrollHeight = Math.max($(document).height(), $(document.body).height()); if (typeof offset != 'object') offsetBottom = offsetTop = offset; if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element); if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element); var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom); if (this.affixed != affix) { if (this.unpin != null) this.$element.css('top', ''); var affixType = 'affix' + (affix ? '-' + affix : ''); var e = $.Event(affixType + '.bs.affix'); this.$element.trigger(e); if (e.isDefaultPrevented()) return; this.affixed = affix; this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null; this.$element .removeClass(Affix.RESET) .addClass(affixType) .trigger(affixType.replace('affix', 'affixed') + '.bs.affix') } if (affix == 'bottom') { this.$element.offset({ top: scrollHeight - height - offsetBottom }) } }; // AFFIX PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function () { var $this = $(this); var data = $this.data('bs.affix'); var options = typeof option == 'object' && option; if (!data) $this.data('bs.affix', (data = new Affix(this, options))); if (typeof option == 'string') data[option]() }) } var old = $.fn.affix; $.fn.affix = Plugin; $.fn.affix.Constructor = Affix; // AFFIX NO CONFLICT // ================= $.fn.affix.noConflict = function () { $.fn.affix = old; return this }; // AFFIX DATA-API // ============== $(window).on('load', function () { $('[data-spy="affix"]').each(function () { var $spy = $(this); var data = $spy.data(); data.offset = data.offset || {}; if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom; if (data.offsetTop != null) data.offset.top = data.offsetTop; Plugin.call($spy, data) }) }) }(jQuery);
const resolveTask = require('./../common/factories/resolveTask'); const rejectTask = require('./../common/factories/rejectTask'); const errors = require('../errors'); const isAdmin = require('./../common/actions/isAdmin'); const toggleCompetitionVisibility = require('./actions/toggleCompetitionVisibility'); module.exports = [ isAdmin, { true: [ toggleCompetitionVisibility, { success: [resolveTask()], error: [rejectTask(errors.ADD_IMAGE)], }, ], false: [rejectTask(errors.ADD_IMAGE)], }, ];
/* 小动态瀑布流 * nano from https://github.com/trix/nano.git * * 返回 json 的结构: * { * "photos": { * "total": 60, * "photo": [{ * "name": "heyun51@gmail.com", * "price": "359.00", * "id": 1796, * "quantity": 0 * }], * "perpage": 10, * "page": 4, * "pages": 6 * }, * "stat": "ok" * } * */ ;(function($) { $.fn.extend({ miniWaterfall: function(options) { // 默认值 var settings = $.extend({ url: window.location.href, row: 4, // 瀑布流的列数 row_id: "waterfall_id_", row_class: "waterfall_class", tpl_id: "#tpl", loading_id: "#loading", init_load: true, // 页面显示就加载一页 page: 1, // 从几页开始 perpage: 10, // 每页显示的数量 load_button: "#load_button", // 点击加载按钮 distance: 200, // 距离底部多少时加载 msg_waterfull: '#msg_waterfull' // 当没有数据时显示 }, options); var div_html = ""; var divs = new Array(); for(i=1; i<=settings.row; i++) { div_html += '<div id="' + settings.row_id + i + '" class="' + settings.row_class + '"></div>'; divs.push("#" + settings.row_id + i); } $(this).append(div_html); // 生成列 $(this).after('<div id="page" style="display: none" data-current_p="0" data-page="' + settings.page + '" data-perpage="' + settings.perpage + '"></div>'); $(settings.msg_waterfull).hide(); $(settings.loading_id).show(); // 每个块的插入 function waterfall_put(json) { var div_hg = new Array(); $.each(divs, function(i, n) { div_hg.push({hg: $(n).outerHeight(), id: n}); }); // 按从低到高 排序 div_hg div_hg.sort(function(a, b) { return a.hg - b.hg; }); $.each(json, function(i, n) { $(div_hg[i%settings.row].id).append($(settings.tpl_id).nano(n)); }); } function data_load() { var page = $('#page').attr('data-page'); var perpage = $('#page').attr('data-perpage'); var current_p = $('#page').attr('data-current_p'); if(page != current_p) { $(settings.loading_id).show(); $('#page').attr('data-current_p', page); $.getJSON(settings.url, {page: page, perpage: perpage}, function(d) { if (d.stat !== 'ok') { alert('load data error!'); $(settings.loading_id).hide(); return; } if (d.photos.total == 0){ $(settings.msg_waterfull).show(); $(settings.loading_id).hide(); return; } $(settings.msg_waterfull).hide(); waterfall_put(d.photos.photo); page++; if(page <= d.photos.pages) { $('#page').attr('data-page', page); } $(settings.loading_id).hide(); }); } else { $(settings.load_button).hide(); } } if(settings.init_load) { data_load(); } $(settings.load_button).click(function() { data_load(); }); $(window).scroll(function(){ if ($(document).height() - $(this).scrollTop() - $(this).height()<settings.distance) { data_load(); } }); }, nano: function(data) { // from https://github.com/trix/nano.git return $(this).html().replace(/\{([\w\.]*)\}/g, function(str, key) { var keys = key.split("."), v = data[keys.shift()]; for (var i = 0, l = keys.length; i < l; i++) v = v[keys[i]]; return (typeof v !== "undefined" && v !== null) ? v : ""; }); } }); })(jQuery);
const buildMonorepoIndex = require('./build-monorepo-index'); const glob = require('glob'); const path = require('path'); const fs = require('fs'); const publishUtils = require('./utils'); const shell = require('shelljs'); function buildStorybook(currentPackage, outputDirectory, npmScriptName) { console.log(`=> Building storybook for: ${currentPackage.name}`); // clear and re-create the out directory shell.rm('-rf', outputDirectory); shell.mkdir(outputDirectory); if (currentPackage.scripts[npmScriptName]) { publishUtils.exec(`npm run ${npmScriptName} -- -o ${outputDirectory}`); } else { publishUtils.exec(`build-storybook -o ${outputDirectory}`); } } function buildSubPackage(origDir, dir, outputDirectory, npmScriptName) { shell.cd(dir); if (!fs.existsSync('package.json')) { return; } const subPackage = JSON.parse( fs.readFileSync(path.resolve('package.json'), 'utf8') ); if ( !fs.existsSync('.storybook') && (!subPackage.scripts || !subPackage.scripts[npmScriptName]) ) { return; } buildStorybook(subPackage, outputDirectory, npmScriptName); const builtStorybook = path.join(dir, outputDirectory, '*'); const outputPath = path.join(origDir, outputDirectory, subPackage.name); shell.mkdir('-p', outputPath); shell.cp('-r', builtStorybook, outputPath); shell.rm('-rf', builtStorybook); return subPackage; } module.exports = function( skipBuild, outputDirectory, packageJson, packagesDirectory, npmScriptName, monorepoIndexGenerator ) { if (skipBuild) { return; } if (packagesDirectory) { const origDir = process.cwd(); const packages = glob .sync(path.join(origDir, packagesDirectory, '**/package.json'), { ignore: '**/node_modules/**' }) .map(path.dirname) .map(subPackage => buildSubPackage(origDir, subPackage, outputDirectory, npmScriptName) ) .filter(subPackage => subPackage); shell.cd(origDir); buildMonorepoIndex(packages, monorepoIndexGenerator, outputDirectory); } else { buildStorybook(packageJson, outputDirectory, npmScriptName); } };
import React from 'react'; import { Card, Button, CardHeader, CardFooter, CardBody, CardTitle, CardText } from 'reactstrap'; const Example = (props) => { return ( <div> <Card> <CardHeader>Header</CardHeader> <CardBody> <CardTitle tag="h5">Special Title Treatment</CardTitle> <CardText>With supporting text below as a natural lead-in to additional content.</CardText> <Button>Go somewhere</Button> </CardBody> <CardFooter>Footer</CardFooter> </Card> <Card> <CardHeader tag="h3">Featured</CardHeader> <CardBody> <CardTitle tag="h5">Special Title Treatment</CardTitle> <CardText>With supporting text below as a natural lead-in to additional content.</CardText> <Button>Go somewhere</Button> </CardBody> <CardFooter className="text-muted">Footer</CardFooter> </Card> </div> ); }; export default Example;
import Hook from 'util/hook' import genSchema from './gensrc/schema' import genResolver from './gensrc/resolver' import {deepMergeToFirst} from 'util/deepMerge' // Hook to add mongodb resolver Hook.on('resolver', ({db, resolvers}) => { deepMergeToFirst(resolvers, genResolver(db)) }) // Hook to add mongodb schema Hook.on('schema', ({schemas}) => { schemas.push(genSchema) })
var express = require('express'), app = express(); var port = 8000; app.use(express.static(__dirname + '/dist')); console.log('listening on port: ' + port); app.listen(port)
/* https://developer.github.com/v3/media/ http://tools.ietf.org/html/rfc4288#section-3.2 Example: application/vnd.<company>[.version].param[+json] */ // Load libraries const Joi = require('joi'); // Declare internals const internals = { schema: Joi.object({ vendor: Joi.string().required(), defaultVersion: Joi.number().positive().required() }) }; exports.register = function (server, options, next) { const regex = new RegExp(`^application\\/vnd\\.${options.vendor}\\.v(\\d+)`); options = Joi.attempt(options, internals.schema, 'Plugin options do not match schema'); server.ext('onPreHandler', internals.onPreHandler.bind(null, regex, options)); server.ext('onPreResponse', internals.onPreResponse.bind(null, options)); return next(); }; internals.onPreHandler = (regex, options, request, reply) => { const acceptHeader = request.headers.accept; const match = acceptHeader ? acceptHeader.match(regex) : null; const apiVersion = match ? parseInt(match[1], 10) : options.defaultVersion; request.pre.apiVersion = apiVersion; return reply.continue(); }; internals.onPreResponse = (options, request, reply) => { const response = request.response; if (!response.isBoom) { request.response.header(`X-${options.vendor}-Media-Type`, `${options.vendor}.v${request.pre.apiVersion};`); } reply.continue(); }; exports.register.attributes = { pkg: require('../package.json') };
/* global it */ 'use strict'; var runBenchmark = require('./common').runBenchmark; var dataSizes = [5, 10, 20, 50, 100, 500, 1000, 2000, 5000, 10000, 100000, 1000000]; var bindingsCount = [5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]; var PAGE_URL = 'http://localhost:8080'; var benchmarks = [ function (bindingsCount, dataSize, done) { runBenchmark({ url: PAGE_URL, description: 'should run standard update benchmarks', id: 'standard-' + dataSize + '-' + bindingsCount, buttons: ['#update-standard-btn'], params: { bindingsCount: bindingsCount, dataSize: dataSize, dataType: 'standard', testType: 'update', }, log: './log' }, done); }, function (bindingsCount, dataSize, done) { runBenchmark({ url: PAGE_URL, description: 'should run immutable update benchmarks', id: 'immutable-' + dataSize + '-' + bindingsCount, buttons: ['#update-immutable-btn'], params: { bindingsCount: bindingsCount, dataSize: dataSize, dataType: 'immutable', testType: 'update', }, log: './log' }, done); }, function (bindingsCount, dataSize, done) { runBenchmark({ url: PAGE_URL, description: 'should run revisionable update benchmarks', id: 'revisionable-' + dataSize + '-' + bindingsCount, buttons: ['#update-revisionable-btn'], params: { bindingsCount: bindingsCount, dataSize: dataSize, dataType: 'revisionable', testType: 'update', }, log: './log' }, done); } ]; var product = []; for (var s = 0; s < dataSizes.length; s += 1) { for (var c = 0; c < bindingsCount.length; c += 1) { product.push({ dataSize: dataSizes[s], bindingsCount: bindingsCount[c] }); } } product.forEach(function (data) { benchmarks.forEach(function (b) { it('should work wow', function (done) { b(data.bindingsCount, data.dataSize, done); }); }); });
var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('To quarters four hallo\n'); }).listen(8888, '127.0.0.1'); console.log('Server running at http://127.0.0.1:8888/');
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/build/js"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 18); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _nonterminal = __webpack_require__(7); var _nonterminal2 = _interopRequireDefault(_nonterminal); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var NonterminalFactory = function () { function NonterminalFactory(grammarObject) { _classCallCheck(this, NonterminalFactory); this.grammarObject = grammarObject; this.nonterminals = []; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = grammarObject[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var grammarRule = _step.value; var nonterminal = new _nonterminal2.default(grammarRule[0], grammarRule[1]); if (grammarRule.length > 2) // it has an array of lookaheadTokensToAvoid { nonterminal.lookaheadTokensToAvoid = grammarRule[2]; } this.nonterminals.push(nonterminal); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } } _createClass(NonterminalFactory, [{ key: 'getNonterminals', value: function getNonterminals() { return this.nonterminals; } }]); return NonterminalFactory; }(); exports.default = NonterminalFactory; /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _token = __webpack_require__(8); var _token2 = _interopRequireDefault(_token); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var TokenFactory = function () { function TokenFactory(tokenDefinitions) { _classCallCheck(this, TokenFactory); this.tokens = []; this.tokenDefinitions = tokenDefinitions; } _createClass(TokenFactory, [{ key: "makeTokenFromDefinition", value: function makeTokenFromDefinition(tokenDefinition) { return this.makeToken(tokenDefinition[0], tokenDefinition[1], tokenDefinition.length > 2 ? tokenDefinition[2] : false); } }, { key: "makeToken", value: function makeToken(regex, name) { var ignore = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var token = new _token2.default(regex, name, 0, "", ignore); this.tokens.push(token); return token; } }, { key: "getTokens", value: function getTokens() { var IGNORE = true; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = this.tokenDefinitions[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var tokenDefinition = _step.value; this.makeTokenFromDefinition(tokenDefinition); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return this.tokens; } }]); return TokenFactory; }(); exports.default = TokenFactory; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _tokenfactory = __webpack_require__(1); var _tokenfactory2 = _interopRequireDefault(_tokenfactory); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Lexer = function () { function Lexer(tokenDefinitions) { _classCallCheck(this, Lexer); var tokenFactory = new _tokenfactory2.default(tokenDefinitions); this.tokens = tokenFactory.getTokens(); } _createClass(Lexer, [{ key: "tokenize", value: function tokenize(sentenceToTokenize) { var arrayOfTokens = []; var startingLetter = 0; var stringToMatch = sentenceToTokenize; // want to keep original sentence for length/reference while (startingLetter < sentenceToTokenize.length) { var foundAMatchSomewhere = false; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = this.tokens[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var token = _step.value; var lengthOfMatch = 0; var _token$matchYourselfT = token.matchYourselfToStartOfThisStringAndAddSelfToArray(arrayOfTokens, stringToMatch, startingLetter); var _token$matchYourselfT2 = _slicedToArray(_token$matchYourselfT, 3); lengthOfMatch = _token$matchYourselfT2[0]; arrayOfTokens = _token$matchYourselfT2[1]; stringToMatch = _token$matchYourselfT2[2]; if (lengthOfMatch > 0) { foundAMatchSomewhere = true; startingLetter += lengthOfMatch; break; // START AT THE TOP OF OUR TOKEN LIST!! // That is IMPORTANT. // Some of our later tokens, like IDENT, are catch-alls that will greedily snatch up keywords like NOT } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } if (!foundAMatchSomewhere) { throw new Error("Illegal character " + stringToMatch.charAt(0) + " at position " + startingLetter); } } return arrayOfTokens; } }]); return Lexer; }(); exports.default = Lexer; /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _symbol = __webpack_require__(4); var _symbol2 = _interopRequireDefault(_symbol); var _nonterminal = __webpack_require__(7); var _nonterminal2 = _interopRequireDefault(_nonterminal); var _nonterminalfactory = __webpack_require__(0); var _nonterminalfactory2 = _interopRequireDefault(_nonterminalfactory); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Parser = function () { function Parser(grammarObject) { _classCallCheck(this, Parser); var nonterminalFactory = new _nonterminalfactory2.default(grammarObject); this.nonterminals = nonterminalFactory.getNonterminals(); this.state = {}; } _createClass(Parser, [{ key: 'setState', value: function setState(state) { this.state = state; // generally just a lookup table for declared/initialized variables } // What does this do? Well, if there's a token of type IDENT, it's a variable. // If that variable hasn't been declared, then how are we supposed to know what type it is? // We'll be strongly-typed so that even a simple grammar can work effectively. }, { key: 'resolveIdentifiersToTypes', value: function resolveIdentifiersToTypes(sentenceOfSymbols) { var resolvedSymbols = []; while (sentenceOfSymbols.length > 0) { // comments might have been turned into null symbols // in which case we should skip them var symbol = sentenceOfSymbols.shift(); // we only care about tokens if (symbol.constructor.name == "Token") { if (symbol.type == "IDENT") { // so now we can wrap our variable in the appropriate nonterminal type if (typeof this.state[symbol._stringIMatched] == "boolean") { var nonterm = new _nonterminal2.default(["IDENT"], "BOOLEAN"); nonterm.seriesOfSymbolsIAbsorbedAndReplaced = [symbol]; symbol = nonterm; } resolvedSymbols.push(symbol); continue; } else { resolvedSymbols.push(symbol); } } else { resolvedSymbols.push(symbol); } } return resolvedSymbols; } }, { key: 'getSimpleStringForSentence', value: function getSimpleStringForSentence(sentenceOfSymbols) { var traceString = ""; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = sentenceOfSymbols[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var symbol = _step.value; traceString += symbol.type + " "; } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return traceString; } }, { key: 'parse', value: function parse(sentenceOfSymbols) { var parseTimeVisitor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; sentenceOfSymbols = this.resolveIdentifiersToTypes(sentenceOfSymbols); var arrayOfSymbolsMatchedBeforeMe = []; var lengthOfMatch = 0; var finished = false; // actually, if our sentence only has one symbol, it may very well be finished already if (sentenceOfSymbols.length == 1) finished = true; while (!finished) { var madeAMatch = false; //console.log("============"); var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = this.nonterminals[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var nonterminal = _step2.value; // we'll go through the input sentence // and try to match this nonterminal to the beginning of it. // if there's a match, then our nonterminal will be part of the future sentence. // (replacing whatever portion it matched.) // if there's no match, we want to pop a symbol off the start of the input sentence // (moving it into the future sentence, since we ) var traceString = this.getSimpleStringForSentence(sentenceOfSymbols); while (sentenceOfSymbols.length > 0) { // if we matched, then the good news is, the input sentence is now changed // so we don't have to worry about changing it. // otherwise, we didn't match the beginning of the input sentence, // so let's pop a symbol off it and try again. var _nonterminal$matchYou = nonterminal.matchYourselfToStartOfThisStringAndAddSelfToArray(arrayOfSymbolsMatchedBeforeMe, sentenceOfSymbols, parseTimeVisitor); // console.log("USING nonterminal " + nonterminal.toStringSimple() + " to look at " + traceString ); var _nonterminal$matchYou2 = _slicedToArray(_nonterminal$matchYou, 3); lengthOfMatch = _nonterminal$matchYou2[0]; arrayOfSymbolsMatchedBeforeMe = _nonterminal$matchYou2[1]; sentenceOfSymbols = _nonterminal$matchYou2[2]; if (lengthOfMatch == 0) { arrayOfSymbolsMatchedBeforeMe.push(sentenceOfSymbols.shift()); traceString = this.getSimpleStringForSentence(sentenceOfSymbols); } else { //console.log("MATCHED nonterminal " + nonterminal.toStringSimple() + " to sentence " + traceString ); madeAMatch = true; } } // ok, we did what we could. let's gather our processed items and hand them to the next nonterminal to process. sentenceOfSymbols = arrayOfSymbolsMatchedBeforeMe.slice(0); // make sure we copy the items over and keep these two arrays discrete! arrayOfSymbolsMatchedBeforeMe = []; //console.log("sentenceOfSymbols is now " + sentenceOfSymbols ); // are we done? if so, then don't bother looking at other nonterminals! if (sentenceOfSymbols.length <= 1) { finished == true; break; } // we need to start from the top of our nonterminals if we made a match! // order MATTERS. if (madeAMatch) break; } // end of cycling through our array of nonterminals // what if we made it through all our nonterminals and didn't make a match? // error, that's what! } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2.return) { _iterator2.return(); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } if (!madeAMatch) { var stringAndPosition = this.getLastTokenDescriptionOfSymbol(sentenceOfSymbols[0]); var errorString = "\nSyntax error:" + stringAndPosition.string + " at position " + stringAndPosition.position; throw new Error(errorString); finished = true; } if (sentenceOfSymbols.length <= 1) { finished = true; } } // end of our "while" loop going through sentenceOfSymbols until finished == true return sentenceOfSymbols; } }, { key: 'getLastTokenDescriptionOfSymbol', value: function getLastTokenDescriptionOfSymbol(symbol) { return this.getStringAndPositionOfTokensOfSymbol(symbol.symbolsMatched[symbol.symbolsMatched.length - 1]); } }, { key: 'getStringAndPositionOfTokensOfSymbol', value: function getStringAndPositionOfTokensOfSymbol(symbol) { var earliestPosition = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100000000; if (symbol.constructor.name == "Token") { return { string: symbol._stringIMatched, position: symbol.start }; } else if (symbol.constructor.name == "Nonterminal") { var tokenString = ""; var _iteratorNormalCompletion3 = true; var _didIteratorError3 = false; var _iteratorError3 = undefined; try { for (var _iterator3 = symbol.symbolsMatched[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { var kid = _step3.value; var stringAndPosition = this.getStringAndPositionOfTokensOfSymbol(kid, earliestPosition); tokenString += stringAndPosition.string; if (stringAndPosition.position < earliestPosition) { earliestPosition = stringAndPosition.position; } } } catch (err) { _didIteratorError3 = true; _iteratorError3 = err; } finally { try { if (!_iteratorNormalCompletion3 && _iterator3.return) { _iterator3.return(); } } finally { if (_didIteratorError3) { throw _iteratorError3; } } } return { string: tokenString, position: earliestPosition }; } } }]); return Parser; }(); exports.default = Parser; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _Symbol = function () { function _Symbol() { _classCallCheck(this, _Symbol); } _createClass(_Symbol, [{ key: "name", get: function get() { return this._name; }, set: function set(someName) { this._name = someName; } }]); return _Symbol; }(); exports.default = _Symbol; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Boolius = undefined; 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; }; }(); //import Token from './token'; //import Symbol from './token'; var _lexer = __webpack_require__(2); var _lexer2 = _interopRequireDefault(_lexer); var _parser = __webpack_require__(3); var _parser2 = _interopRequireDefault(_parser); var _xmlius = __webpack_require__(11); var _xmlius2 = _interopRequireDefault(_xmlius); var _mathius = __webpack_require__(6); var _mathius2 = _interopRequireDefault(_mathius); var _booleanjsonvisitor = __webpack_require__(13); var _booleanjsonvisitor2 = _interopRequireDefault(_booleanjsonvisitor); var _tokenfactory = __webpack_require__(1); var _tokenfactory2 = _interopRequireDefault(_tokenfactory); var _nonterminalfactory = __webpack_require__(0); var _nonterminalfactory2 = _interopRequireDefault(_nonterminalfactory); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Boolius = exports.Boolius = function () { function Boolius(tokenDefinitions, grammarObject) { _classCallCheck(this, Boolius); // we set the state so that the parser knows the data type of each of these variables // (in this case, boolean) // and later so that the visitor can evaluate each node to determine if it is true or false. this.state = { "a": false, "b": true, "c": false, "d": true, "e": false, "f": true, "g": false, "h": true, "i": false }; this.visitor = new _booleanjsonvisitor2.default(this.state); // lay the groundwork for lexical analysis this.lexer = new _lexer2.default(tokenDefinitions); this.parser = new _parser2.default(grammarObject); this.parser.setState(this.state); } _createClass(Boolius, [{ key: 'parse', value: function parse(sentenceToParse) { try { var sentenceOfTokens = this.lexer.tokenize(sentenceToParse); this.parseTree = this.parser.parse(sentenceOfTokens); return this.evaluateParseTree(); } catch (e) { alert(e); } } }, { key: 'evaluateParseTree', value: function evaluateParseTree() { var result = this.parseTree[0].visit(this.visitor); return result; } }]); return Boolius; }(); //window.Boolius = Boolius; module.exports = Boolius; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); //import Token from './token'; //import Symbol from './token'; var _lexer = __webpack_require__(2); var _lexer2 = _interopRequireDefault(_lexer); var _parser = __webpack_require__(3); var _parser2 = _interopRequireDefault(_parser); var _numericvisitor = __webpack_require__(10); var _numericvisitor2 = _interopRequireDefault(_numericvisitor); var _mathjsonvisitor = __webpack_require__(15); var _mathjsonvisitor2 = _interopRequireDefault(_mathjsonvisitor); var _tokenfactory = __webpack_require__(1); var _tokenfactory2 = _interopRequireDefault(_tokenfactory); var _nonterminalfactory = __webpack_require__(0); var _nonterminalfactory2 = _interopRequireDefault(_nonterminalfactory); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Mathius = function () { function Mathius(tokenDefinitions, grammarObject) { _classCallCheck(this, Mathius); // we set the state so that the parser knows the data type of each of these variables // (in this case, boolean) // and later so that the visitor can evaluate each node to determine if it is true or false. this.state = { "a": false, "b": true, "c": false, "d": true, "e": false, "f": true, "g": false, "h": true, "i": false }; this.visitor = new _mathjsonvisitor2.default(this.state); // lay the groundwork for lexical analysis this.lexer = new _lexer2.default(tokenDefinitions); this.parser = new _parser2.default(grammarObject); this.parser.setState(this.state); } _createClass(Mathius, [{ key: 'parse', value: function parse(sentenceToParse) { try { var sentenceOfTokens = this.lexer.tokenize(sentenceToParse); this.parseTree = this.parser.parse(sentenceOfTokens); return this.evaluateParseTree(); } catch (e) { console.error("ERROR PARSING OR EVALUATING:" + e); } } }, { key: 'evaluateParseTree', value: function evaluateParseTree() { var result = this.parseTree[0].visit(this.visitor); return result; } }]); return Mathius; }(); exports.default = Mathius; /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _symbol = __webpack_require__(4); var _symbol2 = _interopRequireDefault(_symbol); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Nonterminal = function (_Symbol2) { _inherits(Nonterminal, _Symbol2); function Nonterminal(seriesOfSymbolsIMustMatch, type) { _classCallCheck(this, Nonterminal); var _this = _possibleConstructorReturn(this, (Nonterminal.__proto__ || Object.getPrototypeOf(Nonterminal)).call(this)); _this.seriesOfSymbolsIMustMatch = seriesOfSymbolsIMustMatch; _this.type = type; _this.seriesOfSymbolsIAbsorbedAndReplaced = []; _this.wildcardMode = false; _this.lookaheadTokensToAvoid = null; return _this; } _createClass(Nonterminal, [{ key: 'toStringSimple', value: function toStringSimple() { return this.type + "(" + this.seriesOfSymbolsIMustMatch.join(' ') + ")"; } }, { key: 'toString', value: function toString() { var returnString = this.type + " ("; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = this.seriesOfSymbolsIAbsorbedAndReplaced[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var symbol = _step.value; returnString += " " + symbol.toString(); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return returnString; } }, { key: 'visit', value: function visit(evaluationVisitor) { return evaluationVisitor.execute(this); } }, { key: 'matchYourselfToStartOfThisStringAndAddSelfToArray', value: function matchYourselfToStartOfThisStringAndAddSelfToArray(arrayOfSymbolsMatchedBeforeMe, sentenceOfSymbolsToMatch, parseTimeVisitor) { // clone it so we don't destroy the original in case we're only a partial match var sentenceOfSymbolsToMatchClone = sentenceOfSymbolsToMatch.slice(0); // same with ours var seriesOfSymbolsIMustMatchClone = this.seriesOfSymbolsIMustMatch.slice(0); this.seriesOfSymbolsIAbsorbedAndReplaced = []; var done = false; // in case of wildcard, we need to know what the previous symbol was var symbolThatBreaksWildcard = null; while (seriesOfSymbolsIMustMatchClone.length > 0) { var mySymbol = seriesOfSymbolsIMustMatchClone.shift(); var theirSymbol = sentenceOfSymbolsToMatchClone.shift(); // if they ran out of symbols, then we're obviously not a match. UNLESS we were in wildcard mode. if (!theirSymbol) { this.seriesOfSymbolsIAbsorbedAndReplaced = []; return [0, arrayOfSymbolsMatchedBeforeMe, sentenceOfSymbolsToMatch]; } if (mySymbol == "WILDCARD") { this.wildcardMode = true; symbolThatBreaksWildcard = seriesOfSymbolsIMustMatchClone.shift(); while (theirSymbol.type != symbolThatBreaksWildcard) { this.seriesOfSymbolsIAbsorbedAndReplaced.push(theirSymbol); if (sentenceOfSymbolsToMatchClone.length == 0) // they ran out of symbols in their sentence! { if (seriesOfSymbolsIMustMatchClone.length == 0) // that wildcard was my last character { arrayOfSymbolsMatchedBeforeMe.push(this.getFrozenClone()); return [this.length, arrayOfSymbolsMatchedBeforeMe, sentenceOfSymbolsToMatchClone]; } else // failure -- we had more to match but they ran out first { this.seriesOfSymbolsIAbsorbedAndReplaced = []; return [0, arrayOfSymbolsMatchedBeforeMe, sentenceOfSymbolsToMatch]; } } else { theirSymbol = sentenceOfSymbolsToMatchClone.shift(); } } //end of tight loop inside wildcard mode, but still in wildcard mode // absorb the one that got us out of the wildcard // i.e., it matched the symbol of ours that follows (and thus ends) the wildcard this.seriesOfSymbolsIAbsorbedAndReplaced.push(theirSymbol); // we made it through! // if that was the last one, then we should skip the rest of the matching and go right to success // if not, keep the process going -- get a new symbol from them if (seriesOfSymbolsIMustMatchClone.length == 0) // we don't have any more { done = true; } else if (sentenceOfSymbolsToMatchClone.length > 0) // we have more, and they have more things that need matching { theirSymbol = sentenceOfSymbolsToMatchClone.shift(); // but if our wildcard was our last character, then we should leave } else // we have more, but they don't! { this.seriesOfSymbolsIAbsorbedAndReplaced = []; return [0, arrayOfSymbolsMatchedBeforeMe, sentenceOfSymbolsToMatch]; } } // end of wildcard loop if (!done) { // do they match? i.e., the next character in the sentence -- does it match the next symbol in my internal list? if (theirSymbol.type != mySymbol) { return [0, arrayOfSymbolsMatchedBeforeMe, sentenceOfSymbolsToMatch]; } else { this.seriesOfSymbolsIAbsorbedAndReplaced.push(theirSymbol); } } } // bottom of seriesOfSymbolsIMustMatchClone.length loop // we made it through -- matched everything we needed to -- but maybe there's a problem after all... // now, there's an edge case -- good for operator precedence enforcement // -- the lookahead tokens. // maybe we matched everything we needed, and that's great, // but maybe the next token in the sentence is a dealbreaker! // for example, 1 + 2 * 3 // if we're NUMERIC + NUMERIC, we'll find a match // but that is wrong! because the next token *after* our possible match is a * // and that has higher precedence than + if (this.lookaheadTokensToAvoid) { if (sentenceOfSymbolsToMatchClone.length > 0) { var theirNextSymbol = sentenceOfSymbolsToMatchClone[0]; if (this.lookaheadTokensToAvoid.indexOf(theirNextSymbol.type) > -1) { return [0, arrayOfSymbolsMatchedBeforeMe, sentenceOfSymbolsToMatch]; } } } // we made it here! must be a basically perfect match. // but let's see if there's a context stack for this parser // e.g., an XML parser keeps a stack of open nodes // so that when you hit a closing tag for a node // the parser can know if it's the most recently opened tag if (!parseTimeVisitor || parseTimeVisitor.execute(this)) { arrayOfSymbolsMatchedBeforeMe.push(this.getFrozenClone()); return [this.length, arrayOfSymbolsMatchedBeforeMe, sentenceOfSymbolsToMatchClone]; } else { return [0, arrayOfSymbolsMatchedBeforeMe, sentenceOfSymbolsToMatch]; } } }, { key: 'getFrozenClone', value: function getFrozenClone() { var frozenClone = new Nonterminal(this.seriesOfSymbolsIMustMatch, this.type); frozenClone.seriesOfSymbolsIAbsorbedAndReplaced = this.seriesOfSymbolsIAbsorbedAndReplaced; return frozenClone; } }, { key: 'symbolsMatched', get: function get() { return this.seriesOfSymbolsIAbsorbedAndReplaced; } }, { key: 'length', get: function get() { return this.seriesOfSymbolsIAbsorbedAndReplaced.length; } }]); return Nonterminal; }(_symbol2.default); exports.default = Nonterminal; /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _symbol = __webpack_require__(4); var _symbol2 = _interopRequireDefault(_symbol); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Token = function (_Symbol2) { _inherits(Token, _Symbol2); /*** * We are one of the two types of Symbol this parser deals with: * Tokens and Nonterminals. * A Token is basically a Symbol that contains one or more string characters. * A Nonterminal is basically a Symbol that contains one or more Symbols * (each of which can be either a Token or a Nonterminal). * * First argument will be a regex that will match some of the raw input stream. * Second argument will be the internal representation I will use for myself * (a string). * */ function Token(regexOfThingsIMustMatch, type, leng, stringIActuallyMatched, ignore) { var startIndex = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : -1; _classCallCheck(this, Token); var _this = _possibleConstructorReturn(this, (Token.__proto__ || Object.getPrototypeOf(Token)).call(this)); _this.regexOfThingsIMustMatch = regexOfThingsIMustMatch; _this._type = type; _this.start = startIndex; _this._length = leng ? leng : 0; _this._stringIMatched = stringIActuallyMatched; _this._ignore = ignore; return _this; } _createClass(Token, [{ key: "toStringSimple", value: function toStringSimple() { return " " + this._type + " "; } }, { key: "visit", value: function visit(evaluationVisitor) { return evaluationVisitor.execute(this); } }, { key: "matchYourselfToStartOfThisStringAndAddSelfToArray", value: function matchYourselfToStartOfThisStringAndAddSelfToArray(symbolArray, stringToMatch, startingIndex) { this._length = 0; var match = this.regexOfThingsIMustMatch.exec(stringToMatch); if (match != null && match.index == 0) { this._length = match[0].length; // a frozen clone to record this moment, // so that our data can go on to be reused without breaking things var frozenToken = new Token(this.regexOfThingsIMustMatch, this.type, this._length, match[0], this._ignore, startingIndex); if (!this._ignore) symbolArray.push(frozenToken); stringToMatch = stringToMatch.substring(this.length); } return [this._length, symbolArray, stringToMatch]; } }, { key: "toString", value: function toString() { return this.type + "(" + this.regexOfThingsIMustMatch.toString() + ")<" + this._stringIMatched + "." + this.start + ">"; } }, { key: "type", get: function get() { return this._type; } }, { key: "length", get: function get() { return this._length; } }]); return Token; }(_symbol2.default); exports.default = Token; /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { "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; }; }(); var _booleanvisitor = __webpack_require__(14); var _booleanvisitor2 = _interopRequireDefault(_booleanvisitor); var _numericvisitor = __webpack_require__(10); var _numericvisitor2 = _interopRequireDefault(_numericvisitor); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var EvaluationVisitor = function () { function EvaluationVisitor(state) { _classCallCheck(this, EvaluationVisitor); this.state = state; this.booleanVisitor = new _booleanvisitor2.default(state); this.numericVisitor = new _numericvisitor2.default(state); } _createClass(EvaluationVisitor, [{ key: 'setState', value: function setState(newstate) { this.state = newstate; this.booleanVisitor.setState(newstate); this.numericVisitor.setState(newstate); } }, { key: 'execute', value: function execute(nonterminalOrToken) { if (nonterminalOrToken.constructor.name == "Nonterminal") { if (nonterminalOrToken.type == "BOOLEAN") return this.booleanVisitor.execute(nonterminalOrToken); if (nonterminalOrToken.type == "NUMERIC") return this.numericVisitor.execute(nonterminalOrToken); } else // it's a token { if (nonterminalOrToken.type.toUpperCase().indexOf("TRUE") > -1) { return true; } if (nonterminalOrToken.type.toUpperCase().indexOf("FALSE") > -1) { return false; } throw new Error("nonterminalOrToken.type is " + nonterminalOrToken.type); return null; } } }]); return EvaluationVisitor; }(); module.exports = EvaluationVisitor; /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { "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; }; }(); var _evaluationvisitor = __webpack_require__(9); var _evaluationvisitor2 = _interopRequireDefault(_evaluationvisitor); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var NumericVisitor = function () { function NumericVisitor(state) { _classCallCheck(this, NumericVisitor); this.state = state; } _createClass(NumericVisitor, [{ key: "setState", value: function setState(newstate) { this.state = newstate; } }, { key: "execute", value: function execute(nonterminalOrToken) { if (nonterminalOrToken.constructor.name == "Nonterminal") { var symbolsMatched = nonterminalOrToken.seriesOfSymbolsIAbsorbedAndReplaced; var value = "FOO"; // declare this and, hey, initialize it with something we'll notice if there's an error. if (symbolsMatched.length == 1) // we're a nonterminal that absorbed one other thing { value = symbolsMatched[0].visit(this); return value; } else if (symbolsMatched.length == 3) // we're a boolean comprising an operator and two operands { // or maybe we're just a numeric wrapped in parens! if (symbolsMatched[0].type == "(" && symbolsMatched[2].type == ")") { return symbolsMatched[1].visit(this); } if (symbolsMatched[1].type == "+") { return symbolsMatched[0].visit(this) + symbolsMatched[2].visit(this); } else if (symbolsMatched[1].type == "-") { return symbolsMatched[0].visit(this) - symbolsMatched[2].visit(this); } else if (symbolsMatched[1].type == "*") { return symbolsMatched[0].visit(this) * symbolsMatched[2].visit(this); } else if (symbolsMatched[1].type == "/") { return symbolsMatched[0].visit(this) / symbolsMatched[2].visit(this); } else if (symbolsMatched[1].type == "^") { return Math.pow(symbolsMatched[0].visit(this), symbolsMatched[2].visit(this)); } else { throw new Error("WE HAVE 3 SYMBOLS BUT I DON'T KNOW WHAT THIS IS:" + JSON.stringify(symbolsMatched)); } } else if (symbolsMatched.length == 2) // we're a boolean with one operator -- probably a not { if (symbolsMatched[0].type == "+") { return symbolsMatched[1].visit(this); } if (symbolsMatched[0].type == "-") { return -1 * symbolsMatched[1].visit(this); } else { throw new Error("IN NUMERICVISITOR, DON'T KNOW WHAT THE OPERATOR OF THIS 2-ELEMENT SYMBOLSMATCHED IS:" + JSON.stringify(symbolsMatched)); } } throw new Error("UNKNOWN LENGTH OF SYMBOLSMATCHED:" + JSON.stringify(symbolsMatched)); } else // it's a token { if (nonterminalOrToken.type.toUpperCase().indexOf("NUM_LIT") > -1) { return parseInt(nonterminalOrToken._stringIMatched); } throw new Error("nonterminalOrToken.type is " + nonterminalOrToken.type); return null; } } }]); return NumericVisitor; }(); module.exports = NumericVisitor; /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); //import Token from './token'; //import Symbol from './token'; var _lexer = __webpack_require__(2); var _lexer2 = _interopRequireDefault(_lexer); var _parser = __webpack_require__(3); var _parser2 = _interopRequireDefault(_parser); var _xmlparsetimevisitor = __webpack_require__(17); var _xmlparsetimevisitor2 = _interopRequireDefault(_xmlparsetimevisitor); var _xmljsonvisitor = __webpack_require__(16); var _xmljsonvisitor2 = _interopRequireDefault(_xmljsonvisitor); var _tokenfactory = __webpack_require__(1); var _tokenfactory2 = _interopRequireDefault(_tokenfactory); var _nonterminalfactory = __webpack_require__(0); var _nonterminalfactory2 = _interopRequireDefault(_nonterminalfactory); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var XMLius = function () { function XMLius(tokenDefinitions, grammarObject) { _classCallCheck(this, XMLius); // we set the state so that the parser knows the data type of each of these variables // (in this case, boolean) // and later so that the visitor can evaluate each node to determine if it is true or false. this.state = {}; this.xmlParseTimeVisitor = new _xmlparsetimevisitor2.default(); this.visitor = new _xmljsonvisitor2.default(this.state); // lay the groundwork for lexical analysis this.lexer = new _lexer2.default(tokenDefinitions); this.parser = new _parser2.default(grammarObject); this.parser.setState(this.state); } _createClass(XMLius, [{ key: 'parse', value: function parse(sentenceToParse) { try { var sentenceOfTokens = this.lexer.tokenize(sentenceToParse); this.parser.setState(this.state); this.parseTree = this.parser.parse(sentenceOfTokens, this.xmlParseTimeVisitor); return this.evaluateParseTree(); } catch (e) { console.error("ERROR PARSING OR EVALUATING:" + e); } } }, { key: 'evaluateParseTree', value: function evaluateParseTree() { var result = this.parseTree[0].visit(this.visitor); return result; } }]); return XMLius; }(); exports.default = XMLius; /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _boolius = __webpack_require__(5); var _boolius2 = _interopRequireDefault(_boolius); var _xmlius = __webpack_require__(11); var _xmlius2 = _interopRequireDefault(_xmlius); var _mathius = __webpack_require__(6); var _mathius2 = _interopRequireDefault(_mathius); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // which in turn imports all the classes it depends upon window.onload = function () { d3.select('#modeSelect').on('change', function (e) { var selectedMode = d3.select('#modeSelect').node().value.toLowerCase(); changeMode(selectedMode); }); function changeMode(newMode) { if (newMode.indexOf('arithmetic') > -1) { // the user wants to look at arithmetic expressions. // is boolius already loaded? if (!evaluator || evaluator.constructor.name != "Mathius") { var grammarObject = [[["NUMERIC", "^", "NUMERIC"], "NUMERIC"], [["NUMERIC", "*", "NUMERIC"], "NUMERIC"], [["NUMERIC", "+", "NUMERIC"], "NUMERIC", ["*", "/", "^"]], [["NUMERIC", "-", "NUMERIC"], "NUMERIC", ["*", "/", "^"]], [["NUM_LIT"], "NUMERIC"], [["(", "NUMERIC", ")"], "NUMERIC"]]; var IGNORE = true; var tokenDefinitions = [[/\s+/, "", IGNORE], // ignore whitespace [/\^/, "^"], // this is the escaped form of ^ [/\(/, "("], [/\)/, ")"], [/\+/, "+"], [/-/, "-"], [/\*/, "*"], [/\//, "/"], [/[-+]?[0-9]*\.?[0-9]+/, "NUM_LIT"], [/[a-zA-Z]+/, "IDENT"], [/.+/, "DIRTYTEXT"]]; makeEvaluatorAndInitialize(new _mathius2.default(tokenDefinitions, grammarObject), "1 + 2 ^ (5 - 2) * 3", "Click operators to expand or collapse."); } } else if (newMode.indexOf('boolean') > -1) { // the user wants to look at boolean expressions. // is boolius already loaded? if (!evaluator || evaluator.constructor.name != "Boolius") { var grammarObject = [[["TRUE"], "BOOLEAN"], [["FALSE"], "BOOLEAN"], [["!", "BOOLEAN"], "BOOLEAN"], [["BOOLEAN", "&", "BOOLEAN"], "BOOLEAN"], [["BOOLEAN", "|", "BOOLEAN"], "BOOLEAN"], [["(", "BOOLEAN", ")"], "BOOLEAN"]]; var _IGNORE = true; var _tokenDefinitions = [[/\s+/, "", _IGNORE], // ignore whitespace [/&&/, "&"], [/AND/i, "&"], [/\|\|/, "|"], // this is the escaped form of || [/XOR/i, "^"], [/OR/i, "|"], [/\^/, "^"], // this is the escaped form of ^ [/\!/, "!"], // this is the escaped form of ! [/NOT/i, "!"], [/\(/, "("], [/\)/, ")"], [/(true)(?![a-zA-Z0-9])/i, "TRUE"], [/(false)(?![a-zA-Z0-9])/i, "FALSE"], [/[a-zA-Z]+/, "IDENT"], [/.+/, "DIRTYTEXT"]]; makeEvaluatorAndInitialize(new _boolius2.default(_tokenDefinitions, grammarObject), "((d && c)) || (!b && a) && (!d || !a) && (!c || !b)", "Click operators to expand or collapse. Click leaf nodes to toggle true/false."); } } else if (newMode.indexOf('xml') > -1) { // the user wants to look at boolean expressions. // is boolius already loaded? if (!evaluator || evaluator.constructor.name != "XMLius") { var _grammarObject = [[["OPENCOMMENT", "WILDCARD", "CLOSECOMMENT"], "COMMENT"], // comments will be engulfed by the text of a node // and ignored when the node is asked for its text as a string [["COMMENT"], "NODETEXT"], [["<", "/", "IDENT", ">"], "CLOSETAG"], [["<", "IDENT", ">"], "OPENTAG"], [["<", "IDENT", "/", ">"], "XMLNODE"], [["<", "IDENT", "IDENT", "=", "\"", "WILDCARD", "\""], "OPENTAGSTART"], /* Some recursive self-nesting here */ [["OPENTAGSTART", "IDENT", "=", "\"", "WILDCARD", "\""], "OPENTAGSTART"], [["OPENTAGSTART", ">"], "OPENTAG"], // can't have two identifiers in a row, unless we're between an opening and closing tag // a/k/a node.text [["IDENT", "IDENT"], "NODETEXT"], [["IDENT", "NODETEXT"], "NODETEXT"], [["NODETEXT", "NODETEXT"], "NODETEXT"], // let's also have nested nodes engulfed in the NODETEXT [["XMLNODE", "NODETEXT"], "NODETEXT"], [["XMLNODES", "NODETEXT"], "NODETEXT"], [["NODETEXT", "XMLNODE"], "NODETEXT"], [["NODETEXT", "XMLNODES"], "NODETEXT"], [["OPENTAG", "CLOSETAG"], "XMLNODE"], [["OPENTAG", "NODETEXT", "CLOSETAG"], "XMLNODE"], [["OPENTAG", "XMLNODE", "CLOSETAG"], "XMLNODE"], [["XMLNODE", "XMLNODE"], "XMLNODES"], [["OPENTAG", "XMLNODES", "CLOSETAG"], "XMLNODE"]]; var _IGNORE2 = true; var _tokenDefinitions2 = [[/\s+/, "", _IGNORE2], [/<!--/, 'OPENCOMMENT'], [/-->/, 'CLOSECOMMENT'], [/\//, "/"], [/>/, ">"], [/</, "<"], [/=/, "="], [/"/, '"'], [/'/, '"'], [/[-+]?[0-9]*\.?[0-9]+/, "NUM_LIT"], [/[a-zA-Z]+[a-zA-Z0-9-]*/, "IDENT"], // having trapped all these things, what's left is nodetext [/[^<]+/, "NODETEXT"]]; makeEvaluatorAndInitialize(new _xmlius2.default(_tokenDefinitions2, _grammarObject), '<div class="hintwrapper"><div class="hint">Click operators to expand or collapse. Click leaf nodes to toggle true/false.</div><div class="styled-select green semi-square" style="bold"></div></div>', "Mouseover nodes to see attributes. Click nodetext to see content."); } } } function makeEvaluatorAndInitialize(newEvaluator, statement, hintText) { assignEvaluator(newEvaluator); d3.select('#statement').node().value = statement; d3.select('div.hint').text(hintText); evaluateStatement(); } function assignEvaluator(newEvaluator) { // don't change if the user wants what they already have if (evaluator && newEvaluator.constructor.name == evaluator.constructor.name) return; evaluator = newEvaluator; } var evaluator; var winHeight = Math.max(600, window.innerHeight); var winWidth = Math.max(1000, window.innerWidth); var m = [0, 120, 140, 120], w = winWidth - m[1] - m[3], h = winHeight - m[0] - m[2], i = 0, root; var tree = d3.layout.tree().size([h, w]); var diagonal = d3.svg.diagonal().projection(function (d) { return [d.y, d.x]; }); var vis = d3.select("#body").append("svg:svg").attr("width", w + m[1] + m[3]).attr("height", h + m[0] + m[2]).append("svg:g").attr("transform", "translate(" + m[3] + "," + m[0] + ")"); vis.append("text").attr("opacity", 1).attr("y", 246).attr("dy", "1.71em").style("font-size", "34px").style("text-anchor", "end").attr("id", "result").text(""); d3.select("#testbutton").on("click", function (e) { evaluateStatement(); }); d3.select("#statement").on("keyup", function () { if (d3.event.keyCode == 13) { d3.select("#testbutton").on("click")(); } }); var parseTree; function evaluateStatement() { var statement = d3.select("#statement").node().value; parseTree = evaluator.parse(statement); displayJSON(parseTree); }; function displayJSON(json) { root = json; root.x0 = h / 2; root.y0 = 0; //d3.select("#statement").val( root.title ); d3.select("#statement").property("value", root.expressionString); d3.select("#result").text(root.value); function toggleAll(d, delay) { if (!delay) delay = 1; if (d.children) { toggle(d); } if (d._children) { toggle(d); } } // Initialize the display to show all nodes. root.children.forEach(toggleAll, 444); update(root); }; // Toggle children. function toggle(d, showOverlay) { if (d == undefined) return; //boolean if (d.value === true || d.value === false) { if (d.children) { // hide the children by moving them into _children d._children = d.children; d.children = null; } else { // bring back the hidden children d.children = d._children; d._children = null; } var hasNoChildren = !d.children && !d._children; if (!hasNoChildren) { // has an array in d.children or d._children // but it might be empty! if (d.children && d.children.length == 0) hasNoChildren = true; if (d._children && d._children.length == 0) hasNoChildren = true; } if (hasNoChildren) // it's a leaf { // toggle true/false if (d.value === true || d.value === false) { d.value = !d.value; //var myInt = parseInt( d.name ); //conditionTruthValues[ myInt ] = d.value; var myVar = d.name; evaluator.state[myVar] = d.value; updateWithoutDeleting(root); } } } else // you clicked something that isn't in a boolean flow { if (showOverlay) { var attributeText = d.attributes ? JSON.stringify(d.attributes) : "None"; if (!d.children && !d._children) // it's a leaf { //showValueOverlay( d.value ); showValueOverlay("Attributes: " + attributeText + "</br>Content: " + d.value); } else //oops, we wanted to collapse this thing { //showValueOverlay( "Attributes: " + attributeText + "</br>Content: " + d.value ); if (d.children) { // hide the children by moving them into _children d._children = d.children; d.children = null; } else { // bring back the hidden children d.children = d._children; d._children = null; } } } } } function showValueOverlay(val) { $('#valueModalText').html(val); $('#valueModal').modal('show'); } function updateWithoutDeleting() { parseTree = evaluator.evaluateParseTree(); updateObjectAndItsChildren(parseTree, root); d3.select("#result").text(root.value); } function updateObjectAndItsChildren(newObjectTemp, rootTemp) { rootTemp.value = newObjectTemp.value; if (!newObjectTemp.children) return; for (var i = 0; i < newObjectTemp.children.length; i++) { if (rootTemp.children) { updateObjectAndItsChildren(newObjectTemp.children[i], rootTemp.children[i]); } else { if (rootTemp._children) { updateObjectAndItsChildren(newObjectTemp.children[i], rootTemp._children[i]); } } } } function update(source) { var duration = d3.event && d3.event.altKey ? 5000 : 500; // Compute the new tree layout. var nodes = tree.nodes(root).reverse(); // Normalize for fixed-depth. // OK -- why is d.y correlated with the horizontal position here??? widthPerNode = 110; var body = d3.select("body"); var svg = body.select("svg"); var widthInPixels = svg.style("width").replace("px", ""); widthInPixels = parseInt(widthInPixels); var widthPerNode = widthInPixels / nodes.length; nodes.forEach(function (d) { d.y = d.depth * widthPerNode; }); d3.select("#result").transition().duration(duration).attr("x", nodes[nodes.length - 1].y - 40).attr("y", function (d) { return nodes[nodes.length - 1].x - 48; }); // Update the nodes… var node = vis.selectAll("g.node").data(nodes, function (d) { return d.id || (d.id = ++i); }); // Enter any new nodes at the parent's previous position. var nodeEnter = node.enter().append("svg:g").attr("class", "node").attr("transform", function (d) { return "translate(" + source.y0 + "," + source.x0 + ")"; }).on("click", function (d) { toggle(d, true);update(d); }).on("mouseover", function (d) { var attributeText = d.attributes ? JSON.stringify(d.attributes) : ""; if (attributeText.length > 0) { showValueOverlay("Attributes: " + attributeText + "</br>Content: " + d.value); } }); nodeEnter.append("svg:circle").attr("r", 1e-6).style("stroke", function (d) { return d.value ? "green" : "red"; }).style("fill", function (d) { return d._children ? "grey" : "#fff"; }); nodeEnter.append("svg:text").attr("x", function (d) { return d.children || d._children ? -1 : 17; }).attr("y", function (d) { return d.children || d._children ? 18 : -1; }).attr("dy", ".35em").attr("text-anchor", function (d) { return d.children || d._children ? "middle" : "left"; }) // .attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; }) .text(function (d) { return d.name; }).style("fill-opacity", 1e-6); // Transition nodes to their new position. var nodeUpdate = node.transition().duration(duration).style("stroke", function (d) { return d.value ? "green" : "red"; }).attr("transform", function (d) { return "translate(" + d.y + "," + d.x + ")"; }); nodeUpdate.select("circle").attr("r", 8.5).style("stroke", function (d) { return d.value ? "green" : "red"; }).style("fill", function (d) { return d._children ? "lightsteelblue" : "#fff"; }); nodeUpdate.select("text").style("fill-opacity", 1); // Transition exiting nodes to the parent's new position. var nodeExit = node.exit().transition().duration(duration).attr("transform", function (d) { return "translate(" + source.y + "," + source.x + ")"; }).remove(); nodeExit.select("circle").attr("r", 1e-6); nodeExit.select("text").style("fill-opacity", 1e-6); // Update the links… var link = vis.selectAll("path.link").data(tree.links(nodes), function (d) { return d.target.id; }); // Enter any new links at the parent's previous position. link.enter().insert("svg:path", "g").attr("class", "link").attr("d", function (d) { var o = { x: source.x0, y: source.y0 }; return diagonal({ source: o, target: o }); }).transition().duration(duration).attr("d", diagonal); // Transition links to their new position. link.transition().duration(duration).attr("d", diagonal); // Transition exiting nodes to the parent's new position. link.exit().transition().duration(duration).attr("d", function (d) { var o = { x: source.x, y: source.y }; return diagonal({ source: o, target: o }); }).remove(); // Stash the old positions for transition. nodes.forEach(function (d) { d.x0 = d.x; d.y0 = d.y; }); } changeMode("boolean"); evaluateStatement(); }; /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { "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 BooleanJSONVisitor = function () { function BooleanJSONVisitor(state) { _classCallCheck(this, BooleanJSONVisitor); this.state = state; } _createClass(BooleanJSONVisitor, [{ key: "setState", value: function setState(newstate) { this.state = newstate; } }, { key: "execute", value: function execute(thingToEvaluate) { var ob = {}; ob.name = thingToEvaluate.type; ob.value = thingToEvaluate.value = this.getBoolean(thingToEvaluate); var symbolsMatched = thingToEvaluate.seriesOfSymbolsIAbsorbedAndReplaced; switch (thingToEvaluate.type) { case "TOKEN": return { name: thingToEvaluate.stringIActuallyMatched, value: this.getBoolean(thingToEvaluate), condition: "Condition Text Goes Here" }; case "BOOLEAN": ob.children = []; if (symbolsMatched.length == 3) // there's a binary operator { // either a binary operator or "(" + boolean + ")" if (symbolsMatched[0].type == "(" && symbolsMatched[2].type == ")") { // we'll pass it through transparently // in other words, allow our middle child to represent us completely // since the user isn't interested in seeing each "(" represented with its own node onscreen return this.execute(symbolsMatched[1]); } else { ob.name = this.getNameForOperator(symbolsMatched[1].type); ob.children.push(this.execute(symbolsMatched[0])); ob.children.push(this.execute(symbolsMatched[2])); } } else if (symbolsMatched.length == 2) // there's a unary operator { // the only unary operator ob.name = this.getNameForOperator(symbolsMatched[0].type); ob.children.push(this.execute(symbolsMatched[1])); } else { return this.execute(symbolsMatched[0]); } break; case "IDENT": // basically a passthrough. Assume our first child is a real operator, and return *its* json. ob.name = thingToEvaluate._stringIMatched; } return ob; } }, { key: "getBoolean", value: function getBoolean(nonterminalOrToken) { if (nonterminalOrToken.constructor.name == "Nonterminal") { var symbolsMatched = nonterminalOrToken.seriesOfSymbolsIAbsorbedAndReplaced; var value = "FOO"; // declare this and, hey, initialize it with something we'll notice if there's an error. if (symbolsMatched.length == 1) // we're a nonterminal that absorbed one other thing { value = this.getBoolean(symbolsMatched[0]); return value; } else if (symbolsMatched.length == 3) // we're a boolean comprising an operator and two operands { if (symbolsMatched[1].type == "|") { return this.getBoolean(symbolsMatched[0]) || this.getBoolean(symbolsMatched[2]); } else if (symbolsMatched[1].type == "&") { return this.getBoolean(symbolsMatched[0]) && this.getBoolean(symbolsMatched[2]); } else if (symbolsMatched[0].type == "(" && symbolsMatched[2].type == ")") { return this.getBoolean(symbolsMatched[1]); } else { throw new Error("DON'T KNOW WHAT THE OPERATOR OF THIS 3-ELEMENT SYMBOLSMATCHED IS:" + JSON.stringify(symbolsMatched)); } } else if (symbolsMatched.length == 2) // we're a boolean with one operator -- probably a not { if (symbolsMatched[0].type == "!") { return !this.getBoolean(symbolsMatched[1]); } else { throw new Error("DON'T KNOW WHAT THE OPERATOR OF THIS 2-ELEMENT SYMBOLSMATCHED IS:" + JSON.stringify(symbolsMatched)); } } throw new Error("UNKNOWN LENGTH OF SYMBOLSMATCHED:" + JSON.stringify(symbolsMatched)); } else // it's a token { if (nonterminalOrToken.type.toUpperCase().indexOf("TRUE") > -1) { return true; } if (nonterminalOrToken.type.toUpperCase().indexOf("FALSE") > -1) { return false; } if (nonterminalOrToken.type.toUpperCase().indexOf("IDENT") > -1) { return this.state[nonterminalOrToken._stringIMatched]; } throw new Error("nonterminalOrToken.type is " + nonterminalOrToken.type); return null; } } }, { key: "getNameForOperator", value: function getNameForOperator(operatorSymbol) { if (operatorSymbol == "|") return "OR"; if (operatorSymbol == "&") return "AND"; if (operatorSymbol == "^") return "XOR"; if (operatorSymbol == "!") return "NOT"; } }]); return BooleanJSONVisitor; }(); module.exports = BooleanJSONVisitor; /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { "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; }; }(); var _evaluationvisitor = __webpack_require__(9); var _evaluationvisitor2 = _interopRequireDefault(_evaluationvisitor); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var BooleanVisitor = function () { function BooleanVisitor(state) { _classCallCheck(this, BooleanVisitor); this.state = state; } _createClass(BooleanVisitor, [{ key: "setState", value: function setState(newstate) { this.state = newstate; } }, { key: "execute", value: function execute(nonterminalOrToken) { if (nonterminalOrToken.constructor.name == "Nonterminal") { var symbolsMatched = nonterminalOrToken.seriesOfSymbolsIAbsorbedAndReplaced; var value = "FOO"; // declare this and, hey, initialize it with something we'll notice if there's an error. if (symbolsMatched.length == 1) // we're a nonterminal that absorbed one other thing { value = symbolsMatched[0].visit(this); return value; } else if (symbolsMatched.length == 3) // we're a boolean comprising an operator and two operands { if (symbolsMatched[1].type == "|") { return symbolsMatched[0].visit(this) || symbolsMatched[2].visit(this); } else if (symbolsMatched[1].type == "&") { return symbolsMatched[0].visit(this) && symbolsMatched[2].visit(this); } else if (symbolsMatched[0].type == "(" && symbolsMatched[2].type == ")") { return symbolsMatched[1].visit(this); } else { throw new Error("DON'T KNOW WHAT THE OPERATOR OF THIS 3-ELEMENT SYMBOLSMATCHED IS:" + JSON.stringify(symbolsMatched)); } } else if (symbolsMatched.length == 2) // we're a boolean with one operator -- probably a not { if (symbolsMatched[0].type == "!") { return !symbolsMatched[1].visit(this); } else { throw new Error("DON'T KNOW WHAT THE OPERATOR OF THIS 2-ELEMENT SYMBOLSMATCHED IS:" + JSON.stringify(symbolsMatched)); } } throw new Error("UNKNOWN LENGTH OF SYMBOLSMATCHED:" + JSON.stringify(symbolsMatched)); } else // it's a token { if (nonterminalOrToken.type.toUpperCase().indexOf("TRUE") > -1) { return true; } if (nonterminalOrToken.type.toUpperCase().indexOf("FALSE") > -1) { return false; } if (nonterminalOrToken.type.toUpperCase().indexOf("IDENT") > -1) { return this.state[nonterminalOrToken._stringIMatched]; } throw new Error("nonterminalOrToken.type is " + nonterminalOrToken.type); return null; } } }]); return BooleanVisitor; }(); module.exports = BooleanVisitor; /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { "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 MathJSONVisitor = function () { function MathJSONVisitor(state) { _classCallCheck(this, MathJSONVisitor); this.state = state; } _createClass(MathJSONVisitor, [{ key: "setState", value: function setState(newstate) { this.state = newstate; } }, { key: "execute", value: function execute(thingToEvaluate) { var ob = {}; ob.name = thingToEvaluate.type; ob.value = thingToEvaluate.value = this.getValue(thingToEvaluate); var symbolsMatched = thingToEvaluate.seriesOfSymbolsIAbsorbedAndReplaced; switch (thingToEvaluate.type) { case "NUM_LIT": return { name: this.getValue(thingToEvaluate), value: this.getValue(thingToEvaluate), condition: "Condition Text Goes Here" }; case "NUMERIC": ob.children = []; if (symbolsMatched.length == 3) // there's a binary operator { // either a binary operator or "(" + boolean + ")" if (symbolsMatched[0].type == "(" && symbolsMatched[2].type == ")") { // we'll pass it through transparently // in other words, allow our middle child to represent us completely // since the user isn't interested in seeing each "(" represented with its own node onscreen return this.execute(symbolsMatched[1]); } else { ob.name = symbolsMatched[1].type; ob.children.push(this.execute(symbolsMatched[0])); ob.children.push(this.execute(symbolsMatched[2])); } } else if (symbolsMatched.length == 2) // there's a unary operator { // the only unary operator ob.name = symbolsMatched[0].type; ob.children.push(this.execute(symbolsMatched[1])); } else { return this.execute(symbolsMatched[0]); } break; case "IDENT": // basically a passthrough. Assume our first child is a real operator, and return *its* json. ob.name = thingToEvaluate._stringIMatched; } return ob; } }, { key: "getValue", value: function getValue(nonterminalOrToken) { if (nonterminalOrToken.constructor.name == "Nonterminal") { var symbolsMatched = nonterminalOrToken.seriesOfSymbolsIAbsorbedAndReplaced; var value = "FOO"; // declare this and, hey, initialize it with something we'll notice if there's an error. if (symbolsMatched.length == 1) // we're a nonterminal that absorbed one other thing { value = this.getValue(symbolsMatched[0]); return value; } else if (symbolsMatched.length == 3) // we're a boolean comprising an operator and two operands { // or maybe we're just a numeric wrapped in parens! if (symbolsMatched[0].type == "(" && symbolsMatched[2].type == ")") { return this.getValue(symbolsMatched[1]); } if (symbolsMatched[1].type == "+") { return this.getValue(symbolsMatched[0]) + this.getValue(symbolsMatched[2]); } else if (symbolsMatched[1].type == "-") { return this.getValue(symbolsMatched[0]) - this.getValue(symbolsMatched[2]); } else if (symbolsMatched[1].type == "*") { return this.getValue(symbolsMatched[0]) * this.getValue(symbolsMatched[2]); } else if (symbolsMatched[1].type == "/") { return this.getValue(symbolsMatched[0]) / this.getValue(symbolsMatched[2]); } else if (symbolsMatched[1].type == "^") { return Math.pow(this.getValue(symbolsMatched[0]), this.getValue(symbolsMatched[2])); } else { throw new Error("WE HAVE 3 SYMBOLS BUT I DON'T KNOW WHAT THIS IS:" + JSON.stringify(symbolsMatched)); } } else if (symbolsMatched.length == 2) // we're a boolean with one operator { if (symbolsMatched[0].type == "+") { return this.getValue(symbolsMatched[1]); } if (symbolsMatched[0].type == "-") { return -1 * this.getValue(symbolsMatched[1]); } else { throw new Error("IN NUMERICVISITOR, DON'T KNOW WHAT THE OPERATOR OF THIS 2-ELEMENT SYMBOLSMATCHED IS:" + JSON.stringify(symbolsMatched)); } } throw new Error("UNKNOWN LENGTH OF SYMBOLSMATCHED:" + JSON.stringify(symbolsMatched)); } else // it's a token { if (nonterminalOrToken.type.toUpperCase().indexOf("NUM_LIT") > -1) { return parseInt(nonterminalOrToken._stringIMatched); } throw new Error("nonterminalOrToken.type is " + nonterminalOrToken.type); return null; } } }, { key: "getNameForOperator", value: function getNameForOperator(operatorSymbol) { if (operatorSymbol == "|") return "OR"; if (operatorSymbol == "&") return "AND"; if (operatorSymbol == "^") return "XOR"; if (operatorSymbol == "!") return "NOT"; } }]); return MathJSONVisitor; }(); module.exports = MathJSONVisitor; /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { "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; }; }(); var _token = __webpack_require__(8); var _token2 = _interopRequireDefault(_token); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var XMLJSONVisitor = function () { function XMLJSONVisitor(state) { _classCallCheck(this, XMLJSONVisitor); this.state = state; } _createClass(XMLJSONVisitor, [{ key: "setState", value: function setState(newstate) { this.state = newstate; } }, { key: "execute", value: function execute(thingToEvaluate) { var ob = {}; ob.name = thingToEvaluate.type; ob.value = this.getValue(thingToEvaluate).trim(); var symbolsMatched = thingToEvaluate.symbolsMatched; switch (thingToEvaluate.type) { case "TOKEN": return { name: thingToEvaluate.stringIActuallyMatched, value: this.getValue(thingToEvaluate), condition: "Condition Text Goes Here" }; case "XMLNODES": ob.name = "nodelist"; ob.children = []; for (var i = 0; i < symbolsMatched.length; i++) { var executedSymbol = this.execute(symbolsMatched[i]); ob.children.push(executedSymbol); } return ob.children; break; case "XMLNODE": this.parentnode = ob; ob.children = []; // opentag is first item, and that gives us our name ob.name = this.getValue(symbolsMatched[0]); var optionalAttributes = this.getAttributes(symbolsMatched[0]); if (optionalAttributes) { ob.attributes = optionalAttributes; } symbolsMatched = this.consolidateChildrenThatAreTokens(symbolsMatched); for (var i = 1; i < symbolsMatched.length - 1; i++) // -1, because the last match will be a closetag, which is irrelevant { var child = this.execute(symbolsMatched[i]); // if a child was a nodelist, then it will return an array of divs. // we should not push that array as an element onto our array! // we should concat all its children onto our children (if we have any) if (Array.isArray(child)) { ob.children = ob.children.concat(child); } else { ob.children.push(child); } } break; case "IDENT": // basically a passthrough. Assume our first child is a real operator, and return *its* json. ob.name = thingToEvaluate._stringIMatched; } return ob; } // good for the wildcard globbing we do inside open and close tags }, { key: "consolidateChildrenThatAreTokens", value: function consolidateChildrenThatAreTokens(arrayOfSymbolsThatMightBeTokens) { var symbolChildrenOnly = []; var runningStringOfTokenText = ""; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = arrayOfSymbolsThatMightBeTokens[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var symbol = _step.value; if (symbol.constructor.name != "Token") { if (runningStringOfTokenText.length > 0) // we've been building up a text string! { var _tokenConsolidatingStrings = this.makeTokenWrappingString(runningStringOfTokenText); symbolChildrenOnly.push(_tokenConsolidatingStrings); runningStringOfTokenText = ""; symbolChildrenOnly.push(symbol); } else { symbolChildrenOnly.push(symbol); } } else // it's a token! { runningStringOfTokenText += symbol._stringIMatched; } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } if (runningStringOfTokenText.length > 0) { var tokenConsolidatingStrings = this.makeTokenWrappingString(runningStringOfTokenText); symbolChildrenOnly.push(tokenConsolidatingStrings); } return symbolChildrenOnly; } }, { key: "makeTokenWrappingString", value: function makeTokenWrappingString(stringToWrap) { var newSymbol = new _token2.default(/.+/, "TEXTNODE", stringToWrap.length, stringToWrap); return newSymbol; } // sent either an opentag or an opentagstart }, { key: "getAttributes", value: function getAttributes(childOfXMLNode) { if (childOfXMLNode.type == "OPENTAGSTART") { // could be nested // or could be <, IDENT, IDENT, =, ', WILDCARD, ' // or could be <, IDENT, IDENT, =, ', IDENT, ' // or could be <, IDENT, IDENT, =, ', IDENT, IDENT, ' var atts = {}; if (childOfXMLNode.symbolsMatched[0].constructor.name == "Token") // could only be "<" { var name = this.getValue(childOfXMLNode.symbolsMatched[2]); var valueForName = ""; for (var attributeValueIndex = 5; attributeValueIndex < childOfXMLNode.symbolsMatched.length - 1; attributeValueIndex++) { valueForName += this.getValue(childOfXMLNode.symbolsMatched[attributeValueIndex]); var notLast = attributeValueIndex < childOfXMLNode.symbolsMatched.length - 2; if (notLast) valueForName += " "; } atts[name] = valueForName; return atts; } else if (childOfXMLNode.symbolsMatched[0].type == "OPENTAGSTART") // nested opentagstarts! multiple attributes { atts = this.getAttributes(childOfXMLNode.symbolsMatched[0]); var _name = this.getValue(childOfXMLNode.symbolsMatched[1]); var val = this.getValue(childOfXMLNode.symbolsMatched[4]); atts[_name] = val; return atts; } } else if (childOfXMLNode.symbolsMatched[0].type == "OPENTAGSTART") { var returnAtts = this.getAttributes(childOfXMLNode.symbolsMatched[0]); return returnAtts; } return null; } }, { key: "getValue", value: function getValue(nonterminalOrToken) { if (nonterminalOrToken.constructor.name == "Nonterminal") { var symbolsMatched = nonterminalOrToken.symbolsMatched; var value = "FOO"; // declare this and, hey, initialize it with something we'll notice if there's an error. if (nonterminalOrToken.type == "XMLNODE") { // our first child will be our opentag, which is where our name comes from. var _returnVal = this.getValue(symbolsMatched[0]); return _returnVal; } if (nonterminalOrToken.type == "XMLNODES") { var _returnVal2 = "NODELIST"; return _returnVal2; } if (nonterminalOrToken.type == "OPENTAG" || nonterminalOrToken.type == "OPENTAGSTART") { var returnVal; // symbolsMatched[1] will either be an IDENT or an OPENTAGSTART (the wrapper for attribute definitions) if (symbolsMatched[0].type == "OPENTAGSTART") { returnVal = this.getValue(symbolsMatched[0]); return returnVal; } returnVal = this.getValue(symbolsMatched[1]); return returnVal; } if (nonterminalOrToken.type == "CLOSETAG") { return this.getValue(symbolsMatched[2]); // after < and / } if (nonterminalOrToken.type == "COMMENT") { var commentstring = ""; var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = nonterminalOrToken.symbolsMatched[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var kid = _step2.value; if (kid.type == "OPENCOMMENT" || kid.type == "CLOSECOMMENT") continue; commentstring += this.getValue(kid); } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2.return) { _iterator2.return(); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } return commentstring; } if (nonterminalOrToken.type == "NODETEXT") { var contentstring = ""; var _iteratorNormalCompletion3 = true; var _didIteratorError3 = false; var _iteratorError3 = undefined; try { for (var _iterator3 = nonterminalOrToken.symbolsMatched[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { var kid = _step3.value; if (kid.type == "NODETEXT" || kid.type == "IDENT") // IDENT generally means it was preceded and/or followed by some kind of whitespace // so we should restore that delimiter if (kid.type == "IDENT") { contentstring += " " + this.getValue(kid); } else { contentstring += this.getValue(kid); } } } catch (err) { _didIteratorError3 = true; _iteratorError3 = err; } finally { try { if (!_iteratorNormalCompletion3 && _iterator3.return) { _iterator3.return(); } } finally { if (_didIteratorError3) { throw _iteratorError3; } } } return contentstring; } throw new Error("XMLJSONVISITOR UNKNOWN LENGTH OF SYMBOLSMATCHED for " + nonterminalOrToken.type + ":" + JSON.stringify(symbolsMatched)); } else // it's a token { if (nonterminalOrToken.type.toUpperCase().indexOf("TRUE") > -1) { return true; } if (nonterminalOrToken.type.toUpperCase().indexOf("TEXTNODE") > -1) { return nonterminalOrToken._stringIMatched; } if (nonterminalOrToken.type.toUpperCase().indexOf("IDENT") > -1) { return nonterminalOrToken._stringIMatched; } return nonterminalOrToken._stringIMatched; // throw new Error("nonterminalOrToken.type is " + nonterminalOrToken.type ); // return null; } } }]); return XMLJSONVisitor; }(); module.exports = XMLJSONVisitor; /***/ }), /* 17 */ /***/ (function(module, exports, __webpack_require__) { "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 XMLParseTimeVisitor = function () { function XMLParseTimeVisitor(state) { _classCallCheck(this, XMLParseTimeVisitor); this.state = state; } _createClass(XMLParseTimeVisitor, [{ key: "setState", value: function setState(newstate) { this.state = newstate; } }, { key: "execute", value: function execute(nonterm) { if (nonterm.type == "XMLNODE") { return this.verifyOpeningAndCloseTagsMatch(nonterm) && this.verifyTagContentIsLegal(nonterm); } else if (nonterm.type == "OPENTAG") { return this.verifyAttributeContentIsLegal(nonterm); } else return true; } }, { key: "verifyOpeningAndCloseTagsMatch", value: function verifyOpeningAndCloseTagsMatch(thingToEvaluate) { var openTagName = this.getTagName(thingToEvaluate.symbolsMatched[0]); var closeTagName = void 0; if (thingToEvaluate.symbolsMatched.length == 2) { closeTagName = this.getTagName(thingToEvaluate.symbolsMatched[1]); } else if (thingToEvaluate.symbolsMatched.length > 2) { closeTagName = this.getTagName(thingToEvaluate.symbolsMatched[thingToEvaluate.symbolsMatched.length - 1]); } return openTagName == closeTagName; } }, { key: "verifyAttributeContentIsLegal", value: function verifyAttributeContentIsLegal(nonterm) { // remember that OPENTAG can contain optional OPENTAGSTART nodes // each of which can enclose other OPENTAGSTART nodes in perpetuity return true; } }, { key: "verifyTagContentIsLegal", value: function verifyTagContentIsLegal(thingToEvaluate) { return true; } }, { key: "getTagName", value: function getTagName(thingToEvaluate) { while (thingToEvaluate.type != "IDENT") { if (thingToEvaluate.type == "OPENTAG") { if (thingToEvaluate.symbolsMatched) { if (thingToEvaluate.symbolsMatched[0].type == "<") { return thingToEvaluate.symbolsMatched[1]._stringIMatched; } } } else if (thingToEvaluate.type == "CLOSETAG") { if (thingToEvaluate.symbolsMatched) { if (thingToEvaluate.symbolsMatched[0].type == "<") { // element [1] will be "/" so we'll skip to [2] return thingToEvaluate.symbolsMatched[2]._stringIMatched; } } } else if (thingToEvaluate.type == "OPENTAGSTART") { if (thingToEvaluate.symbolsMatched) { if (thingToEvaluate.symbolsMatched[0].type == "<") { return thingToEvaluate.symbolsMatched[1]._stringIMatched; } } } thingToEvaluate = thingToEvaluate.symbolsMatched[0]; } return thingToEvaluate._stringIMatched; } }]); return XMLParseTimeVisitor; }(); module.exports = XMLParseTimeVisitor; /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(5); module.exports = __webpack_require__(12); /***/ }) /******/ ]); //# sourceMappingURL=boolius.bundle.js.map
/* * @Author: Picker * @Date: 2017-05-24 16:39:08 * @Last Modified by: Picker * @Last Modified time: 2017-05-27 15:40:36 */ import component from 'element-ui/lib/input'; import { PROPS_MAPPING } from './constants'; import { getDefaultAttrsFromProps, mergePropsMapping } from '../utils'; /** * convert original Input node info to a full component Model. * @param node [original Input node info] */ function transformNodeAttrs(node) { const defaultProps = getDefaultAttrsFromProps(component.props); if (defaultProps.autosize.default === false) { defaultProps.autosize.default = '$false'; } if (defaultProps.autosize.value === false) { defaultProps.autosize.value = '$false'; } const attrs = mergePropsMapping(defaultProps, PROPS_MAPPING, node.attrs); return attrs; } export default { transformNodeAttrs };
var webpack = require('webpack'); var cssnext = require('postcss-cssnext'); var postcssFocus = require('postcss-focus'); var postcssReporter = require('postcss-reporter'); module.exports = { devtool: 'cheap-module-eval-source-map', entry: { app: [ 'eventsource-polyfill', 'webpack-hot-middleware/client', 'webpack/hot/only-dev-server', 'react-hot-loader/patch', './client/index.js', ], vendor: [ 'react', 'react-dom', ], }, output: { path: __dirname, filename: 'app.js', publicPath: 'http://0.0.0.0:8000/', }, resolve: { extensions: ['', '.js', '.jsx'], modules: [ 'client', 'node_modules', ], }, module: { loaders: [ { test: /\.css$/, exclude: /node_modules/, loader: 'style-loader!css-loader?localIdentName=[name]__[local]__[hash:base64:5]&modules&importLoaders=1&sourceMap!postcss-loader', }, { test: /\.css$/, include: /node_modules/, loaders: ['style-loader', 'css-loader'], }, { test: /\.jsx*$/, exclude: [/node_modules/, /.+\.config.js/], loader: 'babel', }, { test: /\.(jpe?g|gif|png|svg)$/i, loader: 'url-loader?limit=10000', }, { test: /\.json$/, loader: 'json-loader', }, { test: /\.(svg|eot|ttf|woff|woff2)$/, loader:'file-loader' } ], }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: Infinity, filename: 'vendor.js', }), new webpack.DefinePlugin({ 'process.env': { CLIENT: JSON.stringify(true), 'NODE_ENV': JSON.stringify('development'), } }), ], postcss: () => [ postcssFocus(), cssnext({ browsers: ['last 2 versions', 'IE > 10'], }), postcssReporter({ clearMessages: true, }), ], };
module.exports = (grunt) => { "use strict"; require("load-grunt-tasks")(grunt); const banner = "/* https://github.com/micmro/performance-bookmarklet by Michael Mrowetz @MicMro\n build:<%= grunt.template.today(\"dd/mm/yyyy\") %> */\n"; grunt.initConfig({ copy : { distBookmarklet: { files: [{ expand: true, cwd: "src/", src: ["**/*.js"], dest: "dist/tempCollect", filter: fileName => { return !fileName.match(/.+\.(?:chromeExtension|firefoxAddon).js$/); }, ext: ".js" }] }, distFirefoxAddon: { files: [{ expand: true, cwd: "src/", src: ["**/*.js"], dest: "dist/tempCollect", filter: fileName => { return !fileName.match(/.+\.(?:bookmarklet|chromeExtension).js$/); }, ext: ".js" }] }, distChromeExtension: { files: [{ expand: true, cwd: "src/", src: ["**/*.js"], dest: "dist/tempCollect", filter: fileName => { return !fileName.match(/.+\.(?:bookmarklet|firefoxAddon).js$/); }, ext: ".js" }] } }, babel: { options: { sourceMap: true, presets: ['@babel/preset-env'] }, dist: { files: [{ expand: true, cwd: "dist/tempCollect", src: "**/*.js", dest: "dist/tempEs5/", ext: ".js" }] } }, browserify: { options: { banner: banner }, distBookmarklet: { files: { "dist/performanceBookmarklet.js": ["dist/tempEs5/**/*.js"], } }, distFirefoxAddon: { files: { "dist/performanceBookmarklet.ff.js": ["dist/tempEs5/**/*.js"], } }, distChromeExtension: { files: { "dist/performanceBookmarklet.chrome.js": ["dist/tempEs5/**/*.js"], } } }, uglify : { options: { compress: { global_defs: { "DEBUG": false }, dead_code: true }, banner: banner }, distBookmarklet: { files: { "dist/performanceBookmarklet.min.js": ["dist/performanceBookmarklet.js"] } }, distFirefoxAddon: { files: { "dist/performanceBookmarklet.ff.min.js": ["dist/performanceBookmarklet.ff.js"] } }, distChromeExtension: { files: { "dist/performanceBookmarklet.chrome.min.js": ["dist/performanceBookmarklet.chrome.js"] } } }, watch: { babelBookmarklet: { files: ["src/**/*", "Gruntfile.js"], tasks: ["distBookmarklet"], options: { spawn: false, interrupt: true }, }, babelFirefoxAddon: { files: ["src/**/*", "Gruntfile.js"], tasks: ["distFirefoxAddon"], options: { spawn: false, interrupt: true }, }, babelChromeExtension: { files: ["src/**/*", "Gruntfile.js"], tasks: ["distChromeExtension"], options: { spawn: false, interrupt: true }, }, } }); //transform CSS file to JS variable grunt.registerTask("inlineCssToJs", () => { const cssFile = "src/style.css"; const cssFileDestination = "dist/tempCollect/helpers/style.js"; const varName = "style"; let cssContent = grunt.file.read(cssFile); //clean CSS content cssContent = cssContent.replace( /\/\*(?:(?!\*\/)[\s\S])*\*\//g, "").replace(/[\r\n\t]+/g, " ").replace(/[ ]{2,}/g, " ").replace(/\"/g,"\\\""); //make JS Var and export as module cssContent = "export const " + varName + " = \"" + cssContent.trim() + "\";"; grunt.log.writeln(cssFile + " transformed to " + cssFileDestination); grunt.file.write(cssFileDestination, cssContent); }); grunt.registerTask("distBookmarklet", ["inlineCssToJs", "copy:distBookmarklet", "babel", "browserify:distBookmarklet", "uglify:distBookmarklet"]); grunt.registerTask("distFirefoxAddon", ["inlineCssToJs", "copy:distFirefoxAddon", "babel", "browserify:distFirefoxAddon", "uglify:distFirefoxAddon"]); grunt.registerTask("distChromeExtension", ["inlineCssToJs", "copy:distChromeExtension", "babel", "browserify:distChromeExtension", "uglify:distChromeExtension"]); grunt.registerTask("distAll", ["distBookmarklet", "distFirefoxAddon", "distChromeExtension"]); grunt.registerTask("watchDistBookmarklet", ["distBookmarklet", "watch:babelBookmarklet"]); grunt.registerTask("watchDistFirefoxAddon", ["distFirefoxAddon", "watch:babelFirefoxAddon"]); grunt.registerTask("watchDistChromeExtension", ["distChromeExtension", "watch:babelChromeExtension"]); grunt.registerTask("default", ["watchDistBookmarklet"]); };
Object.defineProperty( Object.prototype, 'getField', { value: function(field) { if ( field === '' ) return this; let i, ref = this, path = field.toString().split('.'), len = path.length; for ( i = 0; i < len; i++ ) { if ( ref[ path[i] ] !== undefined ) ref = ref[ path[i] ]; else return undefined; } return ref; } } ); Object.defineProperty( Object.prototype, 'setField', { value: function(field, value) { let i, ref = this, path = field.toString().split('.'), len = path.length; for ( i = 0; i < len - 1; i++ ) { if ( ref[ path[i] ] === undefined ) ref[ path[i] ] = {}; ref = ref[ path[i] ]; } ref[ path[len - 1] ] = value; } } ); /** * Create new Evente application * @param {string} selector Selector for application root element * @param {*} [data={}] Initial data * @param {Object} [options] Aplication creation options * @param {boolean} [options.clean=false] Remove Comment and empty Text nodes from DOM * @param {boolean} [options.router=true] Use router * @param {boolean} [options.run=true] Run immediately after create * @returns {EventeApplication} */ const evente = function(selector, data, options) { return new EventeApplication(selector, data, options); }; /** * Get registered pipes * @returns {EventePipes} */ Object.defineProperty(evente, 'pipes', { get: function() { return EventePipes; } }); /** * Create EventeResource instance * @param {string} url Resource URL * @param {string} [type=json] Resource content type * @returns {EventeResource} */ evente.resource = function(url, type) { return new EventeResource(url, type); } /** * Evente Expression class */ class EventeExpression { /** * @param {string} string Expression string */ constructor(string) { this.expression = string; this.tree = this.parse(string.trim()); } /** * Eveluate expression value or path * @param {EventeModel} model EventeModel object * @param {*} [item] Abstract Syntax Tree item * @param {boolean} [property] Flag to get path in model data * @returns {*} */ eval(model, item, property) { if ( item === undefined ) item = this.tree; let value, tmp, number, type = typeof item; switch ( type ) { case 'string': value = property ? item : model.get(item); break; case 'number': value = item; break; default: switch ( item.type ) { case '+': case '-': case '*': case '/': for ( let i in item.params ) { tmp = this.eval(model, item.params[i]); if ( tmp === undefined || tmp === null ) continue; if ( (value === undefined || typeof value === 'number') && typeof tmp !== 'number' ) tmp = this.parse_number(tmp); value = value === undefined ? tmp : EventeExpression.operations[item.type].eval(value, tmp); } break; case '&': case '?': case '=': case '#': value = []; for ( let i in item.params ) { tmp = this.eval(model, item.params[i]); value.push(this.parse_number(tmp)); if ( value.length > 1 ) value = [ EventeExpression.operations[item.type].eval(value[0], value[1]) ]; } value = value[0]; break; case '!': value = !this.eval(model, item.params[0]); break; case 'value': value = this[property ? 'property' : 'eval'](model, item.params[0]); break; case '.': if ( property ) { value = this.property(model, item.params[0]); value = value !== undefined ? value + '.' + item.params[1] : undefined; } else { value = this.eval(model, item.params[0]); value = value !== undefined ? value.getField(item.params[1]) : undefined; } break; case '[]': value = item.params[0] + '.' + this.eval(model, item.params[1]); if ( !property ) value = model.get(value); break; case '|': let params = []; for ( let i in item.params ) params.push( this.eval(model, item.params[i] ) ); value = EventePipes[item.name](params); break; } } return value; } /** * Get path in model data * @param {EventeModel} model EventeModel object * @param {*} [item] Abstract Syntax Tree item * @returns {string} */ property(model, item) { return this.eval(model, item, true); } /** * Get dependencies of Abstract Syntax Tree * @param {*} item Abstract Syntax Tree item * @returns {Array<string>} */ getLinks(item) { if ( item === undefined ) item = this.tree; let i, links = [], type = typeof item; switch ( type ) { case 'number': break; case 'string': if ( item.endsWith('.length') ) item = item.substr(0, item.length - 7); if ( item.endsWith('.keys') ) item = item.substr(0, item.length - 5); links.push(item); break; default: switch ( item.type ) { case '.': links.push(...this.getLinks(item.params[0])); break; default: for ( i in item.params ) links.push(...this.getLinks(item.params[i])); } } return links; } /** * Moves unclosed strings into expression and * convert strings into variables * @public * @param {string} data Expression string * @returns {string} */ preparse(data) { data = this.parse_unclosed(data); return '{{' + this.parse_strings(data) + '}}'; } /** * Parse expression into Abstract Syntax Tree * @private * @param {string} data Expression string * @returns {Object} */ parse(data) { data = this.parse_unclosed(data); data = this.parse_strings(data); data = this.parse_operations(data); this.expression = data; return this.parse_tree(this.parse_tokens(data)); } /** * Parse expression parts not in double braces * @private * @param {string} string Expression string * @returns {string} */ parse_unclosed(string) { let pos = 0, tmp_string = '', tmp, match, reg_exp = /{{.*?}}/gm, reg_token = new RegExp([ '=', '!=', '!', '&&', '\\|\\|', '-', '\\+', '\\*', '\\/', '\\[', ']', '\\(', '\\)', '\\|', ':', ].join('|')); match = reg_exp.exec(string); while ( match ) { if ( match.index !== pos ) { tmp = string.substr(pos, match.index - pos); tmp_string += 'strings.' + EventeStrings.getIndex(tmp) + ' + '; pos = match.index; } tmp = match[0].substr(2, match[0].length - 4).trim(); if ( reg_token.test(tmp) ) tmp = '(' + tmp + ')'; tmp_string += tmp + ' + '; pos += match[0].length; match = reg_exp.exec(string); } tmp = string.substr(pos); if ( tmp.length ) tmp_string += 'strings.' + EventeStrings.getIndex(tmp); if ( tmp_string.endsWith(' + ') ) tmp_string = tmp_string.substr(0, tmp_string.length - 3); if ( tmp_string.startsWith('(') && tmp_string.endsWith(')') && !tmp_string.match(/^\(.*(\(|\)).*\)$/) ) tmp_string = tmp_string.substr(1, tmp_string.length - 2); return tmp_string; } /** * Parse strings of expression into model fields * @private * @param {string} string Expression string * @returns {string} */ parse_strings(string) { let result = '', pos = 0, str = { start: 0 }, regexp = /['"]/gm, match = regexp.exec(string); while ( match ) { if ( !str.start ) { str.start = match.index + 1; str.delim = match[0]; result += string.substr(pos, match.index - pos); } else { if ( str.delim === match[0] ) { str.string = string.substr(str.start, match.index - str.start); str.index = EventeStrings.getIndex(str.string); result += 'strings.' + str.index; str.start = 0; } } pos = match.index + 1; match = regexp.exec(string); } if ( pos < string.length ) result += string.substr(pos); return result; } /** * Parse double symbol operators * @private * @param {string} string Expression string * @returns {string} */ parse_operations(string) { string = string.replace(/&&/g, '&'); string = string.replace(/\|\|/g, '?'); string = string.replace(/==/g, '='); string = string.replace(/!=/g, '#'); return string; } /** * Parse expression into tokens * @private * @param {string} string Expression string * @returns {Array<string>} */ parse_tokens(string) { let pos = 0, tmp, match, reg_token = /[!&?=#\-+*/[\]()|:]/gm, tokens = []; pos = 0; reg_token.lastIndex = 0; match = reg_token.exec(string); while ( match ) { if ( match.index !== pos ) { tmp = string.substr(pos, match.index - pos).trim(); if ( tmp.length ) tokens.push( string.substr(pos, match.index - pos).trim() ); pos = match.index; } tokens.push( match[0].trim() ); pos += match[0].length; match = reg_token.exec(string); } tmp = string.substr(pos).trim(); if ( tmp.length ) tokens.push(tmp); return tokens; } /** * Parse expression tokens into Abstract Syntax Tree * @private * @param {Array<string>} tokens Expression tokens * @param {*} [item] Abstract Syntax Tree item * @returns {Object} */ parse_tree(tokens, item) { if ( item === undefined ) item = {}; if ( item.params === undefined ) item.params = []; let token, tmp; while ( tokens.length ) { token = tokens.shift(); switch ( token ) { case '-': case '+': case '*': case '/': case '&': case '?': case '=': case '#': case '!': if ( item.type === undefined ) { item.type = token; continue; } if ( item.type === token ) break; if ( EventeExpression.operations[item.type].priority >= EventeExpression.operations[token].priority ) item = { type: token, params: [ item ] }; else item.params.push(this.parse_tree( tokens, { type: token, params: [ item.params.pop() ] } )); break; case '(': item.params.push(this.parse_tree(tokens)); break; case ')': if ( item.type === undefined ) item.type = 'value'; return item; case '[': if ( item.type === undefined ) { item.type = '[]'; item.params.push(this.parse_tree(tokens)); } else item.params.push( { type: '[]', params: [ item.params.pop(), this.parse_tree(tokens) ] } ); break; case ']': if ( item.type === undefined ) item.type = 'value'; return item; case '|': if ( item.type !== undefined ) item = { params: [ item ] }; item.type = '|'; item.name = tokens.shift(); token = tokens.shift(); while ( token === ':' ) { item.params.push( this.parse_tree(tokens) ); token = tokens.shift(); } if ( token !== undefined ) tokens.unshift(token); break; case ':': tokens.unshift(token); if ( !item.params.length ) return ''; if ( item.type === undefined ) item.type = 'value' return item; default: if ( token[0] == '.' ) { token = token.substr(1); if ( item.type === undefined ) { item.type = '.'; item.params.push(token); } else { if ( EventeExpression.operations[item.type].priority >= EventeExpression.operations['.'].priority ) item = {type: '.', params: [item, token]}; else item.params.push({type: '.', params: [item.params.pop(), token]}); } } else item.params.push(this.parse_number(token)); } } if ( item.type === undefined ) item.type = 'value'; return item; } /** * Try to parse string as number * @private * @param {string} value * @returns {string|number} */ parse_number(value) { let tmp = parseFloat(value) return !isNaN(tmp) && tmp.toString() == value ? tmp : value; } }; EventeExpression.operations = { '+': { priority: 0, eval: function(a, b) { return a + b; } }, '-': { priority: 0, eval: function(a, b) { return a - b; } }, '*': { priority: 1, eval: function(a, b) { return a * b; } }, '/': { priority: 1, eval: function(a, b) { return a / b; } }, '&': { priority: 2, eval: function(a, b) { return Boolean(a && b); } }, '?': { priority: 2, eval: function(a, b) { return Boolean(a || b); } }, '=': { priority: 3, eval: function(a, b) { return Boolean(a == b); } }, '#': { priority: 3, eval: function(a, b) { return Boolean(a != b); } }, '!': { priority: 4 }, '.': { priority: 5 }, '[]': { priority: 6 }, '|': { priority: 7 }, }; /** * Attribute class * @extends EventeExpression */ class EventeAttribute extends EventeExpression { /** * @param {HTMLElement} node DOM element * @param {string} name Attribute name * @param {EventeModel} model EventeModel object */ constructor(node, name, model) { let attribute = node.attributes[name]; super(attribute.value); this.name = name; this.node = node; this.model = model; } /** * Apply attributes values */ apply() { let value = this.eval(this.model); value = value !== undefined ? value.toString() : ''; if ( this.node.getAttribute(this.name) !== value ) this.node.setAttribute(this.name, value); } /** * Check attribute expression is in double braces * @param {Element} node DOM element * @param {string} name Attribute name * @returns {string} */ static check(node, name) { let value = node.getAttribute(name).trim(); return !value.startsWith('{{') ? '{{' + value + '}}' : value; }; /** * Get registered attributes ordered by priority * @returns {Array<Object>} */ static getAttributes() { if ( EventeAttribute.attributesByPriorty.length !== Object.keys(EventeAttribute.attributes).length ) { let tmp = []; for ( let i in EventeAttribute.attributes ) tmp.push({ name: i, priority: EventeAttribute.attributes[i].priority}); tmp.sort((a,b) => { if ( a.priority > b.priority ) return -1; if ( a.priority < b.priority ) return 1; return 0; }) EventeAttribute.attributesByPriorty = tmp; } return EventeAttribute.attributesByPriorty; } }; /** * Registered attributes * @type {Object} */ EventeAttribute.attributes = {}; /** * Regstered attributes ordered by priority * @private * @type {Array<Object>} */ EventeAttribute.attributesByPriorty = []; /** * Default attribute priority * @type {number} * @default 0 */ EventeAttribute.priority = 0; /** * Evente Application class */ class EventeApplication { /** * @param {string} selector Selector for application root element * @param {*} data Initial data * @param {Object} [options={}] Aplication creation options * @param {boolean} [options.clean=false] Remove Comment and empty Text nodes from DOM * @param {boolean} [options.router=true] Use router * @param {boolean} [options.run=true] Run immediately after create */ constructor(selector, data, options) { options = { clean: false, router: true, run: true, ...options }; this.element = document.querySelector(selector); this.model = new EventeModel(this.element, data); this.model.proxy = new Proxy({$: ''}, new EventeModelProxyHandler(this.model)); if ( options.clean ) this.clean(); if ( options.router ) this.router = new EventeRouter(this.element); if ( options.run ) this.run(); } /** * Get model data * @returns {Object} */ get data() { return this.model.data; } /** * Set model data * @param {Object} value */ set data(value) { this.model.data = value; EventeParser.parseNode(this.element, this.model); } /** * Add or remove route * @param {string} route Route pattern * @param {Function} [callback] Calback function to set or undefined to remove route * @param {*} [params] Parameters that will be passed to callback function */ route(route, callback, params) { if ( !this.router ) return; if ( callback ) this.router.add(route, callback, params); else this.router.remove(route); } /** * Run application */ run() { EventeParser.parseNode(this.element, this.model); if ( this.router ) this.router.trigger(); } /** * Remove Comment and empty Text nodes from DOM * @private */ clean() { let node, nodes = [], walker = document.createTreeWalker(document, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT, null, false); while( node = walker.nextNode() ) { switch ( node.nodeType ) { case Node.TEXT_NODE: if ( !node.nodeValue.match(/[^\s\n]/m) ) nodes.push(node); break; case Node.COMMENT_NODE: nodes.push(node); break; } } for ( node in nodes ) nodes[node].remove(); } }; /** * Base attribute class * @extends EventeAttribute */ class EventeAttributeBase extends EventeAttribute { /** * @inheritdoc */ constructor(node, name, model) { let attribute = node.attributes[name], match = attribute.value.match(/^{{(.*?)(\s+as\s+([a-z0-9_]+))}}$/im); attribute.value = '{{' + match[1] + '}}'; super(node, name, model); this.alias = match[3]; this.apply(); } /** * @inheritdoc */ apply() { let i, item, items = this.node.childNodes, property = this.property(this.model); for ( i = 0; i < items.length; i++ ) { item = items[i]; this.dealias(item, this.alias, property); } } /** * Change alias in expressions on base path * @private * @param {ChildNode | Element | Text} node DOM node * @param {string} alias Alias name * @param {string} base Base path */ dealias(node, alias, base) { let value, regexp = new RegExp('(^|[^a-z])' + alias.replace(/\./g, '\\.') + '([^a-z]|$)', 'gim'), test = new RegExp('{{'); if ( node instanceof Text ) { if ( node.e_base ) { value = node.e_base.replace(regexp, '$1' + base + '$2'); } else { value = node.nodeValue; if ( value.match(test) ) { value = this.preparse(value); if ( value.match(regexp) ) { node.e_base = value; value = value.replace(regexp, '$1' + base + '$2'); } } } if ( node.nodeValue !== value ) { node.nodeValue = value; EventeParser.parseAttributes(node, this.model); this.model.applyAttributes(node); } return; } node.e_base = node.e_base || {}; let i, item, items = node.attributes; for ( i = 0; i < items.length; i++ ) { item = items[i]; if ( node.e_base[item.name] ) { value = node.e_base[item.name].replace(regexp, '$1' + base + '$2'); } else { value = EventeAttribute.attributes[item.name] ? EventeAttribute.attributes[item.name].check(node, item.name) : item.value; value = this.preparse(value); if ( value.match(regexp) ) { node.e_base[item.name] = value; value = value.replace(regexp, '$1' + base + '$2'); } } if ( item.value !== value ) { item.value = value; EventeParser.parseAttribute(node, item.name, this.model); this.model.applyAttribute(node, item.name); } } if ( !Object.keys(node.e_base).length ) delete node.e_base; items = node.childNodes; for ( i = 0; i < items.length; i++ ) { item = items[i]; if ( item instanceof Comment || item instanceof HTMLBRElement || item instanceof HTMLScriptElement ) continue; this.dealias(item, alias, base); } } }; EventeAttribute.attributes['e-base'] = EventeAttributeBase; /** * b-for attribute class * @extends EventeAttribute */ class EventeAttributeFor extends EventeAttribute { /** * @inheritdoc */ constructor(node, name, model) { let attribute = node.attributes[name], match = attribute.value.match(/^{{([a-z0-9_]+)\s+in\s+(.*?)(\s+key\s+([a-z0-9_]+))?}}$/im); attribute.value = '{{' + match[2] + '}}'; super(node, name, model); this.alias = match[1]; this.key = match[4]; this.template = node.children[0]; node.innerHTML = ''; } /** * @inheritdoc */ apply() { let i, key, child, remove = [], property = this.property(this.model), items = this.eval(this.model); for ( i in items ) { key = this.key !== undefined ? items[i][this.key] : i; child = this.node.querySelector('[e-key="' + key + '"]'); if ( child && child.e_index !== i ) { child.remove(); child = null; } if ( !child ) { child = this.template.cloneNode(true); child.e_index = i; child.setAttribute('e-key', key); this.dealias(child, '\\$index', i); this.dealias(child, '\\$key', key); this.dealias(child, this.alias, property + '.' + i); this.node.appendChild(child); EventeParser.parseNode(child, this.model); } } for ( i = 0; i < this.node.childNodes.length; i++ ) { child = this.node.childNodes[i]; if ( items === undefined || items[child.e_index] === undefined ) remove.push(child); } for ( i in remove ) { this.model.unlink(remove[i]); remove[i].remove(); } } /** * Change alias in expressions on base path * @private * @param {ChildNode | Element | Text} node DOM node * @param {string} alias Alias name * @param {string} base Base path */ dealias(node, alias, base) { let value, replace = new RegExp('(^|[^a-z])' + alias.replace(/\./g, '\\.') + '([^a-z]|$)', 'gim'), test = new RegExp('{{'); if ( node instanceof Text ) { value = node.nodeValue; if ( !value.match(test) ) return; value = this.preparse(value); if ( value.match(replace) ) node.nodeValue = value.replace(replace, '$1' + base + '$2'); return; } let i, attr, attrs = node.attributes; for ( i = 0; i < attrs.length; i++ ) { attr = attrs[i]; value = EventeAttribute.attributes[attr.name] ? EventeAttribute.attributes[attr.name].check(node, attr.name) : attr.value; if ( !value.match(test) ) continue; value = this.preparse(value); if ( value.match(replace) ) attr.value = value.replace(replace, '$1' + base + '$2'); } let item, items = node.childNodes; for ( i = 0; i < items.length; i++ ) { item = items[i]; if ( item instanceof Comment || item instanceof HTMLBRElement || item instanceof HTMLScriptElement ) continue; this.dealias(item, alias, base); } } }; EventeAttributeFor.priority = 99; EventeAttribute.attributes['e-for'] = EventeAttributeFor; /** * b-show and b-hide attribute class * @extends EventeAttribute */ class EventeAttributeHideShow extends EventeAttribute { /** * @inheritdoc */ constructor(node, name, model) { super(node, name, model); this.type = name; } /** * @inheritdoc */ apply() { if ( ( this.type == 'e-hide' && !this.eval(this.model) ) || ( this.type == 'e-show' && this.eval(this.model) ) ) this.node.style.display = ''; else this.node.style.display = 'none'; } }; EventeAttribute.attributes['e-hide'] = EventeAttributeHideShow; EventeAttribute.attributes['e-show'] = EventeAttributeHideShow; /** * b-model attribute class * @extends EventeAttribute */ class EventeAttributeModel extends EventeAttribute { /** * @inheritdoc */ constructor(node, name, model) { super(node, name, model); } /** * @inheritdoc */ apply() { let value = this.eval(this.model); if ( value !== undefined ) value = typeof value !== 'object' ? value.toString() : JSON.stringify(value); else value = ''; if ( this.node instanceof HTMLInputElement || this.node instanceof HTMLButtonElement || this.node instanceof HTMLTextAreaElement || this.node instanceof HTMLSelectElement ) { if ( this.node.value != value ) this.node.value = value; } else { if ( this.node.textContent != value ) this.node.textContent = value; } } /** * Get assotiated model field value * @returns {*} */ get() { let value = this.eval(this.model); return value !== undefined ? value : ''; } /** * Set assotiated model field value * @param {*} value */ set(value) { this.model.set(this.property(this.model), value); } }; EventeAttribute.attributes['e-model'] = EventeAttributeModel; /** * Evente Model class */ class EventeModel { /** * @param {Node} node DOM Node * @param {Object} data Initial model data */ constructor(node, data) { /** * @private * @type {Object} */ this.shadow = { ...data, strings: EventeStrings.strings }; /** * @private * @type {Object.<string, Object.<string, Set<Function>>>} */ this.listeners = { get: {}, set: {}, delete: {} }; /** * @private * @type {Object.<string, Set<Node>>} * */ this.links = {}; /** * @type {Proxy} */ this.proxy = null; node.addEventListener('input', EventeModel.eventHander, true); } /** * Get model data * @returns {Object} */ get data() { return this.proxy; } /** * Set model data * @param {Object} value */ set data(value) { value.strings = EventeStrings.strings; this.shadow = value; } /** * Get model field by path * @param {string} property Model path */ get(property) { return this.proxy.getField(property); } /** * Set model field by path * @param {string} property Model path * @param {*} value New value */ set(property, value) { this.proxy.setField(property, value); } /** * Add listener of model change events * @param {string} event Listening evente - get, set or delete * @param {string} property Path in model data * @param {Function} listener Listener function */ addListener(event, property, listener) { if ( !this.listeners[event] ) return; if ( !this.listeners[event][property] ) this.listeners[event][property] = new Set(); this.listeners[event][property].add(listener); } /** * Add listener of model change events * @param {string} event Listening evente - get, set or delete * @param {string} property Path in model data * @param {Function} listener Listener function */ removeListener(event, property, listener) { if ( this.listeners[event] && this.listeners[event][property] ) { this.listeners[event][property].delete(listener); if ( !this.listeners[event][property].size ) delete this.listeners[event][property]; } } /** * Get DOM nodes which dependent of link * @param {string} path Path in model data hierarchy * @returns {Set<Node>} */ getNodes(path) { let i, node, nodes = new Set(); for ( i in this.links ) { if ( !i.startsWith(path + '.') ) continue; for ( node of this.links[i] ) nodes.add(node); } while ( path != '' ) { if ( this.links[path] !== undefined ) { for ( node of this.links[path] ) nodes.add(node); } path = path.split('.').slice(0, -1).join('.'); } return nodes; } /** * Apply node attributes values * @param {Node} node DOM node */ applyAttributes(node) { if ( node.e_attributes === undefined ) return; if ( node instanceof Text ) { // TODO let value = node.e_attributes[''].eval(this); value = value !== undefined ? value.toString() : ''; if ( node.nodeValue !== value ) node.nodeValue = value; return; } let name, attribute; for ( name in node.e_attributes ) this.applyAttribute(node, name); } /** * Apply node attribute value * @param {Node} node DOM node * @param {string} name Atribute name */ applyAttribute(node, name) { if ( node.e_attributes === undefined || node.e_attributes[name] === undefined ) return; node.e_attributes[name].apply(); } /** * Update dependencies of DOMnode * @param {Node} node DOM node */ updateLinks(node) { var i, j, tmp, set = new Set(); for ( i in node.e_attributes ) { tmp = node.e_attributes[i].getLinks(); for ( j in tmp ) set.add(tmp[j]); } tmp = node.e_links || new Set(); for ( i of tmp ) { if ( !set.has(i) ) this.unlink(node, i) } for ( i of set ) { if ( !tmp.has(i) ) this.link(node, i); } } /** * Add dependency of DOM node * @param {Node} node DOM node * @param {string} property Path in model data */ link(node, property) { if ( this.links[property] === undefined ) this.links[property] = new Set(); this.links[property].add(node); if ( node.e_links === undefined ) node.e_links = new Set(); node.e_links.add(property); } /** * Remove dependency of DOM node * @param {Node} node DOM node * @param {string} [property] Path in model data */ unlink(node, property) { if ( property === undefined ) { if ( node.e_links !== undefined ) { for ( let link of node.e_links ) this.unlink(node, link); } let i, nodes = node.childNodes; for ( i = 0; i < nodes.length; i++ ) this.unlink(nodes[i]); } else { if ( this.links[property] !== undefined ) { this.links[property].delete(node); if ( this.links[property].size === 0 ) delete this.links[property]; } if ( node.e_links !== undefined ) { node.e_links.delete(property); if ( node.e_links.size === 0 ) delete node.e_links; } } } /** * Handle model data changes via DOM elements * @param {Event} event Event object */ static eventHander(event) { if ( !(event.target instanceof HTMLInputElement) && !(event.target instanceof HTMLButtonElement ) && !(event.target instanceof HTMLTextAreaElement) && !(event.target instanceof HTMLSelectElement) ) return; if ( event.target.e_attributes === undefined || event.target.e_attributes['e-model'] === undefined ) return; let model = event.target.e_attributes['e-model'], value_old = model.get(), value_new = event.target.value; if ( value_old === value_new ) return; model.set(value_new); } } /** * Evente Model Proxy Handler class */ class EventeModelProxyHandler { /** * @param {EventeModel} data */ constructor(data) { this.data = data; } deleteProperty(target, prop) { let data = this.data.shadow.getField(target.$); let listeners = this.data.listeners.delete[target.$]; if ( listeners ) { for ( let listener of listeners ) listener(data, target.$, prop); } delete data[prop]; let property = ( target.$ ? target.$ + '.' : '' ) + prop, node, nodes = this.data.getNodes(property); for ( node of nodes ) this.data.applyAttributes(node); return true; } get(target, prop) { if ( prop === 'constructor' ) return { name: 'Proxy' }; let data = this.data.shadow.getField(target.$); switch ( prop ) { case 'keys': return Object.keys(data); case 'length': return Object.keys(data).length; case 'toJSON': return function() { return data; }; case 'clone': return function() { return {...data}; }; } let listeners = this.data.listeners.get[target.$]; if ( listeners ) { for ( let listener of listeners ) listener(data, target.$, prop); } if ( data[prop] === undefined || data[prop] === null ) return; switch ( typeof data[prop] ) { case 'object': return new Proxy( { $: ( target.$ ? target.$ + '.' : '' ) + prop }, this ); default: return data[prop]; } } getPrototypeOf(target) { let data = this.data.shadow.getField(target.$); // Not Reflect.getPrototypeOf(data), for .. in not working return data; } has(target, prop) { let data = this.data.shadow.getField(target.$); return Reflect.has(data, prop); } isExtensible(target) { let data = this.data.shadow.getField(target.$); return Reflect.isExtensible(data); } ownKeys(target) { let data = this.data.shadow.getField(target.$); return Object.keys(data); } set(target, prop, value) { let data = this.data.shadow.getField(target.$), listeners = this.data.listeners.set[target.$]; if ( value.constructor.name === 'Proxy' ) value = value.clone(); if ( listeners ) { for ( let listener of listeners ) listener(data, target.$, prop, value); } if ( data[prop] !== value ) { data[prop] = value; let property = ( target.$ ? target.$ + '.' : '' ) + prop, node, nodes = this.data.getNodes(property); for ( node of nodes ) this.data.applyAttributes(node); } return true; } } /** * Evente HTML template parser */ class EventeParser { /** * Parse DOM node * @param {Node} node DOM node * @param {EventeModel} model EventeModel object */ static parseNode(node, model) { EventeParser.parseAttributes(node, model); if ( node instanceof Text ) { model.applyAttributes(node); return; } let i, item, items = node.childNodes; for ( i = 0; i < items.length; i++ ) { item = items[i]; if ( item instanceof Comment || item instanceof HTMLBRElement || item instanceof HTMLScriptElement ) continue; EventeParser.parseNode(item, model); } model.applyAttributes(node); } /** * Parse attributes of DOM node * @param {Node} node DOM node * @param {EventeModel} model EventeModel object */ static parseAttributes(node, model) { if ( node instanceof Text ) { if ( node.nodeValue.indexOf('{{') !== -1 ) { node.e_attributes = { '': new EventeExpression(node.nodeValue) }; model.updateLinks(node); } else { if ( node.e_attributes === undefined ) delete node.e_attributes; } return; } let i, attribute, attributes = EventeAttribute.getAttributes(); for ( i in attributes ) EventeParser.parseAttribute(node, attributes[i].name, model); for ( i = 0; i < node.attributes.length; i++ ) { attribute = node.attributes[i]; if ( EventeAttribute.attributes[attribute.name] === undefined ) EventeParser.parseAttribute(node, attribute.name, model); } if ( node.e_attributes ) model.updateLinks(node); } /** * Parse attribute DOM node * @param {Node} node DOM node * @param {string} name Attribute name * @param {EventeModel} model EventeModel object */ static parseAttribute(node, name, model) { let value, tmp = node.attributes[name]; if ( !tmp ) { if ( node.e_attributes ) delete node.e_attributes[name]; return; } if ( node.e_attributes && node.e_attributes[name] ) { let expression = '{{' + node.e_attributes[name].expression + '}}'; if ( expression === tmp.value ) return; } if ( EventeAttribute.attributes[name] ) { value = EventeAttribute.attributes[name].check(node, name); if ( tmp.value !== value ) tmp.value = value; tmp = new EventeAttribute.attributes[name](node, name, model); } else { if (tmp.value.indexOf('{{') === -1) return; tmp = new EventeAttribute(node, name, model); } if ( node.e_attributes === undefined ) node.e_attributes = {}; node.e_attributes[name] = tmp; } } const EventePipes = { empty: function(params) { return params[0] === undefined || params[0] === null ? ( params[1] ? params[1] : '' ) : ( params[2] ? params[2] : '' ); }, if: function(params) { var tmp = parseFloat(params[0]); if ( !isNaN(tmp) ) params[0] = tmp; return params[0] ? ( params[1] ? params[1] : '' ) : ( params[2] ? params[2] : '' ); }, max: function(params) { let tmp = EventePipes.reverse(params); return tmp ? tmp[0] : ''; }, min: function(params) { let tmp = EventePipes.sort(params); return tmp ? tmp[0] : ''; }, reverse: function(params) { let tmp = EventePipes.sort(params); return tmp ? tmp.reverse() : ''; }, sort: function(params) { if ( params[0] === undefined || params[0] === null ) return ''; let values = params[0] instanceof Array ? params[0].slice() : params[0].keys; if ( values === undefined ) return ''; return values.sort(); }, } /** * Evente Resource class */ class EventeResource { /** * @param {string} url Resource URL * @param {string} [type=json] Resource content type */ constructor(url, type) { this.url = url; this.type = type || 'json'; } /** * Send GET request * @param {Object} params Request parameters * @returns {Promise} */ get(params) { return this.method('get', params); } /** * Send POST request * @param {Object} params Request parameters * @returns {Promise} */ post(params) { return this.method('post', params); } /** * Send PUT request * @param {Object} params Request parameters * @returns {Promise} */ put(params) { return this.method('put', params); } /** * Send DELETE request * @param {Object} params Request parameters * @returns {Promise} */ delete(params) { return this.method('delete', params); } /** * Execute request method * @private * @param {string} method Method type * @param {Object} [params={}] Request parameters * @param {Object} [headers=EventeResource.headers] Request headers * @returns {Promise} */ method(method, params, headers) { params = params || {}; if ( params.constructor.name === 'Proxy' ) params = params.clone(); let url = this.url.replace(/\/:([-_0-9a-z]+)(\/|$)/ig, (match, param, end) => { let tmp = params[param] || ''; delete params[param]; return '/' + tmp + end; }); /** @type {RequestInit} */ let options = { mode: 'cors', method: method, headers: new Headers(headers || EventeResource.headers) }; switch ( method ) { case 'get': case 'delete': let key, tmp = []; for ( key in params ) tmp.push(key + '=' + encodeURIComponent(params[key])); url += '?' + tmp.join('&'); break; case 'post': case 'put': options.body = JSON.stringify(params); break; } if ( ['post', 'put'].indexOf(method) !== -1 ) options.body = JSON.stringify(params); return fetch(url, options).then(response => { this.ok = response.ok; this.status = response.status; switch ( this.type ) { case 'json': return response.json(); case 'form': return response.formData(); case 'text': return response.text(); } }).then(response => { if ( !this.ok ) { let error = new Error(); error.status = this.status; error.data = response; throw error; } return response; }); } } /** * Default headers * @type {Object} * @default {} */ EventeResource.headers = {}; /** * Evente Router class */ class EventeRouter { /** * * @param {Node} node */ constructor(node) { EventeRouter.routers.push(this); this.routes = {}; this.node = node; this.node.addEventListener('click', EventeRouter.clickHander, true); } /** * Add route * @param {string} route Route pattern * @param {Function} callback Callback function * @param {*} params Parameters passed to callback function */ add(route, callback, params) { route = this.normalize(route); this.routes[route] = { parts: route.split('/'), callback: callback, params: params || {}, }; } /** * Remove route * @param {string} route Route pattern */ remove(route) { route = this.normalize(route); delete this.routes[route]; } /** * Trigger route handling * @param {string} route Route * @param {boolean} push Flag to push route in history */ trigger(route, push) { if ( route === undefined ) route = location.pathname; this.handle(route, push); } /** * Handle route change * @param {string} route Route * @param {boolean} push Flag to push route in history * @returns {boolean} */ handle(route, push) { route = this.normalize(route); if ( this.routes[route] !== undefined ) { if ( push ) window.history.pushState({}, '', '/' + route); this.routes[route].callback(this.routes[route].params); return true; } let i, j, tmp, routes = Object.assign({}, this.routes), params = {}, part, parts = route.split('/'); for ( i in parts ) { part = parts[i]; for ( j in routes ) { if ( routes[j].parts.length !== parts.length ) { delete routes[j]; continue; } tmp = routes[j].parts[i]; if ( tmp === part ) continue; if ( tmp !== undefined && tmp[0] === ':' ) params[ tmp.substr(1) ] = part; else delete routes[j]; } } if ( Object.keys(routes).length ) { if ( push ) window.history.pushState({}, '', '/' + route); for ( j in routes ) routes[j].callback(Object.assign(routes[j].params, params)); } return Object.keys(routes).length > 0; } /** * Normalize route form * @param {string} route Route * @returns {string} */ normalize(route) { if ( route.startsWith(location.origin) ) route = route.substr(location.origin.length); if ( route.startsWith('//' + location.host) ) route = route.substr(('//' + location.host).length); if ( route.startsWith('/') ) route = route.substr(1); if ( route.endsWith('/') ) route = route.substr(0, route.length - 1); return route; } /** * Get router by DOM node * @param {Node} node DOM node * @returns {EventeRouter} */ static getRouter(node) { for ( let i in EventeRouter.routers ) { let router = EventeRouter.routers[i]; if ( router.node === node || router.node.contains(node) ) return router; } } /** * Handle clck event * @param {Event} event Event object */ static clickHander(event) { let target = event.target; while ( !(target instanceof HTMLAnchorElement) ) { target = target.parentNode; if ( target instanceof HTMLDocument ) return; } let router = EventeRouter.getRouter(target); if ( !router ) return; let route = target.getAttribute('href'); if ( route && router.handle(route, true) ) event.preventDefault(); } /** * Handle URL change */ static popstateHandler() { for ( let i in EventeRouter.routers ) EventeRouter.routers[i].handle(location.href); } } EventeRouter.routers = []; window.addEventListener('popstate', EventeRouter.popstateHandler); /** * Class for operations with DOM JQuery-like way * @extends Array */ class EventeSelector extends Array { constructor(options, selector) { super(); if ( options !== undefined ) { switch (options.constructor.name) { case 'String': if ( options.length > 0 ) this.push(...document.querySelectorAll(options)); break; case 'Array': this.push(...options); break; default: if ( options instanceof HTMLElement ) this.push(options); else console.warn('Selector: Unknown constructor name - ' + options.constructor.name + '!'); } } Object.defineProperty(this, 'selector', { enumerable: false, writable: true }); this.selector = selector; } addClass(classes) { return this.classes('add', classes); } attr(name, value) { return this.forEach({ 'action': 'attr', 'name': name, 'value': value }); } closest(selector) { return this.forEach({ 'action': 'closest', 'selector': selector }); } contains(node) { return this.forEach({ 'action': 'contains', 'node': node }); } end() { return this.selector; } find(selector) { return this.forEach({ 'action': 'find', 'selector': selector }); } get(index) { return this[index]; } hasClass(className, all) { return this.forEach({ 'action': 'hasClass', 'class': className, 'all': all }); } html(html) { return this.forEach({ 'action': 'html', 'value': html }); } is(selector, all) { return this.forEach({ 'action': 'is', 'selector': selector, 'all': all }); } parent() { return this.forEach({ 'action': 'parent' }); } removeClass(classes) { return this.classes('remove', classes); } text(text) { return this.forEach({ 'action': 'text', 'value': text }); } toggleClass(classes, active) { return this.classes('toggle', classes); } val(value) { return this.forEach({ 'action': 'val', 'value': value }); } classes(action, classes, active) { if ( typeof classes === 'string' ) classes = classes.split(' '); for ( let i in this ) { for ( let j in classes ) { if ( action === 'toggle' ) { this[i].classList.toggle(classes[j], active); } else { this[i].classList[action](classes[j]); } } } return this; } forEach(options) { if ( options.value !== undefined ) { for ( let i in this ) { switch ( options.action ) { case 'attr': this[i].setAttribute(options.name, options.value); break; case 'html': this[i].innerHTML = options.value; break; case 'text': this[i].textContent = options.value; break; case 'val': if ( this[i] instanceof HTMLInputElement ) this[i].value = options.value; break; } } return this; } if ( this.length === 0 ) return undefined; let i, tmp, result = []; for ( i in this ) { switch ( options.action ) { case 'attr': tmp = this[i].getAttribute(options.name); result.push(tmp !== null ? tmp : undefined ); break; case 'closest': tmp = this[i].parentNode; while ( !tmp.matches(options.selector) ) { tmp = tmp.parentNode; if ( tmp instanceof HTMLDocument ) { tmp = null; break; } } result.push(tmp); break; case 'contains': if ( this[i] === options.node || this[i].contains(options.node) ) return true; break; case 'find': result.push(...this[i].querySelectorAll(options.selector)); break; case 'html': result.push(this[i].innerHTML); break; case 'hasClass': tmp = this[i].classList.contains(options.class); if ( options.all !== true ) { if ( tmp ) return true; } else { if ( !tmp ) return false; } break; case 'is': tmp = this[i].matches(options.selector); if ( options.all !== true ) { if ( tmp ) return true; } else { if ( !tmp ) return false; } break; case 'parent': result.push(this[i].parentNode); break; case 'text': result.push(this[i].textContent); break; case 'val': result.push(this[i] instanceof HTMLInputElement ? this[i].value : undefined); break; } } switch ( options.action ) { case 'contains': return false; case 'closest': case 'find': case 'parent': return new EventeSelector(result, this); case 'hasClass': case 'is': return options.all === true ? true : false; default: return result.length > 1 ? result : result[0]; } } }; if ( typeof $ === 'undefined' ) var $ = function(selector) { return new EventeSelector(selector); } /** * Evente Strings class */ class EventeStrings { /** * Get index of string * @param {string} string String to get index * @returns {number} */ static getIndex(string) { var index = EventeStrings.strings.indexOf(string); if ( index === -1 ) { EventeStrings.strings.push(string); index = EventeStrings.strings.indexOf(string); } return index; } } EventeStrings.strings = [];
/** * @param {number[]} nums * @return {number} */ var maxSubArray = function(nums) { if (!nums || !nums.length) { return []; } let max = { start: 0, end: 0, val: nums[0] }; const dp = [{ start: 0, end: 0, val: nums[0] }]; for (let ii = 1; ii < nums.length; ii++) { dp[ii] = {}; dp[ii].end = ii; if ((dp[ii - 1].val + nums[ii]) < nums[ii]) { dp[ii].start = ii; dp[ii].val = nums[ii]; } else { dp[ii].start = dp[ii - 1].start; dp[ii].val = dp[ii - 1].val + nums[ii]; } if (max.val < dp[ii].val) { max = dp[ii]; } } return max.val; }; console.log(6, maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]));
/* * Globalize Culture tn * * http://github.com/jquery/globalize * * Copyright Software Freedom Conservancy, Inc. * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * This file was generated by the Globalize Culture Generator * Translation: bugs found in this file need to be fixed in the generator */ (function (window, undefined) { var Globalize; if (typeof require !== "undefined" && typeof exports !== "undefined" && typeof module !== "undefined") { // Assume CommonJS Globalize = require("globalize"); } else { // Global variable Globalize = window.Globalize; } Globalize.addCultureInfo("tn", "default", { name: "tn", englishName: "Setswana", nativeName: "Setswana", language: "tn", numberFormat: { percent: { pattern: ["-%n", "%n"] }, currency: { pattern: ["$-n", "$ n"], symbol: "R" } }, calendars: { standard: { days: { names: ["Latshipi", "Mosupologo", "Labobedi", "Laboraro", "Labone", "Labotlhano", "Lamatlhatso"], namesAbbr: ["Ltp.", "Mos.", "Lbd.", "Lbr.", "Lbn.", "Lbt.", "Lmt."], namesShort: ["Lp", "Ms", "Lb", "Lr", "Ln", "Lt", "Lm"] }, months: { names: ["Ferikgong", "Tlhakole", "Mopitloe", "Moranang", "Motsheganong", "Seetebosigo", "Phukwi", "Phatwe", "Lwetse", "Diphalane", "Ngwanatsele", "Sedimothole", ""], namesAbbr: ["Fer.", "Tlhak.", "Mop.", "Mor.", "Motsh.", "Seet.", "Phukw.", "Phatw.", "Lwets.", "Diph.", "Ngwan.", "Sed.", ""] }, patterns: { d: "yyyy/MM/dd", D: "dd MMMM yyyy", t: "hh:mm tt", T: "hh:mm:ss tt", f: "dd MMMM yyyy hh:mm tt", F: "dd MMMM yyyy hh:mm:ss tt", M: "dd MMMM", Y: "MMMM yyyy" } } } }); }(this));
import Component from '@glimmer/component'; import { action } from '@ember/object'; import { createPopper } from '@popperjs/core'; export default class TooltipComponent extends Component { _popper = null; @action setup(element) { this._popper = createPopper(this.args.target, element, this.args.options ?? {}); } get applicationElement() { return document.querySelector('.ember-application'); } willDestroy() { super.willDestroy(...arguments); if (this._popper) { this._popper.destroy(); } } }
mix.declare("mix.coll.HashMap", ["mix.Utils", "mix.Detector"], function(Utils, Detector) { var E; mix.declare("mix.coll.Entry", function() { function Entry(key, value) { this.key = key; this.value = value; this.next = null; } return E = Entry; }); "use strict"; var isSymbolAvailable = Detector.symbol.has("for"); var entriesSymbol = isSymbolAvailable ? window.Symbol.for("_entries_") : "_entries_"; var sizeSymbol = isSymbolAvailable ? window.Symbol.for("_size_") : "_size_"; var hashFn = isSymbolAvailable ? window.Symbol.for("_hashFn_") : "_hashFn_"; var equalKeysFn = isSymbolAvailable ? window.Symbol.for("_equalKeysFn_") : "_equalKeysFn_"; var iteratorSymbol = Detector.symbol.iterator ? window.Symbol.iterator : "@@iterator"; function hashCode(o) { return o; } function keysEquality(a, b) { return a === b; } function HashMap(hashCodeFn, keysEqualFn) { this[hashFn] = Utils.isFunction(hashCodeFn) ? hashCodeFn : hashCode; this[equalKeysFn] = Utils.isFunction(keysEqualFn) ? keysEqualFn : keysEquality; this[entriesSymbol] = {}; this[sizeSymbol] = 0; } HashMap.prototype.hash = function hash() { return this[entriesSymbol]; }; HashMap.prototype.key = function key(k) { return this[hashFn](k); }; HashMap.prototype.equalKeys = function equalKeys(a, b) { return this[equalKeysFn](a, b); }; /** * Iterates over all elements in this map * @param fn a function(value, key, map) * @param thisArg to be used as <b>this</b> for callback call * @returns {HashMap} this */ HashMap.prototype.forEach = function forEach(fn, thisArg) { Utils.awaitFunction(fn); var entries = this.hash(); for(var k in entries) { for(var ent = entries[k]; !ent; ent = ent.next) { fn.call(thisArg, ent.value, ent.key, this); } } return this; }; HashMap.prototype.set = function set(k, v) { "use strict"; var key = this.key(k); var entries = this.hash(); for(var ent = entries[key], last = null; ent !== undefined; last = ent, ent = ent.next) { if(this.equalKeys(k, ent.key)) { ent.value = v; return this; } } entries[key] = new E(k, v, last); this[sizeSymbol] += 1; return this; }; HashMap.prototype.get = function get(k) { "use strict"; var key = this.key(k); var entries = this.hash(); for(var ent = entries[key]; ent !== undefined; ent = ent.next) { if(this.equalKeys(k, ent.key)) { return ent.value; } } return null; }; HashMap.prototype["delete"] = function(k) { "use strict"; var key = this.key(k); var entries = this.hash(); for(var ent = entries[key], last = null; ent !== undefined; last = ent, ent = ent.next) { if(this.equalKeys(k, ent.key)) { if(last !== null) { last.next = ent.next; } else if(ent.next) { entries[key] = ent.next; } else { delete entries[key]; } this[sizeSymbol] -= 1; return true; } } return false; }; HashMap.prototype.entries = HashMap.prototype[iteratorSymbol] = function entries() { "use strict"; var index = 0; var entries = this.hash(); var keys = Object.keys(entries); var ent = index < keys.length ? entries[keys[index++]] : null; var iter = { next: function EntryInterator() { if(!ent) { return { done: true, value: undefined }; } else { var res = { done: false, value: [ent.key, ent.value] }; if(ent.next) { ent = ent.next; } else { ent = index < keys.length ? entries[keys[index++]] : null; } return res; } } }; iter[iteratorSymbol] = function() { return iter; }; return iter; }; HashMap.prototype.keys = function keys() { "use strict"; var index = 0; var entries = this.hash(); var keys = Object.keys(entries); var ent = index < keys.length ? entries[keys[index++]] : null; var iter = { next: function KeyIterator() { if(!ent) { return { done: true, value: undefined }; } else { var res = { done: false, value: ent.key }; if(ent.next) { ent = ent.next; } else { ent = index < keys.length ? entries[keys[index++]] : null; } return res; } } }; iter[iteratorSymbol] = function() { return iter; }; return iter; }; HashMap.prototype.values = function values() { "use strict"; var index = 0; var entries = this.hash(); var keys = Object.keys(entries); var ent = index < keys.length ? entries[keys[index++]] : null; var iter = { next: function ValueIterator() { if(!ent) { return { done: true, value: undefined }; } else { var res = { done: false, value: ent.value }; if(ent.next) { ent = ent.next; } else { ent = index < keys.length ? entries[keys[index++]] : null; } return res; } } }; iter[iteratorSymbol] = function() { return iter; }; return iter; }; HashMap.prototype.has = function has(k) { "use strict"; var key = this.key(k); var entries = this.hash(); for(var ent = entries[key]; ent !== undefined; ent = ent.next) { if(this.equalKeys(k, ent.key)) { return true; } } return false; }; HashMap.prototype.clear = function clear() { "use strict"; var entries = this.hash(); for(var k in entries) { delete entries[k]; } this[sizeSymbol] = 0; return this; }; HashMap.prototype.toString = function toString() { return "[object HashMap]"; }; HashMap.prototype.clone = function clone() { var entries = this.hash(); var c = new HashMap(this[hashFn], this[equalKeysFn]); for(var key in entries) { for(var ent = entries[key]; ent !== undefined; ent = ent.next) { c.set(ent.key, ent.value); } } return c; }; Object.defineProperty(HashMap.prototype, "size", { get: function size() { "use strict"; return this[sizeSymbol]; } }); return HashMap; });
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.2.3.7-5-b-245 description: > Object.defineProperties - 'descObj' is a Date object which implements its own [[Get]] method to get 'set' property (8.10.5 step 8.a) includes: [runTestCase.js] ---*/ function testcase() { var data = "data"; var descObj = new Date(); var setFun = function (value) { data = value; }; descObj.prop = { set: setFun }; var obj = {}; Object.defineProperties(obj, descObj); obj.prop = "dateData"; return obj.hasOwnProperty("prop") && data === "dateData"; } runTestCase(testcase);
/** * THIS IS THE ENTRY POINT FOR THE CLIENT, JUST LIKE server.js IS THE ENTRY POINT FOR THE SERVER. */ import 'babel/polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import createHistory from 'history/lib/createBrowserHistory'; import createStore from './redux/create'; import ApiClient from './helpers/ApiClient'; import io from 'socket.io-client'; import {Provider} from 'react-redux'; import {reduxReactRouter, ReduxRouter} from 'redux-router'; import getRoutes from './routes'; const client = new ApiClient(); const dest = document.getElementById('content'); const store = createStore(reduxReactRouter, null, createHistory, client, window.__data); function initSocket() { const socket = io('', {path: '/api/ws', transports: ['polling']}); socket.on('news', (data) => { console.log(data); socket.emit('my other event', { my: 'data from client' }); }); socket.on('msg', (data) => { console.log(data); }); return socket; } global.socket = initSocket(); const component = ( <Provider store={store} key="provider"> <ReduxRouter routes={getRoutes(store)} /> </Provider> ); ReactDOM.render(component, dest); if (process.env.NODE_ENV !== 'production') { window.React = React; // enable debugger if (!dest || !dest.firstChild || !dest.firstChild.attributes || !dest.firstChild.attributes['data-react-checksum']) { console.error('Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.'); } } // if (__DEVTOOLS__) { // const { DevTools, DebugPanel, LogMonitor } = require('redux-devtools/lib/react'); // ReactDOM.render(<div> // {component} // <DebugPanel top right bottom key="debugPanel"> // <DevTools store={store} monitor={LogMonitor}/> // </DebugPanel> // </div>, dest); // }
// // Vivado(TM) // rundef.js: a Vivado-generated Runs Script for WSH 5.1/5.6 // Copyright 1986-2015 Xilinx, Inc. All Rights Reserved. // var WshShell = new ActiveXObject( "WScript.Shell" ); var ProcEnv = WshShell.Environment( "Process" ); var PathVal = ProcEnv("PATH"); if ( PathVal.length == 0 ) { PathVal = "D:/Xilinx/Vivado/2015.4/ids_lite/ISE/bin/nt64;D:/Xilinx/Vivado/2015.4/ids_lite/ISE/lib/nt64;D:/Xilinx/Vivado/2015.4/bin;"; } else { PathVal = "D:/Xilinx/Vivado/2015.4/ids_lite/ISE/bin/nt64;D:/Xilinx/Vivado/2015.4/ids_lite/ISE/lib/nt64;D:/Xilinx/Vivado/2015.4/bin;" + PathVal; } ProcEnv("PATH") = PathVal; var RDScrFP = WScript.ScriptFullName; var RDScrN = WScript.ScriptName; var RDScrDir = RDScrFP.substr( 0, RDScrFP.length - RDScrN.length - 1 ); var ISEJScriptLib = RDScrDir + "/ISEWrap.js"; eval( EAInclude(ISEJScriptLib) ); ISEStep( "vivado", "-log Stack.vds -m64 -mode batch -messageDb vivado.pb -notrace -source Stack.tcl" ); function EAInclude( EAInclFilename ) { var EAFso = new ActiveXObject( "Scripting.FileSystemObject" ); var EAInclFile = EAFso.OpenTextFile( EAInclFilename ); var EAIFContents = EAInclFile.ReadAll(); EAInclFile.Close(); return EAIFContents; }
import expect from 'expect'; import { shallow } from 'enzyme'; import React from 'react'; import { LoginButton } from '../login-button'; describe('<LoginButton />', () => { it('should render RaisedButton', () => { const app = shallow(<LoginButton />); expect(app.find('RaisedButton').length).toEqual(1); }); it('should render ActionExitToApp', () => { const app = shallow(<LoginButton />); expect(app.find('ActionExitToApp').length).toEqual(1); }); });
// Представление мира. var WorldView = function (world) { var me = this; me.world = world; world.view = me; // Полотно для рисования. me.paper = Snap(me.world.width, me.world.height); // Режим выделения. me._isGlobalSelectionOn = true; me._generateLandscape('trees', 80, 'rgb(0,GG,0)'); me._generateLandscape('animals', 20, 'rgb(RR,GG,BB)'); // Создаем представления городов. me._createCitiesView(); }; // Генерируем ладшафт. WorldView.prototype._generateLandscape = function (collName, count, color) { var me = this; var landItemSize = Utils.getRandom(40, 60); for (var i = 0; i < count; i++) { var landItem = me.paper.g().add(svgLib.get(collName, -1)); var box = landItem.getBBox(); var scale = Math.min(landItemSize / box.width, landItemSize / box.height); var x, y, isDotValid; do { x = Utils.getRandom(0, me.world.width - landItemSize); y = Utils.getRandom(0, me.world.height - landItemSize); isDotValid = me._isLandscapeItemInCities(x, y, landItemSize); } while (!isDotValid); landItem.attr({ transform: 'S' + scale + 'T' + (x - 50) + ',' + (y - 50), //опытным путем выяснил что элемент после трасформации находится не там где хотелось, поэтому -50. fill: Utils.getRandomColor(color) }); me.paper.append(landItem); } }; WorldView.prototype._isLandscapeItemInCities = function (x, y, size) { var me = this; for (var i = 0; i < me.world.cities.length; i++) { var city = me.world.cities[i]; if (Utils.geometry.isInCircle(city.x, city.y, city.r + size, x, y)) { return false; } } return true; }, // Создает представления городов. WorldView.prototype._createCitiesView = function () { var me = this; for (var i = 0; i < me.world.cities.length; i++) { new CityView(me.world.cities[i]); } }; // Отрисовка мира. WorldView.prototype.render = function () { var me = this; // Отрисовка городов. for (var i = 0; i < me.world.cities.length; i++) { me.world.cities[i].view.render(); } // Навешиваем событие глобального выделения и выделяем города и в процессе выделения. me._bindGlobalSelection(function OnSelection(selection) { for (var i = 0; i < me.world.cities.length; i++) { var city = me.world.cities[i]; var cityX1 = (city.x - city.r); var cityY1 = (city.y - city.r); var cityX2 = (city.x + city.r); var cityY2 = (city.y + city.r); var isCitySelected = (selection.x1 <= cityX1 && selection.y1 <= cityY1 && selection.x2 >= cityX2 && selection.y2 >= cityY2); city.view.setSelection(isCitySelected); } }); }; // Навешивает событие для глобального выделения. WorldView.prototype._bindGlobalSelection = function (onSelectionCallback) { var me = this; var paper = me.paper; var selection; var isSelectionStarted = false; var rectStart = { x: 0, y: 0 }; var rect = paper.rect(0, 0, 0, 0); rect.attr({ fill: 'rgba(0,0,255,0.3)', stroke: 'rgba(0,0,255,0.5)' }); rect.addClass('hide'); $(paper.node).on('mousedown', function onDragStart(ev) { if (me._isGlobalSelectionOn) { selection = { x1: 0, y1: 0, x2: 0, y2: 0 }; var x = ev.pageX; var y = ev.pageY; rectStart.x = x; rectStart.y = y; rect.attr({ x: x, y: y, width: 1, height: 1 }); rect.removeClass('hide'); isSelectionStarted = true; } else { rect.addClass('hide'); isSelectionStarted = false; } }).on('mousemove', function onDragMove(ev) { if (me._isGlobalSelectionOn && isSelectionStarted) { var x = ev.pageX; var y = ev.pageY; var x1 = Math.min(rectStart.x, x); var y1 = Math.min(rectStart.y, y); var w = Math.abs(rectStart.x - x); var h = Math.abs(rectStart.y - y); selection = { x1: x1, y1: y1, x2: x1 + w, y2: y1 + h }; rect.attr({ x: x1, y: y1, width: w, height: h }); if (me._isGlobalSelectionOn && $.isFunction(onSelectionCallback)) { onSelectionCallback(selection); } } else { rect.addClass('hide'); isSelectionStarted = false; } }).on('mouseup', function onDragEnd(ev) { rect.addClass('hide'); isSelectionStarted = false; if (me._isGlobalSelectionOn && isSelectionStarted && $.isFunction(onSelectionCallback)) { onSelectionCallback(selection); } }); }; // Включает или выключает режим глобального выделения. WorldView.prototype.setGlobalSelection = function (isOn) { this._isGlobalSelectionOn = isOn; }; // Снимает выделение со всех городов. WorldView.prototype.deselectAllCities = function (isOn) { var me = this; for (var i = 0; i < me.world.cities.length; i++) { me.world.cities[i].view.setSelection(false); }; };
var fs = require('fs') var path = require('path') // Load banks var banks = {} var banksFolders = fs.readdirSync(path.join(__dirname, '/banks/')) for (var i = 0; i < banksFolders.length; i++) { banks[banksFolders[i]] = require(path.join(__dirname, '/banks/' + banksFolders[i] + '/index.js')) } exports.Boleto = require('./lib/boleto')(banks) exports.EdiParser = require('./lib/edi-parser')(banks)
export { SetUserInfo } from './set-user-info';
var path = require('path') var dataRootDir = process.env.MULTIPLOT_DATA_ROOT if (!dataRootDir) { console.log('Note: please specify the MULTIPLOT_DATA_ROOT environment variable in order to visualize your specific data') dataRootDir = path.normalize(path.join(__dirname, '..', 'example_data')) } module.exports = dataRootDir
'use strict'; var mongoose = require('mongoose'); var UserSchema = new mongoose.Schema({ email: String, username: String, password: String, profile_picture: String, description: String, created_at: Date, updated_at: Date, language: String }); UserSchema.methods.customCreate = function (cb) { // console.log('in customCreate ', this.save); this.created_at = new Date(); this.updated_at = new Date(); this.language = 'en_US'; this.description = this.description || ''; this.profile_picture = this.profile_picture || ''; this.save(cb); }; UserSchema.methods.passwordMatches = function (password) { return this.password === password; }; //UserSchema.methods.toto = ... var UserModel = mongoose.model('User', UserSchema); module.exports = UserModel;
import * as React from 'react'; import Box from '@mui/material/Box'; import Slider from '@mui/material/Slider'; function valuetext(value) { return `${value}°C`; } export default function ColorSlider() { return ( <Box sx={{ width: 300 }}> <Slider aria-label="Temperature" defaultValue={30} getAriaValueText={valuetext} color="secondary" /> </Box> ); }
var del = require('del') , gulp = require('gulp') , chmod = require('gulp-chmod') , concat = require('gulp-concat') , header = require('gulp-header') , rename = require('gulp-rename') , size = require('gulp-size') , trim = require('gulp-trimlines') , uglify = require('gulp-uglify') , wrapUmd = require('gulp-wrap') , request = require('request') , fs = require('fs') , pkg = require('./package.json') var headerLong = ['/*!' , '* <%= pkg.name %> - <%= pkg.description %>' , '* @version <%= pkg.version %>' , '* <%= pkg.homepage %>' , '*' , '* @copyright <%= pkg.author %>' , '* @license <%= pkg.license %>' , '*' , '* BUILT: <%= pkg.buildDate %>' , '*/;' , ''].join('\n') var headerShort = '/*! <%= pkg.name %> v<%= pkg.version %> <%= pkg.license %>*/;' // all files in the right order (currently we don't use any dependency management system) var parts = [ 'src/svg.js' , 'src/regex.js' , 'src/utilities.js' , 'src/default.js' , 'src/color.js' , 'src/array.js' , 'src/pointarray.js' , 'src/patharray.js' , 'src/number.js' , 'src/element.js' , 'src/fx.js' , 'src/boxes.js' , 'src/matrix.js' , 'src/point.js' , 'src/attr.js' , 'src/transform.js' , 'src/style.js' , 'src/parent.js' , 'src/ungroup.js' , 'src/container.js' , 'src/viewbox.js' , 'src/event.js' , 'src/defs.js' , 'src/group.js' , 'src/arrange.js' , 'src/mask.js' , 'src/clip.js' , 'src/gradient.js' , 'src/pattern.js' , 'src/doc.js' , 'src/shape.js' , 'src/bare.js' , 'src/use.js' , 'src/rect.js' , 'src/ellipse.js' , 'src/line.js' , 'src/poly.js' , 'src/pointed.js' , 'src/path.js' , 'src/image.js' , 'src/text.js' , 'src/textpath.js' , 'src/nested.js' , 'src/hyperlink.js' , 'src/marker.js' , 'src/sugar.js' , 'src/set.js' , 'src/data.js' , 'src/memory.js' , 'src/selector.js' , 'src/helpers.js' , 'src/polyfill.js' ] gulp.task('clean', function() { return del([ 'dist/*' ]) }) /** * Compile everything in /src to one unified file in the order defined in the MODULES constant * wrap the whole thing in a UMD wrapper (@see https://github.com/umdjs/umd) * add the license information to the header plus the build time stamp‏ */ gulp.task('unify', ['clean'], function() { pkg.buildDate = Date() return gulp.src(parts) .pipe(concat('svg.js', { newLine: '\n' })) // wrap the whole thing in an immediate function call .pipe(wrapUmd({ src: 'src/umd.js'})) .pipe(header(headerLong, { pkg: pkg })) .pipe(trim({ leading: false })) .pipe(chmod(0o644)) .pipe(gulp.dest('dist')) .pipe(size({ showFiles: true, title: 'Full' })) }) /** ‎* uglify the file and show the size of the result * add the license info * show the gzipped file size */ gulp.task('minify', ['unify'], function() { return gulp.src('dist/svg.js') .pipe(uglify()) .pipe(rename({ suffix:'.min' })) .pipe(size({ showFiles: true, title: 'Minified' })) .pipe(header(headerShort, { pkg: pkg })) .pipe(chmod(0o644)) .pipe(gulp.dest('dist')) .pipe(size({ showFiles: true, gzip: true, title: 'Gzipped' })) }) /** ‎* rebuild documentation using documentup */ gulp.task('docs', function() { fs.readFile('README.md', 'utf8', function (err, data) { request.post( 'http://documentup.com/compiled' , { form: { content: data, name: 'SVG.js', theme: 'v1' } } , function (error, response, body) { // Replace stylesheet body = body.replace('//documentup.com/stylesheets/themes/v1.css', 'svgjs.css') // Write file fs.writeFile('docs/index.html', body, function(err) {}) } ) }) }) gulp.task('default', ['clean', 'unify', 'minify'])
var webpack = require("webpack"); module.exports = { entry: [ "./src/main" ], output: { path: __dirname + '/build/', filename: 'bundle.js', publicPath: '/build/', library: "stately", libraryTarget: "umd" }, resolve: { extensions: ['', '.js', '.jsx'] }, externals: { "lodash": "lodash" }, module: { loaders: [{ test: /\.jsx?$/, loaders: ['babel'], exclude: /node_modules.*(babel.*|babel-core.*|babel-loader.*|react.*|webpack.*|react.*|react-hot-loader.*|webpack-dev-server)/ }] } }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const http = require("http"); const _debug = require("debug"); const app_1 = require("./app"); const postgres_1 = require("./helpers/db/postgres"); const config_1 = require("./config"); const debug = _debug('bear:app'); const PORT = config_1.default.server.port; const HOST = config_1.default.server.host; const server = http.createServer(app_1.default); // connect to db postgres_1.initializeDb() .then(() => { console.log('Database connected successfully'); server.listen(PORT, HOST); server.on('listening', () => { const address = server.address(); console.log('🚀 Starting server on %s:%s', address.address, address.port); console.log('Press CTRL-C to stop\n'); }); server.on('error', (err) => { console.log(`⚠️ ${err}`); throw err; }); }) .catch((err) => { console.log(err); process.exit(1); }); process.on('SIGINT', () => { console.log('shutting down!'); postgres_1.disconnect(); // 关闭数据库 server.close(); process.exit(); }); process.on('uncaughtException', (error) => { console.log(`uncaughtException: ${error.message}`); console.log(error.stack); debug(error.stack); process.exit(1); }); //# sourceMappingURL=index.js.map
// @flow import React from 'react' import {Map} from 'react-leaflet' import AddTripPatternLayer from '../add-trip-pattern-layer' import {mockWithProvider, mockSegment} from '../../../utils/mock-data' describe('Project-Map > AddTripPatternLayer', () => { it('renders correctly', () => { // mount component expect(mockWithProvider( <Map> <AddTripPatternLayer segments={[mockSegment]} bidirectional={false} /> </Map> ).snapshot()).toMatchSnapshot() }) })
/* global window: true */ (function (w) { 'use strict'; var routes = []; var map = {}; var reference = 'routie'; var oldReference = w[reference]; var ROUTE_CTX_BEFORE = 'before'; var ROUTE_CTX_AFTER = 'after'; var previousRoute = ''; var Route = function (path, name) { this.name = name; this.path = path; this.keys = []; this.fns = []; this.beforeFn = undefined; this.afterFn = undefined; this.params = {}; this.regex = pathToRegexp(this.path, this.keys, false, false); }; Route.prototype.addHandler = function (fn, ctx) { switch (ctx) { case ROUTE_CTX_BEFORE: this.beforeFn = fn; break; case ROUTE_CTX_AFTER: this.afterFn = fn; break; default: this.fns.push(fn); } }; Route.prototype.removeHandler = function (fn) { for (var i = 0, c = this.fns.length; i < c; i++) { var f = this.fns[i]; if (fn === f) { this.fns.splice(i, 1); return; } } }; Route.prototype.run = function (params) { var self = this; var next = function() { self.next(params); }; if (this.beforeFn !== undefined) { this.beforeFn.apply(this, [getHash(), previousRoute, next]); } else { this.next(params); } previousRoute = getHash(); }; Route.prototype.next = function(params) { var i, c; var self = this; var next = function() { self.afterFn.apply(this, [getHash(), previousRoute]); }; params.push(next); for (i = 0, c = this.fns.length; i < c; i++) { this.fns[i].apply(this, params); } }; Route.prototype.match = function (path, params) { var m = this.regex.exec(path); if (!m) { return false; } for (var i = 1, len = m.length; i < len; ++i) { var key = this.keys[i - 1]; var val = ('string' === typeof m[i]) ? decodeURIComponent(m[i]) : m[i]; if (key) { this.params[key.name] = val; } params.push(val); } return true; }; Route.prototype.toURL = function (params) { var path = this.path; for (var param in params) { if (params.hasOwnProperty(param)) { path = path.replace('/:' + param, '/' + params[param]); } } path = path.replace(/\/:.*\?/g, '/').replace(/\?/g, ''); if (path.indexOf(':') !== -1) { throw new Error('missing parameters for url: ' + path); } return path; }; var pathToRegexp = function (path, keys, sensitive, strict) { if (path instanceof RegExp) { return path; } if (path instanceof Array) { path = '(' + path.join('|') + ')'; } path = path .concat(strict ? '' : '/?') .replace(/\/\(/g, '(?:/') .replace(/\+/g, '__plus__') .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, function (_, slash, format, key, capture, optional) { keys.push({ name: key, optional: !!optional }); slash = slash || ''; return '' + (optional ? '' : slash) + '(?:' + (optional ? slash : '') + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')' + (optional || ''); }) .replace(/([\/.])/g, '\\$1') .replace(/__plus__/g, '(.+)') .replace(/\*/g, '(.*)'); return new RegExp('^' + path + '$', sensitive ? '' : 'i'); }; var addHandler = function (path, fn, ctx) { var s = path.split(' '); var name = (s.length === 2) ? s[0] : null; path = (s.length === 2) ? s[1] : s[0]; if (!map[path]) { map[path] = new Route(path, name); routes.push(map[path]); } if (ctx === ROUTE_CTX_BEFORE) { map[path].addHandler(fn, ROUTE_CTX_BEFORE, path); return; } if (ctx === ROUTE_CTX_AFTER) { map[path].addHandler(fn, ROUTE_CTX_AFTER); return; } map[path].addHandler(fn); }; var routie = function (path, fn) { if (typeof fn === 'function') { addHandler(path, fn); routie.reload(); } else if (typeof path === 'object') { for (var p in path) { if (path.hasOwnProperty(p)) { addHandler(p, path[p]); } } routie.reload(); } else if (typeof fn === 'undefined') { routie.navigate(path); } }; routie.lookup = function (name, obj) { for (var i = 0, c = routes.length; i < c; i++) { var route = routes[i]; if (route.name === name) { return route.toURL(obj); } } }; routie.remove = function (path, fn) { var route = map[path]; if (!route) { return; } route.removeHandler(fn); }; routie.removeAll = function () { map = {}; routes = []; }; routie.navigate = function (path, options) { options = options || {}; var silent = options.silent || false; if (silent) { removeListener(); } setTimeout(function () { window.location.hash = path; if (silent) { setTimeout(function () { addListener(); }, 1); } }, 1); }; /** * Callback that should be executed before route, * return false to brak route-chaign and handle * errors, for examle ACL. * * @param {string} path * @param {function} fn */ routie.before = function (path, fn) { addHandler(path, fn, ROUTE_CTX_BEFORE); }; /** * Callback that should be executed before all routes, * * @param {function} fn */ routie.beforeAll = function (fn) { for (var i = 0, c = routes.length; i < c; i++) { addHandler(routes[i].path, fn, ROUTE_CTX_BEFORE); } }; /** * Callback that should be executed after route * * @param {string} path * @param {function} fn */ routie.after = function (path, fn) { addHandler(path, fn, ROUTE_CTX_AFTER); }; /** * Callback that should be executed after all routes, * * @param {callback} fn */ routie.afterAll = function (fn) { for (var i = 0, c = routes.length; i < c; i++) { addHandler(routes[i].path, fn, ROUTE_CTX_AFTER); } }; routie.noConflict = function () { w[reference] = oldReference; return routie; }; var getHash = function () { return window.location.hash.substring(1); }; var checkRoute = function (hash, route) { var params = []; if (route.match(hash, params)) { route.run(params); return true; } return false; }; var hashChanged = routie.reload = function () { var hash = getHash(); for (var i = 0, c = routes.length; i < c; i++) { var route = routes[i]; if (checkRoute(hash, route)) { return; } } }; var addListener = function () { if (w.addEventListener) { w.addEventListener('hashchange', hashChanged, false); } else { w.attachEvent('onhashchange', hashChanged); } }; var removeListener = function () { if (w.removeEventListener) { w.removeEventListener('hashchange', hashChanged); } else { w.detachEvent('onhashchange', hashChanged); } }; addListener(); w[reference] = routie; })(window);
'use strict'; /* * MenuItem * */ import React, { PropTypes } from 'react'; const MenuItem = ({ id, title, onSelectionChange }) => ( <div className='menu-item' onClick={ () => onSelectionChange(id) }>{ title }</div> ); MenuItem.propTypes = { id: PropTypes.string, // only id never change for one schema item title: PropTypes.string.isRequired, onSelectionChange: PropTypes.func }; export default MenuItem;
import signToken from './signToken' const user = { id: '2c062e26-df71-48ce-b363-4ae9b966e7a0', email: 'fake@email.com', roles: [ { id: 1, uuid: '3d062e26-df71-48ce-b363-4ae9b966e7a0', name: 'User', }, ], } it('creates a signed jsonwebtoken', () => { const token = signToken(user) expect(typeof token).toBe('string') })
/* CryptoJS v3.1.2 code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ var CryptoJS = CryptoJS || function (u, p) { var d = {}, l = d.lib = {}, s = function () { }, t = l.Base = { extend: function (a) { s.prototype = this; var c = new s; a && c.mixIn(a); c.hasOwnProperty("init") || (c.init = function () { c.$super.init.apply(this, arguments) }); c.init.prototype = c; c.$super = this; return c }, create: function () { var a = this.extend(); a.init.apply(a, arguments); return a }, init: function () { }, mixIn: function (a) { for (var c in a) a.hasOwnProperty(c) && (this[c] = a[c]); a.hasOwnProperty("toString") && (this.toString = a.toString) }, clone: function () { return this.init.prototype.extend(this) } }, r = l.WordArray = t.extend({ init: function (a, c) { a = this.words = a || []; this.sigBytes = c != p ? c : 4 * a.length }, toString: function (a) { return (a || v).stringify(this) }, concat: function (a) { var c = this.words, e = a.words, j = this.sigBytes; a = a.sigBytes; this.clamp(); if (j % 4) for (var k = 0; k < a; k++) c[j + k >>> 2] |= (e[k >>> 2] >>> 24 - 8 * (k % 4) & 255) << 24 - 8 * ((j + k) % 4); else if (65535 < e.length) for (k = 0; k < a; k += 4) c[j + k >>> 2] = e[k >>> 2]; else c.push.apply(c, e); this.sigBytes += a; return this }, clamp: function () { var a = this.words, c = this.sigBytes; a[c >>> 2] &= 4294967295 << 32 - 8 * (c % 4); a.length = u.ceil(c / 4) }, clone: function () { var a = t.clone.call(this); a.words = this.words.slice(0); return a }, random: function (a) { for (var c = [], e = 0; e < a; e += 4) c.push(4294967296 * u.random() | 0); return new r.init(c, a) } }), w = d.enc = {}, v = w.Hex = { stringify: function (a) { var c = a.words; a = a.sigBytes; for (var e = [], j = 0; j < a; j++) { var k = c[j >>> 2] >>> 24 - 8 * (j % 4) & 255; e.push((k >>> 4).toString(16)); e.push((k & 15).toString(16)) } return e.join("") }, parse: function (a) { for (var c = a.length, e = [], j = 0; j < c; j += 2) e[j >>> 3] |= parseInt(a.substr(j, 2), 16) << 24 - 4 * (j % 8); return new r.init(e, c / 2) } }, b = w.Latin1 = { stringify: function (a) { var c = a.words; a = a.sigBytes; for (var e = [], j = 0; j < a; j++) e.push(String.fromCharCode(c[j >>> 2] >>> 24 - 8 * (j % 4) & 255)); return e.join("") }, parse: function (a) { for (var c = a.length, e = [], j = 0; j < c; j++) e[j >>> 2] |= (a.charCodeAt(j) & 255) << 24 - 8 * (j % 4); return new r.init(e, c) } }, x = w.Utf8 = { stringify: function (a) { try { return decodeURIComponent(escape(b.stringify(a))) } catch (c) { throw Error("Malformed UTF-8 data"); } }, parse: function (a) { return b.parse(unescape(encodeURIComponent(a))) } }, q = l.BufferedBlockAlgorithm = t.extend({ reset: function () { this._data = new r.init; this._nDataBytes = 0 }, _append: function (a) { "string" == typeof a && (a = x.parse(a)); this._data.concat(a); this._nDataBytes += a.sigBytes }, _process: function (a) { var c = this._data, e = c.words, j = c.sigBytes, k = this.blockSize, b = j / (4 * k), b = a ? u.ceil(b) : u.max((b | 0) - this._minBufferSize, 0); a = b * k; j = u.min(4 * a, j); if (a) { for (var q = 0; q < a; q += k) this._doProcessBlock(e, q); q = e.splice(0, a); c.sigBytes -= j } return new r.init(q, j) }, clone: function () { var a = t.clone.call(this); a._data = this._data.clone(); return a }, _minBufferSize: 0 }); l.Hasher = q.extend({ cfg: t.extend(), init: function (a) { this.cfg = this.cfg.extend(a); this.reset() }, reset: function () { q.reset.call(this); this._doReset() }, update: function (a) { this._append(a); this._process(); return this }, finalize: function (a) { a && this._append(a); return this._doFinalize() }, blockSize: 16, _createHelper: function (a) { return function (b, e) { return (new a.init(e)).finalize(b) } }, _createHmacHelper: function (a) { return function (b, e) { return (new n.HMAC.init(a, e)).finalize(b) } } }); var n = d.algo = {}; return d }(Math); (function () { var u = CryptoJS, p = u.lib.WordArray; u.enc.Base64 = { stringify: function (d) { var l = d.words, p = d.sigBytes, t = this._map; d.clamp(); d = []; for (var r = 0; r < p; r += 3) for (var w = (l[r >>> 2] >>> 24 - 8 * (r % 4) & 255) << 16 | (l[r + 1 >>> 2] >>> 24 - 8 * ((r + 1) % 4) & 255) << 8 | l[r + 2 >>> 2] >>> 24 - 8 * ((r + 2) % 4) & 255, v = 0; 4 > v && r + 0.75 * v < p; v++) d.push(t.charAt(w >>> 6 * (3 - v) & 63)); if (l = t.charAt(64)) for (; d.length % 4;) d.push(l); return d.join("") }, parse: function (d) { var l = d.length, s = this._map, t = s.charAt(64); t && (t = d.indexOf(t), -1 != t && (l = t)); for (var t = [], r = 0, w = 0; w < l; w++) if (w % 4) { var v = s.indexOf(d.charAt(w - 1)) << 2 * (w % 4), b = s.indexOf(d.charAt(w)) >>> 6 - 2 * (w % 4); t[r >>> 2] |= (v | b) << 24 - 8 * (r % 4); r++ } return p.create(t, r) }, _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" } })(); (function (u) { function p(b, n, a, c, e, j, k) { b = b + (n & a | ~n & c) + e + k; return (b << j | b >>> 32 - j) + n } function d(b, n, a, c, e, j, k) { b = b + (n & c | a & ~c) + e + k; return (b << j | b >>> 32 - j) + n } function l(b, n, a, c, e, j, k) { b = b + (n ^ a ^ c) + e + k; return (b << j | b >>> 32 - j) + n } function s(b, n, a, c, e, j, k) { b = b + (a ^ (n | ~c)) + e + k; return (b << j | b >>> 32 - j) + n } for (var t = CryptoJS, r = t.lib, w = r.WordArray, v = r.Hasher, r = t.algo, b = [], x = 0; 64 > x; x++) b[x] = 4294967296 * u.abs(u.sin(x + 1)) | 0; r = r.MD5 = v.extend({ _doReset: function () { this._hash = new w.init([1732584193, 4023233417, 2562383102, 271733878]) }, _doProcessBlock: function (q, n) { for (var a = 0; 16 > a; a++) { var c = n + a, e = q[c]; q[c] = (e << 8 | e >>> 24) & 16711935 | (e << 24 | e >>> 8) & 4278255360 } var a = this._hash.words, c = q[n + 0], e = q[n + 1], j = q[n + 2], k = q[n + 3], z = q[n + 4], r = q[n + 5], t = q[n + 6], w = q[n + 7], v = q[n + 8], A = q[n + 9], B = q[n + 10], C = q[n + 11], u = q[n + 12], D = q[n + 13], E = q[n + 14], x = q[n + 15], f = a[0], m = a[1], g = a[2], h = a[3], f = p(f, m, g, h, c, 7, b[0]), h = p(h, f, m, g, e, 12, b[1]), g = p(g, h, f, m, j, 17, b[2]), m = p(m, g, h, f, k, 22, b[3]), f = p(f, m, g, h, z, 7, b[4]), h = p(h, f, m, g, r, 12, b[5]), g = p(g, h, f, m, t, 17, b[6]), m = p(m, g, h, f, w, 22, b[7]), f = p(f, m, g, h, v, 7, b[8]), h = p(h, f, m, g, A, 12, b[9]), g = p(g, h, f, m, B, 17, b[10]), m = p(m, g, h, f, C, 22, b[11]), f = p(f, m, g, h, u, 7, b[12]), h = p(h, f, m, g, D, 12, b[13]), g = p(g, h, f, m, E, 17, b[14]), m = p(m, g, h, f, x, 22, b[15]), f = d(f, m, g, h, e, 5, b[16]), h = d(h, f, m, g, t, 9, b[17]), g = d(g, h, f, m, C, 14, b[18]), m = d(m, g, h, f, c, 20, b[19]), f = d(f, m, g, h, r, 5, b[20]), h = d(h, f, m, g, B, 9, b[21]), g = d(g, h, f, m, x, 14, b[22]), m = d(m, g, h, f, z, 20, b[23]), f = d(f, m, g, h, A, 5, b[24]), h = d(h, f, m, g, E, 9, b[25]), g = d(g, h, f, m, k, 14, b[26]), m = d(m, g, h, f, v, 20, b[27]), f = d(f, m, g, h, D, 5, b[28]), h = d(h, f, m, g, j, 9, b[29]), g = d(g, h, f, m, w, 14, b[30]), m = d(m, g, h, f, u, 20, b[31]), f = l(f, m, g, h, r, 4, b[32]), h = l(h, f, m, g, v, 11, b[33]), g = l(g, h, f, m, C, 16, b[34]), m = l(m, g, h, f, E, 23, b[35]), f = l(f, m, g, h, e, 4, b[36]), h = l(h, f, m, g, z, 11, b[37]), g = l(g, h, f, m, w, 16, b[38]), m = l(m, g, h, f, B, 23, b[39]), f = l(f, m, g, h, D, 4, b[40]), h = l(h, f, m, g, c, 11, b[41]), g = l(g, h, f, m, k, 16, b[42]), m = l(m, g, h, f, t, 23, b[43]), f = l(f, m, g, h, A, 4, b[44]), h = l(h, f, m, g, u, 11, b[45]), g = l(g, h, f, m, x, 16, b[46]), m = l(m, g, h, f, j, 23, b[47]), f = s(f, m, g, h, c, 6, b[48]), h = s(h, f, m, g, w, 10, b[49]), g = s(g, h, f, m, E, 15, b[50]), m = s(m, g, h, f, r, 21, b[51]), f = s(f, m, g, h, u, 6, b[52]), h = s(h, f, m, g, k, 10, b[53]), g = s(g, h, f, m, B, 15, b[54]), m = s(m, g, h, f, e, 21, b[55]), f = s(f, m, g, h, v, 6, b[56]), h = s(h, f, m, g, x, 10, b[57]), g = s(g, h, f, m, t, 15, b[58]), m = s(m, g, h, f, D, 21, b[59]), f = s(f, m, g, h, z, 6, b[60]), h = s(h, f, m, g, C, 10, b[61]), g = s(g, h, f, m, j, 15, b[62]), m = s(m, g, h, f, A, 21, b[63]); a[0] = a[0] + f | 0; a[1] = a[1] + m | 0; a[2] = a[2] + g | 0; a[3] = a[3] + h | 0 }, _doFinalize: function () { var b = this._data, n = b.words, a = 8 * this._nDataBytes, c = 8 * b.sigBytes; n[c >>> 5] |= 128 << 24 - c % 32; var e = u.floor(a / 4294967296); n[(c + 64 >>> 9 << 4) + 15] = (e << 8 | e >>> 24) & 16711935 | (e << 24 | e >>> 8) & 4278255360; n[(c + 64 >>> 9 << 4) + 14] = (a << 8 | a >>> 24) & 16711935 | (a << 24 | a >>> 8) & 4278255360; b.sigBytes = 4 * (n.length + 1); this._process(); b = this._hash; n = b.words; for (a = 0; 4 > a; a++) c = n[a], n[a] = (c << 8 | c >>> 24) & 16711935 | (c << 24 | c >>> 8) & 4278255360; return b }, clone: function () { var b = v.clone.call(this); b._hash = this._hash.clone(); return b } }); t.MD5 = v._createHelper(r); t.HmacMD5 = v._createHmacHelper(r) })(Math); (function () { var u = CryptoJS, p = u.lib, d = p.Base, l = p.WordArray, p = u.algo, s = p.EvpKDF = d.extend({ cfg: d.extend({keySize: 4, hasher: p.MD5, iterations: 1}), init: function (d) { this.cfg = this.cfg.extend(d) }, compute: function (d, r) { for (var p = this.cfg, s = p.hasher.create(), b = l.create(), u = b.words, q = p.keySize, p = p.iterations; u.length < q;) { n && s.update(n); var n = s.update(d).finalize(r); s.reset(); for (var a = 1; a < p; a++) n = s.finalize(n), s.reset(); b.concat(n) } b.sigBytes = 4 * q; return b } }); u.EvpKDF = function (d, l, p) { return s.create(p).compute(d, l) } })(); CryptoJS.lib.Cipher || function (u) { var p = CryptoJS, d = p.lib, l = d.Base, s = d.WordArray, t = d.BufferedBlockAlgorithm, r = p.enc.Base64, w = p.algo.EvpKDF, v = d.Cipher = t.extend({ cfg: l.extend(), createEncryptor: function (e, a) { return this.create(this._ENC_XFORM_MODE, e, a) }, createDecryptor: function (e, a) { return this.create(this._DEC_XFORM_MODE, e, a) }, init: function (e, a, b) { this.cfg = this.cfg.extend(b); this._xformMode = e; this._key = a; this.reset() }, reset: function () { t.reset.call(this); this._doReset() }, process: function (e) { this._append(e); return this._process() }, finalize: function (e) { e && this._append(e); return this._doFinalize() }, keySize: 4, ivSize: 4, _ENC_XFORM_MODE: 1, _DEC_XFORM_MODE: 2, _createHelper: function (e) { return { encrypt: function (b, k, d) { return ("string" == typeof k ? c : a).encrypt(e, b, k, d) }, decrypt: function (b, k, d) { return ("string" == typeof k ? c : a).decrypt(e, b, k, d) } } } }); d.StreamCipher = v.extend({ _doFinalize: function () { return this._process(!0) }, blockSize: 1 }); var b = p.mode = {}, x = function (e, a, b) { var c = this._iv; c ? this._iv = u : c = this._prevBlock; for (var d = 0; d < b; d++) e[a + d] ^= c[d] }, q = (d.BlockCipherMode = l.extend({ createEncryptor: function (e, a) { return this.Encryptor.create(e, a) }, createDecryptor: function (e, a) { return this.Decryptor.create(e, a) }, init: function (e, a) { this._cipher = e; this._iv = a } })).extend(); q.Encryptor = q.extend({ processBlock: function (e, a) { var b = this._cipher, c = b.blockSize; x.call(this, e, a, c); b.encryptBlock(e, a); this._prevBlock = e.slice(a, a + c) } }); q.Decryptor = q.extend({ processBlock: function (e, a) { var b = this._cipher, c = b.blockSize, d = e.slice(a, a + c); b.decryptBlock(e, a); x.call(this, e, a, c); this._prevBlock = d } }); b = b.CBC = q; q = (p.pad = {}).Pkcs7 = { pad: function (a, b) { for (var c = 4 * b, c = c - a.sigBytes % c, d = c << 24 | c << 16 | c << 8 | c, l = [], n = 0; n < c; n += 4) l.push(d); c = s.create(l, c); a.concat(c) }, unpad: function (a) { a.sigBytes -= a.words[a.sigBytes - 1 >>> 2] & 255 } }; d.BlockCipher = v.extend({ cfg: v.cfg.extend({mode: b, padding: q}), reset: function () { v.reset.call(this); var a = this.cfg, b = a.iv, a = a.mode; if (this._xformMode == this._ENC_XFORM_MODE) var c = a.createEncryptor; else c = a.createDecryptor, this._minBufferSize = 1; this._mode = c.call(a, this, b && b.words) }, _doProcessBlock: function (a, b) { this._mode.processBlock(a, b) }, _doFinalize: function () { var a = this.cfg.padding; if (this._xformMode == this._ENC_XFORM_MODE) { a.pad(this._data, this.blockSize); var b = this._process(!0) } else b = this._process(!0), a.unpad(b); return b }, blockSize: 4 }); var n = d.CipherParams = l.extend({ init: function (a) { this.mixIn(a) }, toString: function (a) { return (a || this.formatter).stringify(this) } }), b = (p.format = {}).OpenSSL = { stringify: function (a) { var b = a.ciphertext; a = a.salt; return (a ? s.create([1398893684, 1701076831]).concat(a).concat(b) : b).toString(r) }, parse: function (a) { a = r.parse(a); var b = a.words; if (1398893684 == b[0] && 1701076831 == b[1]) { var c = s.create(b.slice(2, 4)); b.splice(0, 4); a.sigBytes -= 16 } return n.create({ciphertext: a, salt: c}) } }, a = d.SerializableCipher = l.extend({ cfg: l.extend({format: b}), encrypt: function (a, b, c, d) { d = this.cfg.extend(d); var l = a.createEncryptor(c, d); b = l.finalize(b); l = l.cfg; return n.create({ ciphertext: b, key: c, iv: l.iv, algorithm: a, mode: l.mode, padding: l.padding, blockSize: a.blockSize, formatter: d.format }) }, decrypt: function (a, b, c, d) { d = this.cfg.extend(d); b = this._parse(b, d.format); return a.createDecryptor(c, d).finalize(b.ciphertext) }, _parse: function (a, b) { return "string" == typeof a ? b.parse(a, this) : a } }), p = (p.kdf = {}).OpenSSL = { execute: function (a, b, c, d) { d || (d = s.random(8)); a = w.create({keySize: b + c}).compute(a, d); c = s.create(a.words.slice(b), 4 * c); a.sigBytes = 4 * b; return n.create({key: a, iv: c, salt: d}) } }, c = d.PasswordBasedCipher = a.extend({ cfg: a.cfg.extend({kdf: p}), encrypt: function (b, c, d, l) { l = this.cfg.extend(l); d = l.kdf.execute(d, b.keySize, b.ivSize); l.iv = d.iv; b = a.encrypt.call(this, b, c, d.key, l); b.mixIn(d); return b }, decrypt: function (b, c, d, l) { l = this.cfg.extend(l); c = this._parse(c, l.format); d = l.kdf.execute(d, b.keySize, b.ivSize, c.salt); l.iv = d.iv; return a.decrypt.call(this, b, c, d.key, l) } }) }(); (function () { for (var u = CryptoJS, p = u.lib.BlockCipher, d = u.algo, l = [], s = [], t = [], r = [], w = [], v = [], b = [], x = [], q = [], n = [], a = [], c = 0; 256 > c; c++) a[c] = 128 > c ? c << 1 : c << 1 ^ 283; for (var e = 0, j = 0, c = 0; 256 > c; c++) { var k = j ^ j << 1 ^ j << 2 ^ j << 3 ^ j << 4, k = k >>> 8 ^ k & 255 ^ 99; l[e] = k; s[k] = e; var z = a[e], F = a[z], G = a[F], y = 257 * a[k] ^ 16843008 * k; t[e] = y << 24 | y >>> 8; r[e] = y << 16 | y >>> 16; w[e] = y << 8 | y >>> 24; v[e] = y; y = 16843009 * G ^ 65537 * F ^ 257 * z ^ 16843008 * e; b[k] = y << 24 | y >>> 8; x[k] = y << 16 | y >>> 16; q[k] = y << 8 | y >>> 24; n[k] = y; e ? (e = z ^ a[a[a[G ^ z]]], j ^= a[a[j]]) : e = j = 1 } var H = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54], d = d.AES = p.extend({ _doReset: function () { for (var a = this._key, c = a.words, d = a.sigBytes / 4, a = 4 * ((this._nRounds = d + 6) + 1), e = this._keySchedule = [], j = 0; j < a; j++) if (j < d) e[j] = c[j]; else { var k = e[j - 1]; j % d ? 6 < d && 4 == j % d && (k = l[k >>> 24] << 24 | l[k >>> 16 & 255] << 16 | l[k >>> 8 & 255] << 8 | l[k & 255]) : (k = k << 8 | k >>> 24, k = l[k >>> 24] << 24 | l[k >>> 16 & 255] << 16 | l[k >>> 8 & 255] << 8 | l[k & 255], k ^= H[j / d | 0] << 24); e[j] = e[j - d] ^ k } c = this._invKeySchedule = []; for (d = 0; d < a; d++) j = a - d, k = d % 4 ? e[j] : e[j - 4], c[d] = 4 > d || 4 >= j ? k : b[l[k >>> 24]] ^ x[l[k >>> 16 & 255]] ^ q[l[k >>> 8 & 255]] ^ n[l[k & 255]] }, encryptBlock: function (a, b) { this._doCryptBlock(a, b, this._keySchedule, t, r, w, v, l) }, decryptBlock: function (a, c) { var d = a[c + 1]; a[c + 1] = a[c + 3]; a[c + 3] = d; this._doCryptBlock(a, c, this._invKeySchedule, b, x, q, n, s); d = a[c + 1]; a[c + 1] = a[c + 3]; a[c + 3] = d }, _doCryptBlock: function (a, b, c, d, e, j, l, f) { for (var m = this._nRounds, g = a[b] ^ c[0], h = a[b + 1] ^ c[1], k = a[b + 2] ^ c[2], n = a[b + 3] ^ c[3], p = 4, r = 1; r < m; r++) var q = d[g >>> 24] ^ e[h >>> 16 & 255] ^ j[k >>> 8 & 255] ^ l[n & 255] ^ c[p++], s = d[h >>> 24] ^ e[k >>> 16 & 255] ^ j[n >>> 8 & 255] ^ l[g & 255] ^ c[p++], t = d[k >>> 24] ^ e[n >>> 16 & 255] ^ j[g >>> 8 & 255] ^ l[h & 255] ^ c[p++], n = d[n >>> 24] ^ e[g >>> 16 & 255] ^ j[h >>> 8 & 255] ^ l[k & 255] ^ c[p++], g = q, h = s, k = t; q = (f[g >>> 24] << 24 | f[h >>> 16 & 255] << 16 | f[k >>> 8 & 255] << 8 | f[n & 255]) ^ c[p++]; s = (f[h >>> 24] << 24 | f[k >>> 16 & 255] << 16 | f[n >>> 8 & 255] << 8 | f[g & 255]) ^ c[p++]; t = (f[k >>> 24] << 24 | f[n >>> 16 & 255] << 16 | f[g >>> 8 & 255] << 8 | f[h & 255]) ^ c[p++]; n = (f[n >>> 24] << 24 | f[g >>> 16 & 255] << 16 | f[h >>> 8 & 255] << 8 | f[k & 255]) ^ c[p++]; a[b] = q; a[b + 1] = s; a[b + 2] = t; a[b + 3] = n }, keySize: 8 }); u.AES = p._createHelper(d) })(); function encrypt(string, masterkey, options){ if( options ){ if( options.mode ){ options.mode = CryptoJS.mode[options.mode]; } if( options.padding ){ options.padding = CryptoJS.pad[options.padding]; } var encrypted = CryptoJS.AES.encrypt(string, masterkey, options); }else{ var encrypted = CryptoJS.AES.encrypt(string, masterkey); } var result = encrypted.ciphertext.toString(CryptoJS.enc.Base64); return [encrypted, result]; } function decrypt(string, masterkey, options){ if( options ){ if( options.mode ){ options.mode = CryptoJS.mode[options.mode]; } if( options.padding ){ options.padding = CryptoJS.pad[options.padding]; } var decrypted = CryptoJS.AES.decrypt(string, masterkey, options).toString(CryptoJS.enc.Utf8); }else{ var decrypted = CryptoJS.AES.decrypt(string, masterkey).toString(CryptoJS.enc.Utf8); } return decrypted; }
var appRoot = require('app-root-path'); var mongoose = require('mongoose'); var moment = require ('moment'); var Courses = require(appRoot + '/modules/catalogs/courses.js'); var async = require('asyncawait/async'); var await = require('asyncawait/await'); function CourseListAuthor(){ } CourseListAuthor.prototype.init = function(params){ this._id = mongoose.Types.ObjectId(params.cid); }; CourseListAuthor.prototype.run = async ( function(){ var self = this; var result = await( Courses.findOne({ _id: self._id }).populate('createdBy displayName').exec()); self.result = result; } ); CourseListAuthor.prototype.render = function(){ var momentDate = moment(this.result.dateAdded).format('MMMM Do YYYY'); return '<span class="label label-info bg-green"> Author: ' + this.result.createdBy.displayName + ' - ' + momentDate + '</span> <br>'; }; module.exports = CourseListAuthor;
if (Meteor.isClient) { Meteor.startup(function() { Session.set("showLoadingIndicator", true); TAPi18n.setLanguage(getUserLanguage()) .done(function() { Session.set("showLoadingIndicator", false); }) .fail(function(error_message) { // Handle the situation console.log(error_message); }); }); }
/** * The store could be just a global object. I read and write as I please. * It could also have some useful methods. Get children, updateItem, etc. * Also it could emit a change event. But how to handle that change? * Is it fast to listen to that on hundreds of row components? * * What do I ever need to do? * 1. advance to the next visible row * - getNextVisible() * - change the currently selected * - in DOM: unhighlight the currently highlighted item * and highlight the now-highlighted item. * - sometimes I'll want to expand an item and mark all children * as being visible now, or vice versa. * * What about a very tight coupling between the data and the UI. * When a component is created, it's appending itself as an item in the store * Then, when I update the store, I iterate over it, and if I have to update some data * like 'selected' or 'expanded' or 'score' * then I already have a reference to the item that needs to update, so * I can say item.score = 1; item.update() * */ import localforage from 'localforage'; import { ANALYTICS_STRINGS, EVENTS, SCORES, } from '../utils/constants'; import logTiming from '../utils/logTiming'; localforage.ready().catch(() => { console.warn(`localforage threw an error. If this is during webpack build, everything is OK`); }); const diskStore = localforage.createInstance({ name: `know-it-all`, version: 1, }); // this is used to define if an item should be re-rendered // it should contain anything that can be changed by a user const serializeItemState = item => [ item.scoreKey, !!item.visible, !!item.expanded, !!item.selected, ].join(``); /* eslint-disable no-param-reassign */ const store = { data: [], listeners: {}, selectedItem: null, childrenCache: {}, itemCache: {}, isModalVisible: false, scoresLoadedFromDisk: false, scoreSummary: {}, init(data) { this.addData(data); if (window.APP_META.BROWSER) { this.getScoresFromDisk().then(() => { logTiming(ANALYTICS_STRINGS.FIRST_MODULE_SCORES); }); } }, addData(newData) { this.data = this.data.concat(newData); newData.forEach((item) => { this.itemCache[item.id] = item; }); newData.forEach((item) => { this.updateScoreSummary(item); }); }, addModules(newModules) { newModules.forEach((module, i) => { // it can take a few seconds to load all the scores on slow devices // break it up into smaller chunks by calling requestIdleCallback() requestIdleCallback(() => { this.addData(module); this.triggerListener(EVENTS.MODULE_ADDED, module[0]); if (i === newModules.length - 1) { this.getScoresFromDisk().then(() => { logTiming(ANALYTICS_STRINGS.ALL_MODULE_SCORES); }); } }); }); }, getItem(idOrItem) { if (typeof idOrItem === `string`) { return this.itemCache[idOrItem]; } return idOrItem; }, getParent(item) { // this caches a reference to an item's parent for performance if (item.parentItem) return item.parentItem; if (!item.parentId) return null; item.parentItem = this.getItem(item.parentId); return item.parentItem; }, getChildrenOf(id) { // TODO (davidg): actually store references to the children on the item if (id in this.childrenCache) { return this.childrenCache[id]; } const children = this.data.filter(item => item.parentId === id); this.childrenCache[id] = children; if (children && children.length) return children; return false; }, getScoreCounts() { const scoreCounts = Object.keys(SCORES).reduce((result, scoreKey) => { result[scoreKey] = { score: SCORES[scoreKey], count: 0, }; return result; }, {}); this.data.forEach((item) => { const scoreKey = item.scoreKey || SCORES.LEVEL_0.key; // "unrated" if (!scoreCounts[scoreKey]) { console.warn(`${scoreKey} is not a valid score`); } else { scoreCounts[scoreKey].count += 1; } }); // turn the object into an array return Object.keys(scoreCounts).map(scoreKey => scoreCounts[scoreKey]); }, getUnknowns() { const unknowns = []; const getItemPath = (item) => { if (item.parentId) { const parent = this.getItem(item.parentId); return `${getItemPath(parent)} » ${item.name}`; } return item.name; }; this.data.forEach((item) => { if (item.scoreKey === SCORES.LEVEL_1.key) { const path = getItemPath(item); const topLevel = path.substr(0, path.indexOf(` » `, -2)); const searchTerm = `${topLevel} ${item.name}`; const url = `https://www.google.com.au/search?q=${encodeURIComponent(searchTerm)}`; unknowns.push({ path, url, }); } }); return unknowns; }, updateItem(idOrItem, data, options = {}) { const saveToDisk = (typeof options.saveToDisk !== `undefined`) ? options.saveToDisk : true; const updateDom = (typeof options.updateDom !== `undefined`) ? options.updateDom : true; const item = this.getItem(idOrItem); if (!item) return; if (window.APP_DEBUG === true) { console.info(`Updated`, item, `with data`, data); } const prevItemState = serializeItemState(item); const scoreChanged = data.scoreKey && data.scoreKey !== item.scoreKey; Object.assign(item, data); // gasp, mutability if (!updateDom) return; const nextItemState = serializeItemState(item); // potentially trigger a re-render of the item if (item.visible && prevItemState !== nextItemState) { this.triggerListener(item.id); // TODO (davidg): `ROW-${item.id}` } // potentially trigger a re-render of the score bar if (scoreChanged) { if (saveToDisk) diskStore.setItem(item.id, data); if (this.selectedItem && this.selectedItem.id === idOrItem.id) { this.triggerListener(EVENTS.SCORE_CHANGED); // updates the score bar } } }, updateScore(id, scoreKey, options = {}) { const item = this.getItem(id); if (!item) return; const updateDom = (typeof options.updateDom !== `undefined`) ? options.updateDom : true; // caution: update the score summary before updating the item const updatedItems = this.updateScoreSummary(item, scoreKey, item.scoreKey); this.updateItem(item, { scoreKey }, options); if (updateDom) { updatedItems.forEach((updatedItem) => { this.triggerListener(`PIE-${updatedItem.id}`); }); } }, updateScoreSummary(item, newScoreKey, oldScoreKey) { // TODO (davidg): this is pretty CPU intensive - web worker? const newItem = !newScoreKey && !oldScoreKey; // the score summary holds the aggregate scores for non-leaf nodes newScoreKey = newScoreKey || SCORES.LEVEL_0.key; oldScoreKey = oldScoreKey || SCORES.LEVEL_0.key; const updatedItems = []; const updateParentScore = (child) => { const parent = this.getParent(child); if (!parent) return; // we're at the top updatedItems.push(parent); this.scoreSummary[parent.id] = this.scoreSummary[parent.id] || {}; this.scoreSummary[parent.id][newScoreKey] = this.scoreSummary[parent.id][newScoreKey] || 0; this.scoreSummary[parent.id][newScoreKey] += 1; if (!newItem) { this.scoreSummary[parent.id][oldScoreKey] -= 1; } updateParentScore(parent); }; // we don't update the item directly, only its ancestors updateParentScore(item); return updatedItems; }, getScoreSummary(id) { const scoreSummary = this.scoreSummary[id]; if (!scoreSummary) return false; const scoreOrder = [4, 1, 2, 3, 0]; const results = []; let total = 0; scoreOrder.forEach((scoreInt) => { const score = SCORES[`LEVEL_${scoreInt}`]; const scoreCount = scoreSummary[score.key]; if (scoreCount) { total += scoreCount; results.push({ count: scoreCount, score, }); } }); return { total, results }; }, getScoresFromDisk() { return diskStore.iterate((data, id) => { // the only thing we want from the store is the score key // future version maybe 'expanded' or 'selected' if (data.scoreKey) { this.updateScore( id, data.scoreKey, { saveToDisk: false, updateDom: false }, ); } }).then(() => { this.scoresLoadedFromDisk = true; this.data.forEach((item) => { // since potentially every row/pie chart may have changed // just re-render each of the top level items if (!item.parentId) this.triggerListener(item.id); }); }); }, selectNextVisibleRow() { if (this.selectedItem) { if (this.selectedItem.row >= this.data.length - 1) return; const nextSelectedItem = this.data .slice(this.selectedItem.row + 1) .find(item => item.visible); if (!nextSelectedItem) return; this.changeSelectedItem(nextSelectedItem); } else { this.changeSelectedItem(this.data[0]); } }, selectPrevVisibleRow() { if (this.selectedItem) { if (this.selectedItem.row < 1) return; const nextSelectedItem = this.data .slice(0, this.selectedItem.row) .reverse() .find(item => item.visible); this.changeSelectedItem(nextSelectedItem); } else { this.changeSelectedItem(this.data[0]); } }, selectItemById(id) { if (this.selectedItem && this.selectedItem.id === id) return; this.changeSelectedItem(id); }, selectNoItem() { this.changeSelectedItem(null); }, changeSelectedItem(idOrItem) { const selectedItem = this.getItem(idOrItem); if (this.selectedItem) { this.updateItem(this.selectedItem.id, { selected: false }); } if (selectedItem) { // might be null this.updateItem(selectedItem.id, { selected: true }); } this.selectedItem = selectedItem; this.triggerListener(EVENTS.SELECTED_ITEM_CHANGED); }, expandOrNavigateToChild() { if (this.selectedItem && !this.selectedItem.expanded && !this.selectedItem.leaf) { this.expandItemById(this.selectedItem.id); } else if (this.selectedItem && !this.selectedItem.leaf) { this.selectNextVisibleRow(); } }, collapseOrNavigateToParent() { if (this.selectedItem && this.selectedItem.expanded) { this.collapseItemById(this.selectedItem.id); } else if (this.selectedItem && this.selectedItem.parentId) { this.changeSelectedItem(this.selectedItem.parentId); } }, expandItemById(id) { const children = this.getChildrenOf(id); if (!children) return; const item = this.getItem(id); if (item.expanded) return; item.expanded = true; if (children) { children.forEach((child) => { child.visible = true; }); } this.triggerListener(id, item); }, collapseItemById(id) { const item = this.getItem(id); if (item.expanded === false) return; item.expanded = false; const children = this.getChildrenOf(id); if (children) { children.forEach((child) => { child.visible = false; }); } this.triggerListener(id, item); }, scoreSelectedItem(scoreKey) { if (this.selectedItem && this.selectedItem.scoreKey !== scoreKey) { this.updateScore(this.selectedItem.id, scoreKey); } }, showModal() { this.isModalVisible = true; this.triggerListener(EVENTS.MODAL_VISIBILITY_CHANGED); }, closeModal() { this.isModalVisible = false; this.triggerListener(EVENTS.MODAL_VISIBILITY_CHANGED); }, triggerListener(id, payload) { const callbacks = this.listeners[id]; if (callbacks && callbacks.length) { callbacks.forEach(callback => callback(payload)); } }, listen(id, callback) { if (!callback || typeof callback !== `function`) { console.warn(`You must pass a function as the second argument to store.listen()`); } this.listeners[id] = this.listeners[id] || []; this.listeners[id].push(callback); }, }; export default store; /* eslint-enable no-param-reassign */
const {SHA256} = require('crypto-js') const jwt = require('jsonwebtoken') // let {User} = require('./../node-samples/mongo-api/models/user'); // const {User} = require('./../node-samples/mongo-api/models/user') let getToken = (data,salt) => { let promise = new Promise( (resolve, reject) => { jwt.sign(data,salt, (err,token) => { if(err) reject(err) resolve(token) }) }); return promise } let getTokenStr = (data,salt) => { return jwt.sign(data,salt).toString() } module.exports = { getToken, getTokenStr }
const Slack = require('../services/slack') // http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/ElasticBeanstalk.html const elasticbeanstalk = require('aws-sdk/clients/elasticbeanstalk') const eb = new elasticbeanstalk({ accessKeyId: process.env.AWS_ACCESS_KEY, secretAccessKey: process.env.AWS_SECRET_KEY, region: process.env.AWS_REGION, apiVersion: '2010-12-01' }) const param = { EnvironmentName: process.env.AWS_EB_ENV_NAME, MaxRecords: 1 } const UNKNOWN = 'unknown'; const DEPLOYING = 'deploying'; const DEPLOYED = 'deployed'; const MESSAGE_DEPLOYED = 'New application version was deployed to running EC2 instances.' const MESSAGE_BACK_TO_OK = 'Environment health has transitioned from Warning to Ok.' const MESSAGE_UPDATE_START = 'Environment update is starting.' const MESSAGE_DEPLOYING_START = 'Deploying new version to instance(s).' let status = UNKNOWN; const informEBDeployed = () => { return new Promise(resolve => { eb.describeEvents(param, (err, data) => { const message = data.Events[0].Message; if ([MESSAGE_DEPLOYED, MESSAGE_BACK_TO_OK].some(m => message.startsWith(m))) { if (status === DEPLOYING) { status = DEPLOYED; Slack.sendMessage('G562RLQUD', 'Deployed new version to staging server, please check it.') } } if ([MESSAGE_DEPLOYING_START, MESSAGE_UPDATE_START].some(m => message.startsWith(m))) { if (status !== DEPLOYING) { status = DEPLOYING; Slack.sendMessage('G562RLQUD', 'Deploying new version to staging server, may have downtime caused request failed.') } } }) }) } module.exports = informEBDeployed
/** * * View * **/ Ext.define('App.form.order.step2',{ extend : 'Ext.panel.Panel', extend : 'Ext.grid.Panel', alias: 'widget.frmOrderStep2', requires: [ 'Ext.ux.DataTip', ], columns: [ { xtype: 'rownumberer'}, // { text: 'Id', dataIndex: 'id' }, { text: 'Name', dataIndex: 'name',flex: 1 }, { xtype:'actioncolumn', text: 'Add', width:50, items: [{ icon: '/assets/fugue/icons/document--arrow.png', tooltip: 'Add ', handler: function(grid, rowIndex, colIndex) { var rec = grid.getStore().getAt(rowIndex); alert("Edit " + rec.get('name')); } }, // { // icon: 'extjs/examples/restful/images/delete.png', // tooltip: 'Delete', // handler: function(grid, rowIndex, colIndex) { // var rec = grid.getStore().getAt(rowIndex); // alert("Terminate " + rec.get('name')); // } // } ] } ], padding : 10, store : 'product.MasterProducts', initComponent: function(){ this.callParent(arguments); }, });
var masiro = new Array(); masiro = "<?= $result ?>"; masiro = shuffle(masiro); for (var i = 0; i <= masiro.length - 1; i++) { document.write("<a class='example-image-link' href='img/masiro/" + masiro[i] + "' data-lightbox='example-set' data-title='Click'><img class='example-image' src='img/masiro/" + masiro[i] + "' alt=''/></a>"); } function shuffle(array) { var m = array.length, t, i; while (m) { i = Math.floor(Math.random() * m--); t = array[m]; array[m] = array[i]; array[i] = t; } return array; }
const mongoose = require('mongoose') const select = require('mongoose-json-select') const shortid = require('shortid') const TokenSchema = new mongoose.Schema({ tokenId: { type: String, default: shortid.generate }, owner: { type: String, required: true }, name: { type: String, default: 'Token' }, description: String, default: Boolean, scopes: [String], token: String }, { timestamps: true }) TokenSchema.plugin(select, '-_id -__v') TokenSchema.index({ owner: 1 }) TokenSchema.index({ owner: 1, tokenId: 1 }, { unique: true }) module.exports = mongoose.model('Token', TokenSchema)
'use strict'; const utils = require('../utils/utils'); const processor = require('./processor'); const constant = require('./constant'); const tagNameRE = /(end)?(\w+)/; const spaceReg = /(>|)(?:\t| )*(?:\r?\n)+(?:\t| )*(<|)/; let mus; class Ast { constructor(html, options = {}, fileUrl) { this.root = []; this.parent = null; this.macro = new Map(); this.extends = null; this.scanIndex = 0; this.endIndex = 0; this.template = html; this.fileUrl = fileUrl; this.blockStart = options.blockStart || '{%'; this.blockEnd = options.blockEnd || '%}'; this.variableStart = options.variableStart || '{{'; this.variableEnd = options.variableEnd || '}}'; this.compress = options.compress; this.processor = processor; this.commentStart = '{#'; this.commentEnd = '#}'; // support extending processor if (options.processor) { this.processor = Object.assign({}, processor, options.processor); } if (this.blockStart === this.variableStart) { throw new Error('blockStart should be different with variableStart!'); } // create a regexp used to match leftStart this.startRegexp = utils.cache( `symbol_${this.blockStart}_${this.variableStart}_${this.commentStart}`, () => { // make sure can match the longest start string at first const str = [this.blockStart, this.variableStart, this.commentStart] .sort((a, b) => (a.length > b.length ? -1 : 1)) .map(item => utils.reStringFormat(item)) .join('|'); return new RegExp(str); } ); this.parse(html); this.optimize(); } parse(str) { if (!str) { return; } const collector = this.genCollector(); const parent = this.parent; const matches = str.match(this.startRegexp); const collectText = str => { const el = this.genNode(constant.TYPE_TEXT, str); this.processor.text(el); collector.push(el); }; if (!matches) { // parse end parent && utils.warn(`${parent.tag} was not closed`, parent); return collectText(str); } let element; this.endIndex = matches.index; const leftStart = matches[0]; const isTag = leftStart === this.blockStart; const isComment = leftStart === this.commentStart; collectText(str.substring(0, this.endIndex)); // get blockEnd or the other const rightEnd = isTag ? this.blockEnd : isComment ? this.commentEnd : this.variableEnd; str = this.advance(str, this.endIndex); // get rightEnd index this.endIndex = str.indexOf(rightEnd); const expression = str.substring(leftStart.length, this.endIndex); if (isComment) { // comment element = this.genNode(constant.TYPE_COM, leftStart + expression + rightEnd); element.comment = true; this.processor.comment(element); this.endIndex = this.endIndex >= 0 ? this.endIndex + rightEnd.length : str.length; } else if (this.endIndex < 0 || expression.indexOf(leftStart) >= 0) { // text collectText(leftStart); this.endIndex = leftStart.length; } else { this.endIndex = this.endIndex + rightEnd.length; if (parent && parent.raw) { // raw if (isTag && expression.trim() === 'endraw') { this.closeTag('raw'); } else { collectText(leftStart + expression + rightEnd); } } else if (isTag) { // tag const matches = expression.match(tagNameRE); const tagName = matches[0]; const isCustom = mus && mus.customTags.has(tagName); const tagHandle = this.processor[tagName] || (isCustom ? this.processor.custom : null); if (tagHandle) { // create ast node element = this.genNode( constant.TYPE_TAG, expression.substring(matches.index + tagName.length).trim() ); element[tagName] = true; element.tag = tagName; tagHandle.apply( this.processor, [element, isCustom ? mus.customTags.get(tagName) : null] ); if (!element.isUnary) { this.parent = element; } } else if (matches[1]) { this.closeTag(matches[2]); } else { utils.throw(`unknown tag '${expression.trim()}'`, this.genNode(null)); } } else { // variable element = this.genNode(constant.TYPE_VAR, expression); this.processor.variable(element); } } element && collector.push(element); this.parse(this.advance(str, this.endIndex)); } optimize(list = this.root) { const newList = []; for (let i = 0; i < list.length; i++) { const node = list[i]; const lastNode = newList[newList.length - 1]; if (node.type === constant.TYPE_TEXT) { if (this.compress) { let text = node.text; let matches; let newText = ''; // compress template while ((matches = text.match(spaceReg))) { const l = matches[1] || ''; const r = matches[2] || ''; const t = text.substring(0, matches.index); newText += t + l; // prevent comment in javascript or css if (t.indexOf('//') >= 0) { newText += '\n'; } newText += r; text = text.substring(matches.index + matches[0].length); } node.text = newText + text; } if (lastNode && lastNode.type === constant.TYPE_TEXT) { lastNode.text += node.text; } else { newList.push(node); } } else { if (!node.isAlone) { newList.push(node); } if (node.children) { node.children = this.optimize(node.children); } } } if (list === this.root) { this.root = newList; } return newList; } genNode(type, expr) { return { type, parent: this.parent, text: expr, _index: this.scanIndex, _len: this.endIndex, _ast: this, }; } advance(str, index) { this.scanIndex += index; return str.substring(index); } genCollector() { return this.parent ? (this.parent.children = this.parent.children || []) : this.root; } // close block // change current parent closeTag(tagName) { const p = this.parent; if (p) { this.parent = this.parent.parent; if (p.tag !== tagName) { if (!p.else && !p.elseif && !p.elif) { utils.warn(`${p.tag} was not closed`, p); } return this.closeTag(tagName); } else { return p; } } } } module.exports = function(html, options, fileUrl, musObj) { mus = musObj; const ast = new Ast(html, options, fileUrl); mus = null; return ast; };
var dir_53507bf88ef5425748f9348c5ded7768 = [ [ "structs", "dir_54d77f48aecee2faf230fe9d00e6d3d2.html", "dir_54d77f48aecee2faf230fe9d00e6d3d2" ], [ "Channel.hpp", "_channel_8hpp_source.html", null ], [ "Client.hpp", "_client_8hpp_source.html", null ], [ "functions.hpp", "functions_8hpp_source.html", null ], [ "Group.hpp", "_group_8hpp_source.html", null ], [ "Permission.hpp", "_permission_8hpp_source.html", null ], [ "Server.hpp", "_server_8hpp_source.html", null ] ];
Date.prototype.format = function (mask, utc) { return dateFormat(this, mask, utc); }; var currentMonth = new Date(); currentMonth.setUTCDate(1, 0, 0, 0, 0); var map = L.map('map', { zoom: 2, fullscreenControl: true, timeDimension: true, timeDimensionOptions:{ timeInterval: "1981-09/" + currentMonth.format("yyyy-mm"), period: "P1M", currentTime: Date.parse("1981-09-01T00:00:00Z") }, center: [20.0, 0.0], }); L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' }).addTo(map); var proxy = 'server/proxy.php'; var testWMS = "https://www.ncei.noaa.gov/thredds/wms/ncFC/fc-oisst-daily-avhrr-only-dly/OISST_Daily_AVHRR-only_Feature_Collection_best.ncd" var testLayer = L.tileLayer.wms(testWMS, { layers: 'sst', format: 'image/png', transparent: true, style: 'boxfill/sst_36', colorscalerange: '-3,35', abovemaxcolor: "extend", belowmincolor: "extend", attribution: '<a href="http://www.ncdc.noaa.gov">NOAAs National Climatic Data Center</a>' }); var testTimeLayer = L.timeDimension.layer.wms(testLayer, { proxy: proxy, updateTimeDimension: false, }); testTimeLayer.addTo(map); var testLegend = L.control({ position: 'topright' }); testLegend.onAdd = function(map) { var src = testWMS + "?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetLegendGraphic&LAYER=sst&PALETTE=sst_36&COLORSCALERANGE=-3,35"; var div = L.DomUtil.create('div', 'info legend'); div.innerHTML += '<img src="' + src + '" alt="legend">'; return div; }; testLegend.addTo(map); L.Control.TimeDimensionCustom = L.Control.TimeDimension.extend({ _getDisplayDateFormat: function(date){ return date.format("dS mmmm yyyy"); } }); var timeDimensionControl = new L.Control.TimeDimensionCustom({ playerOptions: { buffer: 1, minBufferReady: -1 } }); map.addControl(this.timeDimensionControl);
/** * authority-mgr.js */ define('authority-mgr',['jquery','base','liger.all'],function(require, exports, module){ var Base = require("base"); var $ = require("jquery"); require("liger.all")($); var ctx = Base.common.utils.getContextPath(); var typeEnum = {0:'超级管理员',1:'普通管理员',2:'高级用户',3:'普通用户',4:'过期用户'};//TODO 来自远程服务器 $("#portalMain").ligerPortal({ // draggable : true, columns: [{ width: '100%', panels: [{ title: 'url', width: '100%', height: 200, content: '<div id="urlContainer">ddd<div>' }, { title: '角色', width: '100%', height: 200, content: '<div id="roleContainer">ddd<div>' } ] }, { width: '100%', panels: [{ title: '用户', width: '100%', height: 200, content: '<div id="usrContainer">ddd<div>' } ] }] }); /** * 初始化表单按钮 */ function initFormBtns(){ var btns = []; btns.push({ text:'保存', click : function() { var form = liger.get("form"); var data = form.getData(); var param = {data:liger.toJSON(data)}; $.ajax({ url: ctx+ '/url/save.do', type : 'POST', dataType : 'json', data : param, success : function(backData) { if(backData){ $roleList.reload(); } } }); } }); btns.push({ text:'清空', click : function() { var form = liger.get("form"); form.setData({id:'',name:'',type:1,parentId: 1}); } }); return btns; } var $roleList = $("#urlContainer").ligerGrid({ url: ctx + "/url/fetch.do", root:'datas', columns: [ { display: '主键', hide:true, name:'id', align: 'left', width: 120 } , { display: '名称', name: 'name', minWidth: 150 }, { display: 'url', name: 'url', width: 150, align: 'left'}, { display: '上级', name: 'parentId', width: 150, align: 'left'}, { display: '类型', name: 'type', width: 150, align: 'left'} ], data: [], pageSize: 20, sortName: 'id', width: '100%', height: '170', checkbox: true, rownumbers:false, fixedCellHeight:false, toolbar:{ items: [ { text: '查询', click: query , icon:'add'}, { line:true }, { text: '修改', click: modify }, { line:true }, { text: '删除', click: del } ] } }); $("#usrContainer").ligerGrid({ url: ctx + "/usr/fetch.do", root:'datas', columns: [ { display: '主键', hide:true, name:'id', align: 'left', width: 120 } , { display: '用户名称', name: 'name', minWidth: 150 }, { display: '性别', name: 'sex', width: 150, align: 'left'}, { display: '电子邮件', name: 'email', width: 150, align: 'left'}, { display: '电话号码', name: 'phoneNumber', width: 150, align: 'left'}, { display: '年龄', name: 'age', width: 150, align: 'left'}, { display: '证件号', name: 'idCardNo', width: 150, align: 'left'}, { display: '类型', name: 'type', width: 150, align: 'left'} ], data: [], pageSize: 20, sortName: 'id', width: '100%', height: '170', checkbox: true, rownumbers:false, fixedCellHeight:false, toolbar:{ items: [ { text: '查询', click: query , icon:'add'}, { line:true }, { text: '修改', click: modify }, { line:true }, { text: '删除', click: del }, { line:true }/*, { text: '授权', click: del }, { line:true }, { text: '分配角色', click : assignRole}*/ ] } }); $("#roleContainer").ligerGrid({ url: ctx + "/role/fetch.do", root:'datas', columns: [ { display: '主键', hide: true, name:'id', align:'left', width: 120 } , { display: '角色名称', name: 'name', minWidth: 80 }, { display: '类型', name: 'type', width: 150, align: 'left',render:function (rowData, index, value){ rowData.type_real = rowData.type; value = typeEnum[rowData.type]; return value; }} ], data: [], pageSize: 20, sortName: 'name', width : '100%', height : '170', checkbox : true, rownumbers : false, isScroll : true, toolbar:{ items: [ { text: '增加', click: add , icon:'add'}, { line:true }, { text: '修改', click: modify }, { line:true }, { text: '删除', click: del }, { line:true }/*, { text: '分配权限', click: dispathAuthority }*/ ] }, fixedCellHeight: false }); function add(){} /** * 查询 */ function query(){ $.ligerDialog.success('查询'); } /** * 修改 */ function modify(){ var data = $roleList.getSelectedRow(); if(!data){ $.ligerDialog.warn('请选择要修改的记录'); return; } var form = liger.get("form"); console.log(data); form.setData(data); } /** * 删除记录 */ function del(){ $.ligerDialog.confirm('是否删除所选记录', function (yes){ if(yes){ var rows = $roleList.getSelectedRows(); var param = {user:liger.toJSON(rows)}; $.ajax({ url: ctx+ '/url/delete.do', type : 'POST', dataType : 'json', data : param, success : function(backData) { if(backData){ $.ligerDialog.tip({ title: '提示信息',content:'记录已经删除!'}); $roleList.reload(); } } }); } }); } $("#pageloading").hide(); });
import React, {Component} from 'react'; import {Link} from 'react-router' class Product extends Component { render() { var booleanCheck = function (value) { if (value == true) { return "Yes" } else { return "No" } }; return ( <Link to={'/product-page/' + this.props.product._id}> <div className="card"> <ul> <li><h4>{this.props.product.name}</h4></li> <li>SKU: {this.props.product.sku}</li> <li>Discontinued: {booleanCheck(this.props.product.discontinued)}</li> <li>Seasonal: {booleanCheck(this.props.product.seasonal)}</li> </ul> </div> </Link> ); } } export default Product;
define(['dummy'], function (Dummy) { var view = new Dummy.View(); $('main').html("POOP") })
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang("a11yhelp","nb",{title:"Instruksjoner for tilgjengelighet",contents:"Innhold for hjelp. Trykk ESC for å lukke denne dialogen.",legend:[{name:"Generelt",items:[{name:"Verktøylinje for editor",legend:"Trykk ${toolbarFocus} for å navigere til verktøylinjen. Flytt til neste og forrige verktøylinjegruppe med TAB og SHIFT-TAB. Flytt til neste og forrige verktøylinjeknapp med HØYRE PILTAST og VENSTRE PILTAST. Trykk MELLOMROM eller ENTER for å aktivere verktøylinjeknappen."},{name:"Dialog for editor", legend:"Mens du er i en dialog, trykk TAB for å navigere til neste dialogfelt, press SHIFT + TAB for å flytte til forrige felt, trykk ENTER for å akseptere dialogen, trykk ESC for å avbryte dialogen. For dialoger med flere faner, trykk ALT + F10 for å navigere til listen over faner. Gå til neste fane med TAB eller HØYRE PILTAST. Gå til forrige fane med SHIFT + TAB eller VENSTRE PILTAST. Trykk MELLOMROM eller ENTER for å velge fanen."},{name:"Kontekstmeny for editor",legend:"Trykk ${contextMenu} eller MENYKNAPP for å åpne kontekstmeny. Gå til neste alternativ i menyen med TAB eller PILTAST NED. Gå til forrige alternativ med SHIFT+TAB eller PILTAST OPP. Trykk MELLOMROM eller ENTER for å velge menyalternativet. Åpne undermenyen på valgt alternativ med MELLOMROM eller ENTER eller HØYRE PILTAST. Gå tilbake til overordnet menyelement med ESC eller VENSTRE PILTAST. Lukk kontekstmenyen med ESC."}, {name:"Listeboks for editor",legend:"I en listeboks, gå til neste alternativ i listen med TAB eller PILTAST NED. Gå til forrige alternativ i listen med SHIFT + TAB eller PILTAST OPP. Trykk MELLOMROM eller ENTER for å velge alternativet i listen. Trykk ESC for å lukke listeboksen."},{name:"Verktøylinje for elementsti",legend:"Trykk ${elementsPathFocus} for å navigere til verktøylinjen som viser elementsti. Gå til neste elementknapp med TAB eller HØYRE PILTAST. Gå til forrige elementknapp med SHIFT+TAB eller VENSTRE PILTAST. Trykk MELLOMROM eller ENTER for å velge elementet i editoren."}]}, {name:"Hurtigtaster",items:[{name:"Angre",legend:"Trykk ${undo}"},{name:"Gjør om",legend:"Trykk ${redo}"},{name:"Fet tekst",legend:"Trykk ${bold}"},{name:"Kursiv tekst",legend:"Trykk ${italic}"},{name:"Understreking",legend:"Trykk ${underline}"},{name:"Lenke",legend:"Trykk ${link}"},{name:"Skjul verktøylinje",legend:"Trykk ${toolbarCollapse}"},{name:"Gå til forrige fokusområde",legend:"Trykk ${accessPreviousSpace} for å komme til nærmeste fokusområde før skrivemarkøren som ikke kan nås på vanlig måte, for eksempel to tilstøtende HR-elementer. Gjenta tastekombinasjonen for å komme til fokusområder lenger unna i dokumentet."}, {name:"Gå til neste fokusområde",legend:"Trykk ${accessNextSpace} for å komme til nærmeste fokusområde etter skrivemarkøren som ikke kan nås på vanlig måte, for eksempel to tilstøtende HR-elementer. Gjenta tastekombinasjonen for å komme til fokusområder lenger unna i dokumentet."},{name:"Hjelp for tilgjengelighet",legend:"Trykk ${a11yHelp}"}]}],backspace:"Backspace",tab:"Tabulator",enter:"Enter",shift:"Shift",ctrl:"Ctrl",alt:"Alt",pause:"Pause",capslock:"Caps Lock",escape:"Escape",pageUp:"Page Up", pageDown:"Page Down",end:"End",home:"Home",leftArrow:"Venstre piltast",upArrow:"Opp-piltast",rightArrow:"Høyre piltast",downArrow:"Ned-piltast",insert:"Insert","delete":"Delete",leftWindowKey:"Venstre Windows-tast",rightWindowKey:"Høyre Windows-tast",selectKey:"Select key",numpad0:"Numerisk tastatur 0",numpad1:"Numerisk tastatur 1",numpad2:"Numerisk tastatur 2",numpad3:"Numerisk tastatur 3",numpad4:"Numerisk tastatur 4",numpad5:"Numerisk tastatur 5",numpad6:"Numerisk tastatur 6",numpad7:"Numerisk tastatur 7", numpad8:"Numerisk tastatur 8",numpad9:"Numerisk tastatur 9",multiply:"Multiply",add:"Add",subtract:"Subtract",decimalPoint:"Decimal Point",divide:"Divide",f1:"F1",f2:"F2",f3:"F3",f4:"F4",f5:"F5",f6:"F6",f7:"F7",f8:"F8",f9:"F9",f10:"F10",f11:"F11",f12:"F12",numLock:"Num Lock",scrollLock:"Scroll Lock",semiColon:"Semikolon",equalSign:"Likhetstegn",comma:"Komma",dash:"Bindestrek",period:"Punktum",forwardSlash:"Forover skråstrek",graveAccent:"Grave Accent",openBracket:"Open Bracket",backSlash:"Bakover skråstrek", closeBracket:"Close Bracket",singleQuote:"Single Quote"});
import firebase from 'firebase'; import React, { Component } from 'react'; import { View } from 'react-native'; import { FormLabel, FormInput, Button } from 'react-native-elements'; import axios from 'axios'; const ROOT_URL = 'https://us-central1-one-time-password-d704a.cloudfunctions.net'; class SignInForm extends Component { state = { phone: '', code: '' }; // using an arrow function prevent the need of ".bind(this) when the helper function is called" handleSubmit = async () => { const { phone, code } = this.state; try { let { data } = await axios.post(`${ROOT_URL}/verifyOneTimePassword`, { phone, code }); firebase.auth().signInWithCustomToken(data.token); } catch (err) { console.log(err); } } render() { return ( <View> <View style={{ marginBottom: 10 }}> <FormLabel>Enter Phone Number</FormLabel> <FormInput value={this.state.phone} onChangeText={phone => this.setState({ phone })} /> </View> <View style={{ marginBottom: 10 }}> <FormLabel>Enter Phone Code</FormLabel> <FormInput value={this.state.code} onChangeText={code => this.setState({ code })} /> </View> <Button title='Submit' onPress={this.handleSubmit} /> </View> ); } } export default SignInForm;
Package.describe({ 'summary': 'Fetch data from our Kadira Fetchman', 'name': 'local:kadira-data' }); Npm.depends({ "lru-cache": "2.6.4", "mongo-sharded-cluster": "1.2.0" }); Package.onTest(function(api) { configurePackage(api); api.addFiles([ 'test/server/init.js', 'test/server/helpers.js', 'test/server/methods.js', 'test/server/publish.js', ], ['server']); api.addFiles([ 'test/client/api.js' ], ['client']); api.use('tinytest'); api.use('practicalmeteor:sinon@1.10.3_2'); api.use('accounts-password'); api.use('insecure'); api.use('random'); }); Package.onUse(function(api) { configurePackage(api); api.export('KadiraData'); }); function configurePackage(api) { api.versionsFrom('METEOR@1.0'); api.use('mongo'); api.use('accounts-base'); api.use('underscore'); api.use('reactive-var', 'client'); api.use('check'); api.use('tracker', 'client'); api.use('ddp'); api.use('ejson'); api.use('meteorhacks:unblock@1.1.0'); api.use('cosmos:browserify@0.7.0'); api.use('local:plans-manager'); api.use('local:permissions-manager'); api.use('anti:i18n'); api.addFiles([ 'lib/namespace.js', 'lib/ranges.js' ]); api.addFiles([ 'lib/server/helpers.js', 'lib/server/api.js', 'lib/server/publish.js', 'lib/server/methods.js', ], ['server']); api.addFiles([ 'client.browserify.js', 'lib/client/api.js', 'lib/client/flow_mixin.js' ], ['client']); }
var StellarSdk = require('stellar-sdk'); StellarSdk.Network.useTestNetwork(); var server = new StellarSdk.Server('https://horizon-testnet.stellar.org'); // Keys for accounts to issue and receive the new asset var issuingKeys = StellarSdk.Keypair .fromSecret('SCZANGBA5YHTNYVVV4C3U252E2B6P6F5T3U6MM63WBSBZATAQI3EBTQ4'); var receivingKeys = StellarSdk.Keypair .fromSecret('SDSAVCRE5JRAI7UFAVLE5IMIZRD6N6WOJUWKY4GFN34LOBEEUS4W2T2D'); // Create an object to represent the new asset var astroDollar = new StellarSdk.Asset('ASD', issuingKeys.publicKey()); // First, the receiving account must trust the asset server.loadAccount(receivingKeys.publicKey()) .then(function(receiver) { var transaction = new StellarSdk.TransactionBuilder(receiver) // The `changeTrust` operation creates (or alters) a trustline // The `limit` parameter below is optional .addOperation(StellarSdk.Operation.changeTrust({ asset: astroDollar, limit: '1000' })) .build(); transaction.sign(receivingKeys); return server.submitTransaction(transaction); }) // Second, the issuing account actually sends a payment using the asset .then(function() { return server.loadAccount(issuingKeys.publicKey()) }) .then(function(issuer) { var transaction = new StellarSdk.TransactionBuilder(issuer) .addOperation(StellarSdk.Operation.payment({ destination: receivingKeys.publicKey(), asset: astroDollar, amount: '10' })) .build(); transaction.sign(issuingKeys); return server.submitTransaction(transaction); }) .catch(function(error) { console.error('Error!', error); });
// Compiled by ClojureScript 1.9.229 {} goog.provide('conway.core'); goog.require('cljs.core'); goog.require('reagent.core'); goog.require('conway.game'); conway.core.game_state = reagent.core.atom.call(null,conway.game.alternate.call(null,(9),(9),conway.game.alternate.call(null,(9),(10),conway.game.alternate.call(null,(9),(8),conway.game.Game_conway.call(null,(40),(17)))))); conway.core.next_state = (function conway$core$next_state(game){ return cljs.core.swap_BANG_.call(null,game,conway.game.play_round); }); conway.core.toggle = (function conway$core$toggle(something){ return cljs.core.swap_BANG_.call(null,something,cljs.core.update,new cljs.core.Keyword(null,"running","running",1554969103),(function (){ return cljs.core.not.call(null,new cljs.core.Keyword(null,"running","running",1554969103).cljs$core$IFn$_invoke$arity$1(cljs.core.deref.call(null,something))); })); }); conway.core.generations_loop = (function conway$core$generations_loop(switch$){ return setInterval((function (){ if(cljs.core.truth_(new cljs.core.Keyword(null,"running","running",1554969103).cljs$core$IFn$_invoke$arity$1(cljs.core.deref.call(null,switch$)))){ return conway.core.next_state.call(null,conway.core.game_state); } else { return null; } }),(1500)); }); conway.core.game_switch = cljs.core.atom.call(null,new cljs.core.PersistentArrayMap(null, 3, [new cljs.core.Keyword(null,"running","running",1554969103),true,new cljs.core.Keyword(null,"run-function","run-function",-475080789),(function (){ return conway.core.generations_loop.call(null,conway.core.game_switch); }),new cljs.core.Keyword(null,"btn-class","btn-class",1476521100),"pure-button-active"], null)); conway.core.toggle_class = (function conway$core$toggle_class(id,toggled_class){ var el_classList = document.getElementById(id).classList; if(cljs.core.truth_(el_classList.contains(toggled_class))){ return el_classList.remove(toggled_class); } else { return el_classList.add(toggled_class); } }); conway.core.toggle_html = (function conway$core$toggle_html(id,html1,html2){ var el = document.getElementById(id); if(cljs.core._EQ_.call(null,el.innerHTML,html1)){ return el.innerHTML = html2; } else { return el.innerHTML = html1; } }); conway.core.start_button_clicked = (function conway$core$start_button_clicked(){ conway.core.toggle_class.call(null,"start","pure-button-active"); conway.core.toggle_html.call(null,"start","Start","Stop"); return conway.core.toggle.call(null,conway.core.game_switch); }); conway.core.start_button = (function conway$core$start_button(){ return new cljs.core.PersistentVector(null, 3, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"button.pure-button","button.pure-button",698850720),new cljs.core.PersistentArrayMap(null, 4, [new cljs.core.Keyword(null,"class","class",-2030961996),"pure-button pure-button-active",new cljs.core.Keyword(null,"onClick","onClick",-1991238530),conway.core.start_button_clicked,new cljs.core.Keyword(null,"key","key",-1516042587),"start",new cljs.core.Keyword(null,"id","id",-1388402092),"start"], null),"Stop"], null); }); conway.core.title = (function conway$core$title(){ return new cljs.core.PersistentVector(null, 4, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"div","div",1057191632),new cljs.core.PersistentArrayMap(null, 2, [new cljs.core.Keyword(null,"id","id",-1388402092),"title-bar",new cljs.core.Keyword(null,"class","class",-2030961996),"pure-u-1"], null),new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"h1","h1",-1896887462),"An Implementation of Conway's Game of Life"], null),conway.core.start_button.call(null)], null); }); conway.core.cell = (function conway$core$cell(x,y,living){ return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"td","td",1479933353),new cljs.core.PersistentArrayMap(null, 3, [new cljs.core.Keyword(null,"key","key",-1516042587),cljs.core.gensym.call(null,[cljs.core.str(x),cljs.core.str(" "),cljs.core.str(y)].join('')),new cljs.core.Keyword(null,"class","class",-2030961996),(cljs.core.truth_(cljs.core.deref.call(null,living))?"cell alive":"cell dead"),new cljs.core.Keyword(null,"onClick","onClick",-1991238530),(function (){ return cljs.core.swap_BANG_.call(null,living,cljs.core.not); })], null)], null); }); conway.core.row = (function conway$core$row(cells){ return cljs.core.into.call(null,new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"tr","tr",-1424774646),new cljs.core.PersistentArrayMap(null, 3, [new cljs.core.Keyword(null,"class","class",-2030961996),"row",new cljs.core.Keyword(null,"key","key",-1516042587),cljs.core.gensym.call(null,cljs.core.rand.call(null,(1000))),new cljs.core.Keyword(null,"style","style",-496642736),new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"width","width",-384071477),[cljs.core.str((1.7 * cljs.core.count.call(null,cells))),cljs.core.str("em")].join('')], null)], null)], null),cells); }); conway.core.grid = (function conway$core$grid(width,height){ return new cljs.core.PersistentVector(null, 3, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"table","table",-564943036),new cljs.core.PersistentArrayMap(null, 3, [new cljs.core.Keyword(null,"key","key",-1516042587),"grid",new cljs.core.Keyword(null,"id","id",-1388402092),"grid",new cljs.core.Keyword(null,"class","class",-2030961996),"pure-u-23-24"], null),new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"tbody","tbody",-80678300),cljs.core.doall.call(null,cljs.core.map.call(null,conway.core.row,cljs.core.partition.call(null,width,cljs.core.doall.call(null,(function (){var iter__20969__auto__ = (function conway$core$grid_$_iter__23123(s__23124){ return (new cljs.core.LazySeq(null,(function (){ var s__23124__$1 = s__23124; while(true){ var temp__4657__auto__ = cljs.core.seq.call(null,s__23124__$1); if(temp__4657__auto__){ var xs__5205__auto__ = temp__4657__auto__; var y = cljs.core.first.call(null,xs__5205__auto__); var iterys__20965__auto__ = ((function (s__23124__$1,y,xs__5205__auto__,temp__4657__auto__){ return (function conway$core$grid_$_iter__23123_$_iter__23125(s__23126){ return (new cljs.core.LazySeq(null,((function (s__23124__$1,y,xs__5205__auto__,temp__4657__auto__){ return (function (){ var s__23126__$1 = s__23126; while(true){ var temp__4657__auto____$1 = cljs.core.seq.call(null,s__23126__$1); if(temp__4657__auto____$1){ var s__23126__$2 = temp__4657__auto____$1; if(cljs.core.chunked_seq_QMARK_.call(null,s__23126__$2)){ var c__20967__auto__ = cljs.core.chunk_first.call(null,s__23126__$2); var size__20968__auto__ = cljs.core.count.call(null,c__20967__auto__); var b__23128 = cljs.core.chunk_buffer.call(null,size__20968__auto__); if((function (){var i__23127 = (0); while(true){ if((i__23127 < size__20968__auto__)){ var x = cljs.core._nth.call(null,c__20967__auto__,i__23127); cljs.core.chunk_append.call(null,b__23128,new cljs.core.PersistentVector(null, 4, 5, cljs.core.PersistentVector.EMPTY_NODE, [conway.core.cell,x,y,reagent.core.cursor.call(null,conway.core.game_state,new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"grid","grid",402978600),conway.game.index.call(null,x,y,width)], null))], null)); var G__23129 = (i__23127 + (1)); i__23127 = G__23129; continue; } else { return true; } break; } })()){ return cljs.core.chunk_cons.call(null,cljs.core.chunk.call(null,b__23128),conway$core$grid_$_iter__23123_$_iter__23125.call(null,cljs.core.chunk_rest.call(null,s__23126__$2))); } else { return cljs.core.chunk_cons.call(null,cljs.core.chunk.call(null,b__23128),null); } } else { var x = cljs.core.first.call(null,s__23126__$2); return cljs.core.cons.call(null,new cljs.core.PersistentVector(null, 4, 5, cljs.core.PersistentVector.EMPTY_NODE, [conway.core.cell,x,y,reagent.core.cursor.call(null,conway.core.game_state,new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"grid","grid",402978600),conway.game.index.call(null,x,y,width)], null))], null),conway$core$grid_$_iter__23123_$_iter__23125.call(null,cljs.core.rest.call(null,s__23126__$2))); } } else { return null; } break; } });})(s__23124__$1,y,xs__5205__auto__,temp__4657__auto__)) ,null,null)); });})(s__23124__$1,y,xs__5205__auto__,temp__4657__auto__)) ; var fs__20966__auto__ = cljs.core.seq.call(null,iterys__20965__auto__.call(null,cljs.core.range.call(null,width))); if(fs__20966__auto__){ return cljs.core.concat.call(null,fs__20966__auto__,conway$core$grid_$_iter__23123.call(null,cljs.core.rest.call(null,s__23124__$1))); } else { var G__23130 = cljs.core.rest.call(null,s__23124__$1); s__23124__$1 = G__23130; continue; } } else { return null; } break; } }),null,null)); }); return iter__20969__auto__.call(null,cljs.core.range.call(null,height)); })()))))], null)], null); }); conway.core.app = (function conway$core$app(w,h){ return new cljs.core.PersistentVector(null, 4, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"div.app","div.app",-99849286),new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"class","class",-2030961996),"pure-g"], null),conway.core.grid.call(null,cljs.core.deref.call(null,w),cljs.core.deref.call(null,h)),conway.core.title.call(null)], null); }); conway.core.mount_root = (function conway$core$mount_root(){ return reagent.core.render_component.call(null,new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [(function (){ return conway.core.app.call(null,reagent.core.cursor.call(null,conway.core.game_state,new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"width","width",-384071477)], null)),reagent.core.cursor.call(null,conway.core.game_state,new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"height","height",1025178622)], null))); })], null),document.getElementById("app")); }); conway.core.init_BANG_ = (function conway$core$init_BANG_(){ conway.core.mount_root.call(null); return conway.core.generations_loop.call(null,conway.core.game_switch); }); //# sourceMappingURL=core.js.map?rel=1490131385109