code
stringlengths
2
1.05M
var chai = require('chai') var assert = chai.assert var currencyFormatter = require('./index') describe('format', () => { context('Default Options', () => { context('Symbol on the left', () => { context('No Space', () => { it('Returns -$10.00 for -10', () => { var result = currencyFormatter.format(-10, { code: 'USD' }) assert.equal(result, '-$10.00') }) it('Returns $0.00 for 0', () => { var result = currencyFormatter.format(0, { code: 'USD' }) assert.equal(result, '$0.00') }) it('Returns $10.00 for 10', () => { var result = currencyFormatter.format(10, { code: 'USD' }) assert.equal(result, '$10.00') }) it('Returns $100.00 for 100', () => { var result = currencyFormatter.format(100, { code: 'USD' }) assert.equal(result, '$100.00') }) it('Returns $1,000.00 for 1000', () => { var result = currencyFormatter.format(1000, { code: 'USD' }) assert.equal(result, '$1,000.00') }) it('Returns $10,000.00 for 10000', () => { var result = currencyFormatter.format(10000, { code: 'USD' }) assert.equal(result, '$10,000.00') }) it('Returns $1,000,000.00 for 1000000', () => { var result = currencyFormatter.format(1000000, { code: 'USD' }) assert.equal(result, '$1,000,000.00') }) }) context('With Space', () => { it('Returns -$ 10,00 for -10', () => { var result = currencyFormatter.format(-10, { code: 'ARS' }) assert.equal(result, '-$ 10,00') }) it('Returns $ 0,00 for 0', () => { var result = currencyFormatter.format(0, { code: 'ARS' }) assert.equal(result, '$ 0,00') }) it('Returns $ 10,00 for 10', () => { var result = currencyFormatter.format(10, { code: 'ARS' }) assert.equal(result, '$ 10,00') }) it('Returns $ 100,00 for 100', () => { var result = currencyFormatter.format(100, { code: 'ARS' }) assert.equal(result, '$ 100,00') }) it('Returns $ 1.000,00 for 1000', () => { var result = currencyFormatter.format(1000, { code: 'ARS' }) assert.equal(result, '$ 1.000,00') }) it('Returns $ 10.000,00 for 10000', () => { var result = currencyFormatter.format(10000, { code: 'ARS' }) assert.equal(result, '$ 10.000,00') }) it('Returns $ 1.000.000,00 for 1000000', () => { var result = currencyFormatter.format(1000000, { code: 'ARS' }) assert.equal(result, '$ 1.000.000,00') }) }) }) context('Symbol on the right', () => { context('No Space', () => { it('Returns -10.00Nfk for -10', () => { var result = currencyFormatter.format(-10, { code: 'ERN' }) assert.equal(result, '-10.00Nfk') }) it('Returns 0.00Nfk for 0', () => { var result = currencyFormatter.format(0, { code: 'ERN' }) assert.equal(result, '0.00Nfk') }) it('Returns 10.00Nfk for 10', () => { var result = currencyFormatter.format(10, { code: 'ERN' }) assert.equal(result, '10.00Nfk') }) it('Returns 100.00Nfk for 100', () => { var result = currencyFormatter.format(100, { code: 'ERN' }) assert.equal(result, '100.00Nfk') }) it('Returns 1,000.00Nfk for 1000', () => { var result = currencyFormatter.format(1000, { code: 'ERN' }) assert.equal(result, '1,000.00Nfk') }) it('Returns 10,000.00Nfk for 10000', () => { var result = currencyFormatter.format(10000, { code: 'ERN' }) assert.equal(result, '10,000.00Nfk') }) it('Returns 1,000,000.00Nfk for 1000000', () => { var result = currencyFormatter.format(1000000, { code: 'ERN' }) assert.equal(result, '1,000,000.00Nfk') }) }) context('With Space', () => { it('Returns -10,00 € for -10', () => { var result = currencyFormatter.format(-10, { code: 'EUR' }) assert.equal(result, '-10,00 €') }) it('Returns 0,00 € for 0', () => { var result = currencyFormatter.format(0, { code: 'EUR' }) assert.equal(result, '0,00 €') }) it('Returns 10,00 € for 10', () => { var result = currencyFormatter.format(10, { code: 'EUR' }) assert.equal(result, '10,00 €') }) it('Returns 100,00 € for 100', () => { var result = currencyFormatter.format(100, { code: 'EUR' }) assert.equal(result, '100,00 €') }) it('Returns 1 000,00 € for 1000', () => { var result = currencyFormatter.format(1000, { code: 'EUR' }) assert.equal(result, '1 000,00 €') }) it('Returns 10 000,00 € for 10000', () => { var result = currencyFormatter.format(10000, { code: 'EUR' }) assert.equal(result, '10 000,00 €') }) it('Returns 1 000 000,00 € for 1000000', () => { var result = currencyFormatter.format(1000000, { code: 'EUR' }) assert.equal(result, '1 000 000,00 €') }) }) }) }) context('Overriding Options', () => { it('Returns 1^000^000*000 ¯\\_(ツ)_/¯ for the given parameters', () => { var result = currencyFormatter.format(1000000, { code: 'USD', symbol: '¯\\_(ツ)_/¯', decimal: '*', thousand: '^', precision: 3, format: '%v %s' }) assert.equal(result, '1^000^000*000 ¯\\_(ツ)_/¯') }) it('Supports objects for format, to override the positive result', () => { var result = currencyFormatter.format(10, { code: 'USD', format: { pos: '%s %v', neg: '-%s%v' } }) assert.equal(result, '$ 10.00') }) it('Supports objects for format, to override the negative result', () => { var result = currencyFormatter.format(-10, { code: 'USD', format: { pos: '%s %v', neg: '(%s%v)' } }) assert.equal(result, '($10.00)') }) it('Supports empty symbol', () => { var result = currencyFormatter.format(1000000, { code: 'USD', symbol: '' }) assert.equal(result, '1,000,000.00') }) it('Supports empty decimal', () => { var result = currencyFormatter.format(1000000, { code: 'USD', decimal: '' }) assert.equal(result, '$1,000,00000') }) it('Supports empty thousands separator', () => { var result = currencyFormatter.format(1000000, { code: 'USD', thousand: '' }) assert.equal(result, '$1000000.00') }) it('Supports 0 precision digits', () => { var result = currencyFormatter.format(1000000, { code: 'USD', precision: 0 }) assert.equal(result, '$1,000,000') }) it('Supports empty format', () => { var result = currencyFormatter.format(1000000, { code: 'USD', format: '' }) assert.equal(result, '$1,000,000.00') }) }) context('When the currency is not found', () => { it('Uses default values', () => { var result = currencyFormatter.format(1000000, { code: 'None existing currency' }) assert.equal(result, '1,000,000.00') }) }) }) describe('currencies', () => { it('should be exposed as public via require()', () => { assert(Array.isArray(require('./currencies'))) }) it('should be exposed as public via .currencies', () => { assert(Array.isArray(currencyFormatter.currencies)) }) }) describe('findCurrency', () => { it('returns the expected currency for USD', () => { var expected = { code: 'USD', symbol: '$', thousandsSeparator: ',', decimalSeparator: '.', symbolOnLeft: true, spaceBetweenAmountAndSymbol: false, decimalDigits: 2 } var result = currencyFormatter.findCurrency('USD') assert.deepEqual(result, expected) }) it('returns the expected currency for EUR', () => { var expected = { code: 'EUR', symbol: '€', thousandsSeparator: ' ', decimalSeparator: ',', symbolOnLeft: false, spaceBetweenAmountAndSymbol: true, decimalDigits: 2 } var result = currencyFormatter.findCurrency('EUR') assert.deepEqual(result, expected) }) it('returns undefined when it can\'t find the currency', () => { var result = currencyFormatter.findCurrency('NON EXISTING') assert.isUndefined(result) }) })
$(document).ready(function() { $.urlParam = function(name){ var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href); if (results==null){ return null; } else{ return results[1] || 0; } } var uuid = $.urlParam('uuid') || okular.device_uuid || 'testdevice'; function updateData() { $.getJSON('/events/' + uuid, function(data) { var filled = false; var next = ''; var now; $.each(data, function(index, evt) { var start = moment.tz(evt.start.dateTime, evt.timeZone), end = moment.tz(evt.end.dateTime, evt.timeZone); if (!now) { now = moment.tz(new Date(), evt.timeZone); } var attendees = [evt.creator]; if ('attendees' in evt) { attendees = attendees.concat(evt.attendees); } attendees = $.map(attendees, function(a) { return a.displayName || a.email; }); if (start.isBefore(now) && now.isBefore(end) && !filled) { var text = '<h1>' + evt.summary + '</h1><h2>' + start.format('HH:mm') + '-' + end.format('HH:mm') + '</h2><h2>Atendees:</h2><h3>' + attendees.join(', ') + '</h3>'; if ($.trim($('#meeting div').html()) != text) { $('#meeting div').html(text); $('#finish, #cancel').show(); } filled = true; } else { next += '<button type="button" class="btn btn-success">' + start.format('HH:mm') + '-' + end.format('HH:mm') + '<br/>' + evt.summary + '</button>'; } }); if ($.trim($('#next').html()) != next) { $('#next').html(next); } if (!filled && $.trim($('#meeting div').html()) != '<h1>Room available</h1>') { $('#meeting div').html('<h1>Room available</h1>'); $('#finish, #cancel').hide(); } }); } $('#book').click(function(e) { $.get('/create_action/' + uuid + '/newevent', function(data) { console.log(data); $('#qr').show(); //$('#qr').html('Scan this code <div id="qrcode"></div> or open <p>' + data + '</p> in your browser.'); $('#qr').html('Scan this code <div id="qrcode"></div>'); new QRCode("qrcode", { text: data, width: 300, height: 300 }); $('#qr').tmList(); $('body').one('click', function() { $('#qr').hide(); okular.add({ width: 600, height: 600 }); }); }); }); $('#cancel').click(function(e) { $.get('/create_action/' + uuid + '/cancelevent', function(data) { $('#qr').show(); //$('#qr').html('Scan this code <div id="qrcode"></div> or open <p>' + data + '</p> in your browser.'); $('#qr').html('Scan this code <div id="qrcode"></div>'); new QRCode("qrcode", { text: data, width: 300, height: 300 }); $('#qr').tmList(); $('body').one('click', function() { $('#qr').hide(); okular.add({ width: 600, height: 600 }); }); }); }); $('#finish').click(function(e) { $.get('/create_action/' + uuid + '/finishevent', function(data) { $('#qr').show(); //$('#qr').html('Scan this code <div id="qrcode"></div> or open <p>' + data + '</p> in your browser.'); $('#qr').html('Scan this code <div id="qrcode"></div>'); new QRCode("qrcode", { text: data, width: 300, height: 300 }); $('#qr').tmList(); $('body').one('click', function() { $('#qr').hide(); okular.add({ width: 600, height: 600 }); }); }); }); okular.init({ width: 800, height: 600, debug: false }); updateData(); setInterval(updateData, 60000); $('#finish, #cancel').hide(); });
window.repatched = (window.repatched || 0) + 1; Page.patch(function(state) { document.body.dataset.repatched = (parseInt(document.body.dataset.repatched) || 0) + 1; });
import P, * as L from "partial.lenses" import {liftListBy as llb} from "./operators" const extend = Object.assign const always = value => () => value const equals = (a, b) => a === b export function makeModelDriver(initial, opts = {}) { const ID = {} const { logging = false, info = (...args) => console.info(...args), // eslint-disable-line warn = (...args) => console.warn(...args) // eslint-disable-line } = opts return function ModelDriver(mod$) { let state$ = mod$ .filter(m => (m && m.ID === ID) || (warn( "Received modification that was not created by using 'M.mods'. Ignoring.." ) && false)) .startWith(initial) .scan((s, {mod}) => mod(s)) if (logging) { state$ = state$.do(s => info("New state:", s)) } state$ = state$.replay(null, 1) state$.connect() return model(toProp(state$), L.identity) function model(state$, modLens) { const lens = (l, ...ls) => model(toProp(state$.map(L.get(P(l, ...ls)))), P(modLens, l, ...ls)) const mod = mod$ => mod$.map(mod => ({mod: L.modify(modLens, mod), ID})) const set = val$ => val$.map(val => ({mod: L.modify(modLens, always(val)), ID})) const log = prefix => model(state$.do(s => info(prefix, s)).shareReplay(1), modLens) const liftListBy = (identity, it, replay = ["DOM"]) => { const iterator = (ident, item$) => { const l = L.find(item => identity(item) === ident) return it(ident, model(item$, P(modLens, l))) } return llb(identity, state$, iterator, replay) } const liftListById = liftListBy.bind(null, it => it.id) return extend(state$, { lens, mod, set, liftListBy, liftListById, log }) } function toProp(val$) { return val$.distinctUntilChanged(x => x, equals).shareReplay(1) } } }
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.1.0-rc.5-master-3a0f323 */ (function( window, angular, undefined ){ "use strict"; /** * @ngdoc module * @name material.components.chips */ /* * @see js folder for chips implementation */ angular.module('material.components.chips', [ 'material.core', 'material.components.autocomplete' ]); angular .module('material.components.chips') .controller('MdChipCtrl', MdChipCtrl); /** * Controller for the MdChip component. Responsible for handling keyboard * events and editting the chip if needed. * * @param $scope * @param $element * @param $mdConstant * @param $timeout * @param $mdUtil * @constructor */ function MdChipCtrl ($scope, $element, $mdConstant, $timeout, $mdUtil) { /** * @type {$scope} */ this.$scope = $scope; /** * @type {$element} */ this.$element = $element; /** * @type {$mdConstant} */ this.$mdConstant = $mdConstant; /** * @type {$timeout} */ this.$timeout = $timeout; /** * @type {$mdUtil} */ this.$mdUtil = $mdUtil; /** * @type {boolean} */ this.isEditting = false; /** * @type {MdChipsCtrl} */ this.parentController = undefined; /** * @type {boolean} */ this.enableChipEdit = false; } MdChipCtrl.$inject = ["$scope", "$element", "$mdConstant", "$timeout", "$mdUtil"]; /** * @param {MdChipsCtrl} controller */ MdChipCtrl.prototype.init = function(controller) { this.parentController = controller; this.enableChipEdit = this.parentController.enableChipEdit; if (this.enableChipEdit) { this.$element.on('keydown', this.chipKeyDown.bind(this)); this.$element.on('mousedown', this.chipMouseDown.bind(this)); this.getChipContent().addClass('_md-chip-content-edit-is-enabled'); } }; /** * @return {Object} */ MdChipCtrl.prototype.getChipContent = function() { var chipContents = this.$element[0].getElementsByClassName('md-chip-content'); return angular.element(chipContents[0]); }; /** * @return {Object} */ MdChipCtrl.prototype.getContentElement = function() { return angular.element(this.getChipContent().children()[0]); }; /** * @return {number} */ MdChipCtrl.prototype.getChipIndex = function() { return parseInt(this.$element.attr('index')); }; /** * Presents an input element to edit the contents of the chip. */ MdChipCtrl.prototype.goOutOfEditMode = function() { if (!this.isEditting) return; this.isEditting = false; this.$element.removeClass('_md-chip-editing'); this.getChipContent()[0].contentEditable = 'false'; var chipIndex = this.getChipIndex(); var content = this.getContentElement().text(); if (content) { this.parentController.updateChipContents( chipIndex, this.getContentElement().text() ); this.$mdUtil.nextTick(function() { if (this.parentController.selectedChip === chipIndex) { this.parentController.focusChip(chipIndex); } }.bind(this)); } else { this.parentController.removeChipAndFocusInput(chipIndex); } }; /** * Given an HTML element. Selects contents of it. * @param node */ MdChipCtrl.prototype.selectNodeContents = function(node) { var range, selection; if (document.body.createTextRange) { range = document.body.createTextRange(); range.moveToElementText(node); range.select(); } else if (window.getSelection) { selection = window.getSelection(); range = document.createRange(); range.selectNodeContents(node); selection.removeAllRanges(); selection.addRange(range); } }; /** * Presents an input element to edit the contents of the chip. */ MdChipCtrl.prototype.goInEditMode = function() { this.isEditting = true; this.$element.addClass('_md-chip-editing'); this.getChipContent()[0].contentEditable = 'true'; this.getChipContent().on('blur', function() { this.goOutOfEditMode(); }.bind(this)); this.selectNodeContents(this.getChipContent()[0]); }; /** * Handles the keydown event on the chip element. If enable-chip-edit attribute is * set to true, space or enter keys can trigger going into edit mode. Enter can also * trigger submitting if the chip is already being edited. * @param event */ MdChipCtrl.prototype.chipKeyDown = function(event) { if (!this.isEditting && (event.keyCode === this.$mdConstant.KEY_CODE.ENTER || event.keyCode === this.$mdConstant.KEY_CODE.SPACE)) { event.preventDefault(); this.goInEditMode(); } else if (this.isEditting && event.keyCode === this.$mdConstant.KEY_CODE.ENTER) { event.preventDefault(); this.goOutOfEditMode(); } }; /** * Handles the double click event */ MdChipCtrl.prototype.chipMouseDown = function() { if(this.getChipIndex() == this.parentController.selectedChip && this.enableChipEdit && !this.isEditting) { this.goInEditMode(); } }; angular .module('material.components.chips') .directive('mdChip', MdChip); /** * @ngdoc directive * @name mdChip * @module material.components.chips * * @description * `<md-chip>` is a component used within `<md-chips>` and is responsible for rendering individual * chips. * * * @usage * <hljs lang="html"> * <md-chip>{{$chip}}</md-chip> * </hljs> * */ // This hint text is hidden within a chip but used by screen readers to // inform the user how they can interact with a chip. var DELETE_HINT_TEMPLATE = '\ <span ng-if="!$mdChipsCtrl.readonly" class="md-visually-hidden">\ {{$mdChipsCtrl.deleteHint}}\ </span>'; /** * MDChip Directive Definition * * @param $mdTheming * @param $mdUtil * ngInject */ function MdChip($mdTheming, $mdUtil) { var hintTemplate = $mdUtil.processTemplate(DELETE_HINT_TEMPLATE); return { restrict: 'E', require: ['^?mdChips', 'mdChip'], compile: compile, controller: 'MdChipCtrl' }; function compile(element, attr) { // Append the delete template element.append($mdUtil.processTemplate(hintTemplate)); return function postLink(scope, element, attr, ctrls) { var chipsController = ctrls.shift(); var chipController = ctrls.shift(); $mdTheming(element); if (chipsController) { chipController.init(chipsController); angular .element(element[0] .querySelector('.md-chip-content')) .on('blur', function () { chipsController.resetSelectedChip(); chipsController.$scope.$applyAsync(); }); } }; } } MdChip.$inject = ["$mdTheming", "$mdUtil"]; angular .module('material.components.chips') .directive('mdChipRemove', MdChipRemove); /** * @ngdoc directive * @name mdChipRemove * @restrict A * @module material.components.chips * * @description * Designates an element to be used as the delete button for a chip. <br/> * This element is passed as a child of the `md-chips` element. * * The designated button will be just appended to the chip and removes the given chip on click.<br/> * By default the button is not being styled by the `md-chips` component. * * @usage * <hljs lang="html"> * <md-chips> * <button md-chip-remove=""> * <md-icon md-svg-icon="md-close"></md-icon> * </button> * </md-chips> * </hljs> */ /** * MdChipRemove Directive Definition. * * @param $timeout * @returns {{restrict: string, require: string[], link: Function, scope: boolean}} * @constructor */ function MdChipRemove ($timeout) { return { restrict: 'A', require: '^mdChips', scope: false, link: postLink }; function postLink(scope, element, attr, ctrl) { element.on('click', function(event) { scope.$apply(function() { ctrl.removeChip(scope.$$replacedScope.$index); }); }); // Child elements aren't available until after a $timeout tick as they are hidden by an // `ng-if`. see http://goo.gl/zIWfuw $timeout(function() { element.attr({ tabindex: -1, 'aria-hidden': true }); element.find('button').attr('tabindex', '-1'); }); } } MdChipRemove.$inject = ["$timeout"]; angular .module('material.components.chips') .directive('mdChipTransclude', MdChipTransclude); function MdChipTransclude ($compile) { return { restrict: 'EA', terminal: true, link: link, scope: false }; function link (scope, element, attr) { var ctrl = scope.$parent.$mdChipsCtrl, newScope = ctrl.parent.$new(false, ctrl.parent); newScope.$$replacedScope = scope; newScope.$chip = scope.$chip; newScope.$index = scope.$index; newScope.$mdChipsCtrl = ctrl; var newHtml = ctrl.$scope.$eval(attr.mdChipTransclude); element.html(newHtml); $compile(element.contents())(newScope); } } MdChipTransclude.$inject = ["$compile"]; angular .module('material.components.chips') .controller('MdChipsCtrl', MdChipsCtrl); /** * Controller for the MdChips component. Responsible for adding to and * removing from the list of chips, marking chips as selected, and binding to * the models of various input components. * * @param $scope * @param $mdConstant * @param $log * @param $element * @param $mdUtil * @constructor */ function MdChipsCtrl ($scope, $mdConstant, $log, $element, $timeout, $mdUtil) { /** @type {$timeout} **/ this.$timeout = $timeout; /** @type {Object} */ this.$mdConstant = $mdConstant; /** @type {angular.$scope} */ this.$scope = $scope; /** @type {angular.$scope} */ this.parent = $scope.$parent; /** @type {$log} */ this.$log = $log; /** @type {$element} */ this.$element = $element; /** @type {angular.NgModelController} */ this.ngModelCtrl = null; /** @type {angular.NgModelController} */ this.userInputNgModelCtrl = null; /** @type {Element} */ this.userInputElement = null; /** @type {Array.<Object>} */ this.items = []; /** @type {number} */ this.selectedChip = -1; /** @type {boolean} */ this.hasAutocomplete = false; /** @type {string} */ this.enableChipEdit = $mdUtil.parseAttributeBoolean(this.mdEnableChipEdit); /** * Hidden hint text for how to delete a chip. Used to give context to screen readers. * @type {string} */ this.deleteHint = 'Press delete to remove this chip.'; /** * Hidden label for the delete button. Used to give context to screen readers. * @type {string} */ this.deleteButtonLabel = 'Remove'; /** * Model used by the input element. * @type {string} */ this.chipBuffer = ''; /** * Whether to use the transformChip expression to transform the chip buffer * before appending it to the list. * @type {boolean} */ this.useTransformChip = false; /** * Whether to use the onAdd expression to notify of chip additions. * @type {boolean} */ this.useOnAdd = false; /** * Whether to use the onRemove expression to notify of chip removals. * @type {boolean} */ this.useOnRemove = false; /** * Whether to use the onSelect expression to notify the component's user * after selecting a chip from the list. * @type {boolean} */ } MdChipsCtrl.$inject = ["$scope", "$mdConstant", "$log", "$element", "$timeout", "$mdUtil"]; /** * Handles the keydown event on the input element: by default <enter> appends * the buffer to the chip list, while backspace removes the last chip in the * list if the current buffer is empty. * @param event */ MdChipsCtrl.prototype.inputKeydown = function(event) { var chipBuffer = this.getChipBuffer(); // If we have an autocomplete, and it handled the event, we have nothing to do if (this.hasAutocomplete && event.isDefaultPrevented && event.isDefaultPrevented()) { return; } if (event.keyCode === this.$mdConstant.KEY_CODE.BACKSPACE) { // Only select and focus the previous chip, if the current caret position of the // input element is at the beginning. if (this.getCursorPosition(event.target) !== 0) { return; } event.preventDefault(); event.stopPropagation(); if (this.items.length) { this.selectAndFocusChipSafe(this.items.length - 1); } return; } // By default <enter> appends the buffer to the chip list. if (!this.separatorKeys || this.separatorKeys.length < 1) { this.separatorKeys = [this.$mdConstant.KEY_CODE.ENTER]; } // Support additional separator key codes in an array of `md-separator-keys`. if (this.separatorKeys.indexOf(event.keyCode) !== -1) { if ((this.hasAutocomplete && this.requireMatch) || !chipBuffer) return; event.preventDefault(); // Only append the chip and reset the chip buffer if the max chips limit isn't reached. if (this.hasMaxChipsReached()) return; this.appendChip(chipBuffer.trim()); this.resetChipBuffer(); } }; /** * Returns the cursor position of the specified input element. * @param element HTMLInputElement * @returns {Number} Cursor Position of the input. */ MdChipsCtrl.prototype.getCursorPosition = function(element) { /* * Figure out whether the current input for the chips buffer is valid for using * the selectionStart / end property to retrieve the cursor position. * Some browsers do not allow the use of those attributes, on different input types. */ try { if (element.selectionStart === element.selectionEnd) { return element.selectionStart; } } catch (e) { if (!element.value) { return 0; } } }; /** * Updates the content of the chip at given index * @param chipIndex * @param chipContents */ MdChipsCtrl.prototype.updateChipContents = function(chipIndex, chipContents){ if(chipIndex >= 0 && chipIndex < this.items.length) { this.items[chipIndex] = chipContents; this.ngModelCtrl.$setDirty(); } }; /** * Returns true if a chip is currently being edited. False otherwise. * @return {boolean} */ MdChipsCtrl.prototype.isEditingChip = function() { return !!this.$element[0].getElementsByClassName('_md-chip-editing').length; }; MdChipsCtrl.prototype.isRemovable = function() { // Return false if we have static chips if (!this.ngModelCtrl) { return false; } return this.readonly ? this.removable : angular.isDefined(this.removable) ? this.removable : true; }; /** * Handles the keydown event on the chip elements: backspace removes the selected chip, arrow * keys switch which chips is active * @param event */ MdChipsCtrl.prototype.chipKeydown = function (event) { if (this.getChipBuffer()) return; if (this.isEditingChip()) return; switch (event.keyCode) { case this.$mdConstant.KEY_CODE.BACKSPACE: case this.$mdConstant.KEY_CODE.DELETE: if (this.selectedChip < 0) return; event.preventDefault(); // Cancel the delete action only after the event cancel. Otherwise the page will go back. if (!this.isRemovable()) return; this.removeAndSelectAdjacentChip(this.selectedChip); break; case this.$mdConstant.KEY_CODE.LEFT_ARROW: event.preventDefault(); if (this.selectedChip < 0) this.selectedChip = this.items.length; if (this.items.length) this.selectAndFocusChipSafe(this.selectedChip - 1); break; case this.$mdConstant.KEY_CODE.RIGHT_ARROW: event.preventDefault(); this.selectAndFocusChipSafe(this.selectedChip + 1); break; case this.$mdConstant.KEY_CODE.ESCAPE: case this.$mdConstant.KEY_CODE.TAB: if (this.selectedChip < 0) return; event.preventDefault(); this.onFocus(); break; } }; /** * Get the input's placeholder - uses `placeholder` when list is empty and `secondary-placeholder` * when the list is non-empty. If `secondary-placeholder` is not provided, `placeholder` is used * always. */ MdChipsCtrl.prototype.getPlaceholder = function() { // Allow `secondary-placeholder` to be blank. var useSecondary = (this.items && this.items.length && (this.secondaryPlaceholder == '' || this.secondaryPlaceholder)); return useSecondary ? this.secondaryPlaceholder : this.placeholder; }; /** * Removes chip at {@code index} and selects the adjacent chip. * @param index */ MdChipsCtrl.prototype.removeAndSelectAdjacentChip = function(index) { var selIndex = this.getAdjacentChipIndex(index); this.removeChip(index); this.$timeout(angular.bind(this, function () { this.selectAndFocusChipSafe(selIndex); })); }; /** * Sets the selected chip index to -1. */ MdChipsCtrl.prototype.resetSelectedChip = function() { this.selectedChip = -1; }; /** * Gets the index of an adjacent chip to select after deletion. Adjacency is * determined as the next chip in the list, unless the target chip is the * last in the list, then it is the chip immediately preceding the target. If * there is only one item in the list, -1 is returned (select none). * The number returned is the index to select AFTER the target has been * removed. * If the current chip is not selected, then -1 is returned to select none. */ MdChipsCtrl.prototype.getAdjacentChipIndex = function(index) { var len = this.items.length - 1; return (len == 0) ? -1 : (index == len) ? index -1 : index; }; /** * Append the contents of the buffer to the chip list. This method will first * call out to the md-transform-chip method, if provided. * * @param newChip */ MdChipsCtrl.prototype.appendChip = function(newChip) { if (this.useTransformChip && this.transformChip) { var transformedChip = this.transformChip({'$chip': newChip}); // Check to make sure the chip is defined before assigning it, otherwise, we'll just assume // they want the string version. if (angular.isDefined(transformedChip)) { newChip = transformedChip; } } // If items contains an identical object to newChip, do not append if (angular.isObject(newChip)){ var identical = this.items.some(function(item){ return angular.equals(newChip, item); }); if (identical) return; } // Check for a null (but not undefined), or existing chip and cancel appending if (newChip == null || this.items.indexOf(newChip) + 1) return; // Append the new chip onto our list var index = this.items.push(newChip); // Update model validation this.ngModelCtrl.$setDirty(); this.validateModel(); // If they provide the md-on-add attribute, notify them of the chip addition if (this.useOnAdd && this.onAdd) { this.onAdd({ '$chip': newChip, '$index': index }); } }; /** * Sets whether to use the md-transform-chip expression. This expression is * bound to scope and controller in {@code MdChipsDirective} as * {@code transformChip}. Due to the nature of directive scope bindings, the * controller cannot know on its own/from the scope whether an expression was * actually provided. */ MdChipsCtrl.prototype.useTransformChipExpression = function() { this.useTransformChip = true; }; /** * Sets whether to use the md-on-add expression. This expression is * bound to scope and controller in {@code MdChipsDirective} as * {@code onAdd}. Due to the nature of directive scope bindings, the * controller cannot know on its own/from the scope whether an expression was * actually provided. */ MdChipsCtrl.prototype.useOnAddExpression = function() { this.useOnAdd = true; }; /** * Sets whether to use the md-on-remove expression. This expression is * bound to scope and controller in {@code MdChipsDirective} as * {@code onRemove}. Due to the nature of directive scope bindings, the * controller cannot know on its own/from the scope whether an expression was * actually provided. */ MdChipsCtrl.prototype.useOnRemoveExpression = function() { this.useOnRemove = true; }; /* * Sets whether to use the md-on-select expression. This expression is * bound to scope and controller in {@code MdChipsDirective} as * {@code onSelect}. Due to the nature of directive scope bindings, the * controller cannot know on its own/from the scope whether an expression was * actually provided. */ MdChipsCtrl.prototype.useOnSelectExpression = function() { this.useOnSelect = true; }; /** * Gets the input buffer. The input buffer can be the model bound to the * default input item {@code this.chipBuffer}, the {@code selectedItem} * model of an {@code md-autocomplete}, or, through some magic, the model * bound to any inpput or text area element found within a * {@code md-input-container} element. * @return {Object|string} */ MdChipsCtrl.prototype.getChipBuffer = function() { return !this.userInputElement ? this.chipBuffer : this.userInputNgModelCtrl ? this.userInputNgModelCtrl.$viewValue : this.userInputElement[0].value; }; /** * Resets the input buffer for either the internal input or user provided input element. */ MdChipsCtrl.prototype.resetChipBuffer = function() { if (this.userInputElement) { if (this.userInputNgModelCtrl) { this.userInputNgModelCtrl.$setViewValue(''); this.userInputNgModelCtrl.$render(); } else { this.userInputElement[0].value = ''; } } else { this.chipBuffer = ''; } }; MdChipsCtrl.prototype.hasMaxChipsReached = function() { if (angular.isString(this.maxChips)) this.maxChips = parseInt(this.maxChips, 10) || 0; return this.maxChips > 0 && this.items.length >= this.maxChips; }; /** * Updates the validity properties for the ngModel. */ MdChipsCtrl.prototype.validateModel = function() { this.ngModelCtrl.$setValidity('md-max-chips', !this.hasMaxChipsReached()); }; /** * Removes the chip at the given index. * @param index */ MdChipsCtrl.prototype.removeChip = function(index) { var removed = this.items.splice(index, 1); // Update model validation this.ngModelCtrl.$setDirty(); this.validateModel(); if (removed && removed.length && this.useOnRemove && this.onRemove) { this.onRemove({ '$chip': removed[0], '$index': index }); } }; MdChipsCtrl.prototype.removeChipAndFocusInput = function (index) { this.removeChip(index); this.onFocus(); }; /** * Selects the chip at `index`, * @param index */ MdChipsCtrl.prototype.selectAndFocusChipSafe = function(index) { if (!this.items.length) { this.selectChip(-1); this.onFocus(); return; } if (index === this.items.length) return this.onFocus(); index = Math.max(index, 0); index = Math.min(index, this.items.length - 1); this.selectChip(index); this.focusChip(index); }; /** * Marks the chip at the given index as selected. * @param index */ MdChipsCtrl.prototype.selectChip = function(index) { if (index >= -1 && index <= this.items.length) { this.selectedChip = index; // Fire the onSelect if provided if (this.useOnSelect && this.onSelect) { this.onSelect({'$chip': this.items[this.selectedChip] }); } } else { this.$log.warn('Selected Chip index out of bounds; ignoring.'); } }; /** * Selects the chip at `index` and gives it focus. * @param index */ MdChipsCtrl.prototype.selectAndFocusChip = function(index) { this.selectChip(index); if (index != -1) { this.focusChip(index); } }; /** * Call `focus()` on the chip at `index` */ MdChipsCtrl.prototype.focusChip = function(index) { this.$element[0].querySelector('md-chip[index="' + index + '"] .md-chip-content').focus(); }; /** * Configures the required interactions with the ngModel Controller. * Specifically, set {@code this.items} to the {@code NgModelCtrl#$viewVale}. * @param ngModelCtrl */ MdChipsCtrl.prototype.configureNgModel = function(ngModelCtrl) { this.ngModelCtrl = ngModelCtrl; var self = this; ngModelCtrl.$render = function() { // model is updated. do something. self.items = self.ngModelCtrl.$viewValue; }; }; MdChipsCtrl.prototype.onFocus = function () { var input = this.$element[0].querySelector('input'); input && input.focus(); this.resetSelectedChip(); }; MdChipsCtrl.prototype.onInputFocus = function () { this.inputHasFocus = true; this.resetSelectedChip(); }; MdChipsCtrl.prototype.onInputBlur = function () { this.inputHasFocus = false; }; /** * Configure event bindings on a user-provided input element. * @param inputElement */ MdChipsCtrl.prototype.configureUserInput = function(inputElement) { this.userInputElement = inputElement; // Find the NgModelCtrl for the input element var ngModelCtrl = inputElement.controller('ngModel'); // `.controller` will look in the parent as well. if (ngModelCtrl != this.ngModelCtrl) { this.userInputNgModelCtrl = ngModelCtrl; } var scope = this.$scope; var ctrl = this; // Run all of the events using evalAsync because a focus may fire a blur in the same digest loop var scopeApplyFn = function(event, fn) { scope.$evalAsync(angular.bind(ctrl, fn, event)); }; // Bind to keydown and focus events of input inputElement .attr({ tabindex: 0 }) .on('keydown', function(event) { scopeApplyFn(event, ctrl.inputKeydown) }) .on('focus', function(event) { scopeApplyFn(event, ctrl.onInputFocus) }) .on('blur', function(event) { scopeApplyFn(event, ctrl.onInputBlur) }) }; MdChipsCtrl.prototype.configureAutocomplete = function(ctrl) { if ( ctrl ) { this.hasAutocomplete = true; ctrl.registerSelectedItemWatcher(angular.bind(this, function (item) { if (item) { // Only append the chip and reset the chip buffer if the max chips limit isn't reached. if (this.hasMaxChipsReached()) return; this.appendChip(item); this.resetChipBuffer(); } })); this.$element.find('input') .on('focus',angular.bind(this, this.onInputFocus) ) .on('blur', angular.bind(this, this.onInputBlur) ); } }; MdChipsCtrl.prototype.hasFocus = function () { return this.inputHasFocus || this.selectedChip >= 0; }; angular .module('material.components.chips') .directive('mdChips', MdChips); /** * @ngdoc directive * @name mdChips * @module material.components.chips * * @description * `<md-chips>` is an input component for building lists of strings or objects. The list items are * displayed as 'chips'. This component can make use of an `<input>` element or an * `<md-autocomplete>` element. * * ### Custom templates * A custom template may be provided to render the content of each chip. This is achieved by * specifying an `<md-chip-template>` element containing the custom content as a child of * `<md-chips>`. * * Note: Any attributes on * `<md-chip-template>` will be dropped as only the innerHTML is used for the chip template. The * variables `$chip` and `$index` are available in the scope of `<md-chip-template>`, representing * the chip object and its index in the list of chips, respectively. * To override the chip delete control, include an element (ideally a button) with the attribute * `md-chip-remove`. A click listener to remove the chip will be added automatically. The element * is also placed as a sibling to the chip content (on which there are also click listeners) to * avoid a nested ng-click situation. * * <h3> Pending Features </h3> * <ul style="padding-left:20px;"> * * <ul>Style * <li>Colours for hover, press states (ripple?).</li> * </ul> * * <ul>Validation * <li>allow a validation callback</li> * <li>hilighting style for invalid chips</li> * </ul> * * <ul>Item mutation * <li>Support ` * <md-chip-edit>` template, show/hide the edit element on tap/click? double tap/double * click? * </li> * </ul> * * <ul>Truncation and Disambiguation (?) * <li>Truncate chip text where possible, but do not truncate entries such that two are * indistinguishable.</li> * </ul> * * <ul>Drag and Drop * <li>Drag and drop chips between related `<md-chips>` elements. * </li> * </ul> * </ul> * * <span style="font-size:.8em;text-align:center"> * Warning: This component is a WORK IN PROGRESS. If you use it now, * it will probably break on you in the future. * </span> * * Sometimes developers want to limit the amount of possible chips.<br/> * You can specify the maximum amount of chips by using the following markup. * * <hljs lang="html"> * <md-chips * ng-model="myItems" * placeholder="Add an item" * md-max-chips="5"> * </md-chips> * </hljs> * * In some cases, you have an autocomplete inside of the `md-chips`.<br/> * When the maximum amount of chips has been reached, you can also disable the autocomplete selection.<br/> * Here is an example markup. * * <hljs lang="html"> * <md-chips ng-model="myItems" md-max-chips="5"> * <md-autocomplete ng-hide="myItems.length > 5" ...></md-autocomplete> * </md-chips> * </hljs> * * @param {string=|object=} ng-model A model to bind the list of items to * @param {string=} placeholder Placeholder text that will be forwarded to the input. * @param {string=} secondary-placeholder Placeholder text that will be forwarded to the input, * displayed when there is at least one item in the list * @param {boolean=} md-removable Enables or disables the deletion of chips through the * removal icon or the Delete/Backspace key. Defaults to true. * @param {boolean=} readonly Disables list manipulation (deleting or adding list items), hiding * the input and delete buttons. If no `ng-model` is provided, the chips will automatically be * marked as readonly.<br/><br/> * When `md-removable` is not defined, the `md-remove` behavior will be overwritten and disabled. * @param {string=} md-enable-chip-edit Set this to "true" to enable editing of chip contents. The user can * go into edit mode with pressing "space", "enter", or double clicking on the chip. Chip edit is only * supported for chips with basic template. * @param {number=} md-max-chips The maximum number of chips allowed to add through user input. * <br/><br/>The validation property `md-max-chips` can be used when the max chips * amount is reached. * @param {expression} md-transform-chip An expression of form `myFunction($chip)` that when called * expects one of the following return values: * - an object representing the `$chip` input string * - `undefined` to simply add the `$chip` input string, or * - `null` to prevent the chip from being appended * @param {expression=} md-on-add An expression which will be called when a chip has been * added. * @param {expression=} md-on-remove An expression which will be called when a chip has been * removed. * @param {expression=} md-on-select An expression which will be called when a chip is selected. * @param {boolean} md-require-match If true, and the chips template contains an autocomplete, * only allow selection of pre-defined chips (i.e. you cannot add new ones). * @param {string=} delete-hint A string read by screen readers instructing users that pressing * the delete key will remove the chip. * @param {string=} delete-button-label A label for the delete button. Also hidden and read by * screen readers. * @param {expression=} md-separator-keys An array of key codes used to separate chips. * * @usage * <hljs lang="html"> * <md-chips * ng-model="myItems" * placeholder="Add an item" * readonly="isReadOnly"> * </md-chips> * </hljs> * * <h3>Validation</h3> * When using [ngMessages](https://docs.angularjs.org/api/ngMessages), you can show errors based * on our custom validators. * <hljs lang="html"> * <form name="userForm"> * <md-chips * name="fruits" * ng-model="myItems" * placeholder="Add an item" * md-max-chips="5"> * </md-chips> * <div ng-messages="userForm.fruits.$error" ng-if="userForm.$dirty"> * <div ng-message="md-max-chips">You reached the maximum amount of chips</div> * </div> * </form> * </hljs> * */ var MD_CHIPS_TEMPLATE = '\ <md-chips-wrap\ ng-keydown="$mdChipsCtrl.chipKeydown($event)"\ ng-class="{ \'md-focused\': $mdChipsCtrl.hasFocus(), \ \'md-readonly\': !$mdChipsCtrl.ngModelCtrl || $mdChipsCtrl.readonly,\ \'md-removable\': $mdChipsCtrl.isRemovable() }"\ class="md-chips">\ <md-chip ng-repeat="$chip in $mdChipsCtrl.items"\ index="{{$index}}"\ ng-class="{\'md-focused\': $mdChipsCtrl.selectedChip == $index, \'md-readonly\': !$mdChipsCtrl.ngModelCtrl || $mdChipsCtrl.readonly}">\ <div class="md-chip-content"\ tabindex="-1"\ aria-hidden="true"\ ng-click="!$mdChipsCtrl.readonly && $mdChipsCtrl.focusChip($index)"\ ng-focus="!$mdChipsCtrl.readonly && $mdChipsCtrl.selectChip($index)"\ md-chip-transclude="$mdChipsCtrl.chipContentsTemplate"></div>\ <div ng-if="$mdChipsCtrl.isRemovable()"\ class="md-chip-remove-container"\ md-chip-transclude="$mdChipsCtrl.chipRemoveTemplate"></div>\ </md-chip>\ <div class="md-chip-input-container" ng-if="!$mdChipsCtrl.readonly && $mdChipsCtrl.ngModelCtrl">\ <div md-chip-transclude="$mdChipsCtrl.chipInputTemplate"></div>\ </div>\ </md-chips-wrap>'; var CHIP_INPUT_TEMPLATE = '\ <input\ class="md-input"\ tabindex="0"\ placeholder="{{$mdChipsCtrl.getPlaceholder()}}"\ aria-label="{{$mdChipsCtrl.getPlaceholder()}}"\ ng-model="$mdChipsCtrl.chipBuffer"\ ng-focus="$mdChipsCtrl.onInputFocus()"\ ng-blur="$mdChipsCtrl.onInputBlur()"\ ng-keydown="$mdChipsCtrl.inputKeydown($event)">'; var CHIP_DEFAULT_TEMPLATE = '\ <span>{{$chip}}</span>'; var CHIP_REMOVE_TEMPLATE = '\ <button\ class="md-chip-remove"\ ng-if="$mdChipsCtrl.isRemovable()"\ ng-click="$mdChipsCtrl.removeChipAndFocusInput($$replacedScope.$index)"\ type="button"\ aria-hidden="true"\ tabindex="-1">\ <md-icon md-svg-src="{{ $mdChipsCtrl.mdCloseIcon }}"></md-icon>\ <span class="md-visually-hidden">\ {{$mdChipsCtrl.deleteButtonLabel}}\ </span>\ </button>'; /** * MDChips Directive Definition */ function MdChips ($mdTheming, $mdUtil, $compile, $log, $timeout, $$mdSvgRegistry) { // Run our templates through $mdUtil.processTemplate() to allow custom start/end symbols var templates = getTemplates(); return { template: function(element, attrs) { // Clone the element into an attribute. By prepending the attribute // name with '$', Angular won't write it into the DOM. The cloned // element propagates to the link function via the attrs argument, // where various contained-elements can be consumed. attrs['$mdUserTemplate'] = element.clone(); return templates.chips; }, require: ['mdChips'], restrict: 'E', controller: 'MdChipsCtrl', controllerAs: '$mdChipsCtrl', bindToController: true, compile: compile, scope: { readonly: '=readonly', removable: '=mdRemovable', placeholder: '@', mdEnableChipEdit: '@', secondaryPlaceholder: '@', maxChips: '@mdMaxChips', transformChip: '&mdTransformChip', onAppend: '&mdOnAppend', onAdd: '&mdOnAdd', onRemove: '&mdOnRemove', onSelect: '&mdOnSelect', deleteHint: '@', deleteButtonLabel: '@', separatorKeys: '=?mdSeparatorKeys', requireMatch: '=?mdRequireMatch' } }; /** * Builds the final template for `md-chips` and returns the postLink function. * * Building the template involves 3 key components: * static chips * chip template * input control * * If no `ng-model` is provided, only the static chip work needs to be done. * * If no user-passed `md-chip-template` exists, the default template is used. This resulting * template is appended to the chip content element. * * The remove button may be overridden by passing an element with an md-chip-remove attribute. * * If an `input` or `md-autocomplete` element is provided by the caller, it is set aside for * transclusion later. The transclusion happens in `postLink` as the parent scope is required. * If no user input is provided, a default one is appended to the input container node in the * template. * * Static Chips (i.e. `md-chip` elements passed from the caller) are gathered and set aside for * transclusion in the `postLink` function. * * * @param element * @param attr * @returns {Function} */ function compile(element, attr) { // Grab the user template from attr and reset the attribute to null. var userTemplate = attr['$mdUserTemplate']; attr['$mdUserTemplate'] = null; var chipTemplate = getTemplateByQuery('md-chips>md-chip-template'); var chipRemoveSelector = $mdUtil .prefixer() .buildList('md-chip-remove') .map(function(attr) { return 'md-chips>*[' + attr + ']'; }) .join(','); // Set the chip remove, chip contents and chip input templates. The link function will put // them on the scope for transclusion later. var chipRemoveTemplate = getTemplateByQuery(chipRemoveSelector) || templates.remove, chipContentsTemplate = chipTemplate || templates.default, chipInputTemplate = getTemplateByQuery('md-chips>md-autocomplete') || getTemplateByQuery('md-chips>input') || templates.input, staticChips = userTemplate.find('md-chip'); // Warn of malformed template. See #2545 if (userTemplate[0].querySelector('md-chip-template>*[md-chip-remove]')) { $log.warn('invalid placement of md-chip-remove within md-chip-template.'); } function getTemplateByQuery (query) { if (!attr.ngModel) return; var element = userTemplate[0].querySelector(query); return element && element.outerHTML; } /** * Configures controller and transcludes. */ return function postLink(scope, element, attrs, controllers) { $mdUtil.initOptionalProperties(scope, attr); $mdTheming(element); var mdChipsCtrl = controllers[0]; if(chipTemplate) { // Chip editing functionality assumes we are using the default chip template. mdChipsCtrl.enableChipEdit = false; } mdChipsCtrl.chipContentsTemplate = chipContentsTemplate; mdChipsCtrl.chipRemoveTemplate = chipRemoveTemplate; mdChipsCtrl.chipInputTemplate = chipInputTemplate; mdChipsCtrl.mdCloseIcon = $$mdSvgRegistry.mdClose; element .attr({ 'aria-hidden': true, tabindex: -1 }) .on('focus', function () { mdChipsCtrl.onFocus(); }); if (attr.ngModel) { mdChipsCtrl.configureNgModel(element.controller('ngModel')); // If an `md-transform-chip` attribute was set, tell the controller to use the expression // before appending chips. if (attrs.mdTransformChip) mdChipsCtrl.useTransformChipExpression(); // If an `md-on-append` attribute was set, tell the controller to use the expression // when appending chips. // // DEPRECATED: Will remove in official 1.0 release if (attrs.mdOnAppend) mdChipsCtrl.useOnAppendExpression(); // If an `md-on-add` attribute was set, tell the controller to use the expression // when adding chips. if (attrs.mdOnAdd) mdChipsCtrl.useOnAddExpression(); // If an `md-on-remove` attribute was set, tell the controller to use the expression // when removing chips. if (attrs.mdOnRemove) mdChipsCtrl.useOnRemoveExpression(); // If an `md-on-select` attribute was set, tell the controller to use the expression // when selecting chips. if (attrs.mdOnSelect) mdChipsCtrl.useOnSelectExpression(); // The md-autocomplete and input elements won't be compiled until after this directive // is complete (due to their nested nature). Wait a tick before looking for them to // configure the controller. if (chipInputTemplate != templates.input) { // The autocomplete will not appear until the readonly attribute is not true (i.e. // false or undefined), so we have to watch the readonly and then on the next tick // after the chip transclusion has run, we can configure the autocomplete and user // input. scope.$watch('$mdChipsCtrl.readonly', function(readonly) { if (!readonly) { $mdUtil.nextTick(function(){ if (chipInputTemplate.indexOf('<md-autocomplete') === 0) mdChipsCtrl .configureAutocomplete(element.find('md-autocomplete') .controller('mdAutocomplete')); mdChipsCtrl.configureUserInput(element.find('input')); }); } }); } // At the next tick, if we find an input, make sure it has the md-input class $mdUtil.nextTick(function() { var input = element.find('input'); input && input.toggleClass('md-input', true); }); } // Compile with the parent's scope and prepend any static chips to the wrapper. if (staticChips.length > 0) { var compiledStaticChips = $compile(staticChips.clone())(scope.$parent); $timeout(function() { element.find('md-chips-wrap').prepend(compiledStaticChips); }); } }; } function getTemplates() { return { chips: $mdUtil.processTemplate(MD_CHIPS_TEMPLATE), input: $mdUtil.processTemplate(CHIP_INPUT_TEMPLATE), default: $mdUtil.processTemplate(CHIP_DEFAULT_TEMPLATE), remove: $mdUtil.processTemplate(CHIP_REMOVE_TEMPLATE) }; } } MdChips.$inject = ["$mdTheming", "$mdUtil", "$compile", "$log", "$timeout", "$$mdSvgRegistry"]; angular .module('material.components.chips') .controller('MdContactChipsCtrl', MdContactChipsCtrl); /** * Controller for the MdContactChips component * @constructor */ function MdContactChipsCtrl () { /** @type {Object} */ this.selectedItem = null; /** @type {string} */ this.searchText = ''; } MdContactChipsCtrl.prototype.queryContact = function(searchText) { var results = this.contactQuery({'$query': searchText}); return this.filterSelected ? results.filter(angular.bind(this, this.filterSelectedContacts)) : results; }; MdContactChipsCtrl.prototype.itemName = function(item) { return item[this.contactName]; }; MdContactChipsCtrl.prototype.filterSelectedContacts = function(contact) { return this.contacts.indexOf(contact) == -1; }; angular .module('material.components.chips') .directive('mdContactChips', MdContactChips); /** * @ngdoc directive * @name mdContactChips * @module material.components.chips * * @description * `<md-contact-chips>` is an input component based on `md-chips` and makes use of an * `md-autocomplete` element. The component allows the caller to supply a query expression which * returns a list of possible contacts. The user can select one of these and add it to the list of * chips. * * You may also use the `md-highlight-text` directive along with its parameters to control the * appearance of the matched text inside of the contacts' autocomplete popup. * * @param {string=|object=} ng-model A model to bind the list of items to * @param {string=} placeholder Placeholder text that will be forwarded to the input. * @param {string=} secondary-placeholder Placeholder text that will be forwarded to the input, * displayed when there is at least on item in the list * @param {expression} md-contacts An expression expected to return contacts matching the search * test, `$query`. If this expression involves a promise, a loading bar is displayed while * waiting for it to resolve. * @param {string} md-contact-name The field name of the contact object representing the * contact's name. * @param {string} md-contact-email The field name of the contact object representing the * contact's email address. * @param {string} md-contact-image The field name of the contact object representing the * contact's image. * * * @param {expression=} filter-selected Whether to filter selected contacts from the list of * suggestions shown in the autocomplete. This attribute has been removed but may come back. * * * * @usage * <hljs lang="html"> * <md-contact-chips * ng-model="ctrl.contacts" * md-contacts="ctrl.querySearch($query)" * md-contact-name="name" * md-contact-image="image" * md-contact-email="email" * placeholder="To"> * </md-contact-chips> * </hljs> * */ var MD_CONTACT_CHIPS_TEMPLATE = '\ <md-chips class="md-contact-chips"\ ng-model="$mdContactChipsCtrl.contacts"\ md-require-match="$mdContactChipsCtrl.requireMatch"\ md-autocomplete-snap>\ <md-autocomplete\ md-menu-class="md-contact-chips-suggestions"\ md-selected-item="$mdContactChipsCtrl.selectedItem"\ md-search-text="$mdContactChipsCtrl.searchText"\ md-items="item in $mdContactChipsCtrl.queryContact($mdContactChipsCtrl.searchText)"\ md-item-text="$mdContactChipsCtrl.itemName(item)"\ md-no-cache="true"\ md-autoselect\ placeholder="{{$mdContactChipsCtrl.contacts.length == 0 ?\ $mdContactChipsCtrl.placeholder : $mdContactChipsCtrl.secondaryPlaceholder}}">\ <div class="md-contact-suggestion">\ <img \ ng-src="{{item[$mdContactChipsCtrl.contactImage]}}"\ alt="{{item[$mdContactChipsCtrl.contactName]}}"\ ng-if="item[$mdContactChipsCtrl.contactImage]" />\ <span class="md-contact-name" md-highlight-text="$mdContactChipsCtrl.searchText"\ md-highlight-flags="{{$mdContactChipsCtrl.highlightFlags}}">\ {{item[$mdContactChipsCtrl.contactName]}}\ </span>\ <span class="md-contact-email" >{{item[$mdContactChipsCtrl.contactEmail]}}</span>\ </div>\ </md-autocomplete>\ <md-chip-template>\ <div class="md-contact-avatar">\ <img \ ng-src="{{$chip[$mdContactChipsCtrl.contactImage]}}"\ alt="{{$chip[$mdContactChipsCtrl.contactName]}}"\ ng-if="$chip[$mdContactChipsCtrl.contactImage]" />\ </div>\ <div class="md-contact-name">\ {{$chip[$mdContactChipsCtrl.contactName]}}\ </div>\ </md-chip-template>\ </md-chips>'; /** * MDContactChips Directive Definition * * @param $mdTheming * @returns {*} * ngInject */ function MdContactChips($mdTheming, $mdUtil) { return { template: function(element, attrs) { return MD_CONTACT_CHIPS_TEMPLATE; }, restrict: 'E', controller: 'MdContactChipsCtrl', controllerAs: '$mdContactChipsCtrl', bindToController: true, compile: compile, scope: { contactQuery: '&mdContacts', placeholder: '@', secondaryPlaceholder: '@', contactName: '@mdContactName', contactImage: '@mdContactImage', contactEmail: '@mdContactEmail', contacts: '=ngModel', requireMatch: '=?mdRequireMatch', highlightFlags: '@?mdHighlightFlags' } }; function compile(element, attr) { return function postLink(scope, element, attrs, controllers) { $mdUtil.initOptionalProperties(scope, attr); $mdTheming(element); element.attr('tabindex', '-1'); }; } } MdContactChips.$inject = ["$mdTheming", "$mdUtil"]; })(window, window.angular);
CHAKRA = {}; CHAKRA.hues = [ 0, 30, 60, 120, 240, 260, 320 ]; // Requires ISPIRAL // CHAKRA.chakras = []; function Chakra(num, opts) { if (!opts) opts = {}; this.num = num; this.name = "Chakra"+num; this.spiral = null; this.imageSpiral = null; this.opts = opts; this.speed = 1; if (opts.speed) this.speed = opts.speed; this.init = function() { CHAKRA.chakras[this.num] = this; this.y = 100 + this.num*50; var ballSize = 20; var geo = new THREE.SphereGeometry( ballSize, 20, 20 ); var material = new THREE.MeshPhongMaterial( { color: 0xffaaaa } ); this.hue = CHAKRA.hues[this.num-1]/360; this.material = material; material.color.setHSL(this.hue, .9, .5); material.transparent = true; material.opacity = .6; var mesh = new THREE.Mesh( geo, material ); mesh.position.y = this.y; mesh.castShadow = false; mesh.receiveShadow = false; if (opts.scale) { report("Setting chakra scale "+opts.scale); mesh.scale.x = opts.scale[0]; mesh.scale.y = opts.scale[1]; mesh.scale.z = opts.scale[2]; } this.mesh = mesh; this.group = new THREE.Object3D(); this.group.add(mesh); if (opts.spiral) { this.addSpiral(); } if (opts.imageSpiral) { report("Chakra adding imageSpiral"); this.addImageSpiral(opts.imageSpiral); } if (opts.scene) opts.scene.add(this.group); } this.addSpiral = function(opts) { if (this.spiral) { this.spiral.group.visible = true; return; } this.spiral = new BallSpiral(200, {scale: [4,40,40], position: [0, this.y, 0], hue: this.hue}); this.spiral.group.rotation.z = Math.PI/2; this.group.add(this.spiral.group); } this.hideSpiral = function(opts) { if (this.spiral) this.spiral.group.visible = false; } this.addImageSpiral = function(opts) { if (this.imageSpiral) { this.imageSpiral.images.visible = true; return; } var imageList = opts.images; // list of paths if (imageList) { this.imageSpiral = new ImageSpiral(imageList, {scale: [4,20,20], position: [0,this.y,0]}); var images = this.imageSpiral.images; images.rotation.z = Math.PI/2; this.group.add(images); } else { report("**** no imageList given ****"); } } this.hideImageSpiral = function(opts) { if (this.imageSpiral) this.imageSpiral.images.visible = false; } this.update = function(t) { if (this.spiral) this.spiral.update(this.speed*t); if (this.imageSpiral) this.imageSpiral.update(this.speed*t); } this.init(); } CHAKRA.update = function(t) { // report("CHAKRA.update "+t); for (i in CHAKRA.chakras) { var chakra = CHAKRA.chakras[i]; chakra.update(t); } }
angular .module('tcxviewer.service') .factory('UploadService', ['$log', '$http', function($log, $http) { function _getData(url) { $log.warn('Get data'); var promise = $http({method:'GET', url: url}) .then(function _success(success) { return success.data; }, function _error(error) { return error; }); return promise; } var _factory = { getData: _getData }; return _factory; } ]);
/** * Implement a trie with insert, search, and startsWith methods. * * Note: * You may assume that all inputs are consist of lowercase letters a-z. * * The following picture explains construction of trie using keys given in the example below, * * root * / \ \ * t a b * | | | * h n y * | | \ | * e s y e * / | | * i r w * | | | * r e e * | * r * * Trie is an efficient information reTrieval data structure. Using Trie, * search complexities can be brought to optimal limit (key length). * * If we store keys in binary search tree, a well balanced BST will need time proportional to M * log N, * where M is maximum string length and N is number of keys in tree. Using Trie, we can search the key in O(M) time. * * However the penalty is on Trie storage requirements. */ class TrieNode { constructor() { this.children = {}; this.isEnd = false; } } export default class Trie { constructor() { this.root = new TrieNode(); } insert(word) { let current = this.root; for (let i = 0; i < word.length; i++) { if (!(word[i] in current.children)) { current.children[word[i]] = new TrieNode(); } current = current.children[word[i]]; } current.isEnd = true; } search(word) { let current = this.root; for (let i = 0; i < word.length; i++) { if (!(word[i] in current.children)) { return false; } current = current.children[word[i]]; } return current.isEnd; } startsWith(prefix) { let current = this.root; for (let i = 0; i < prefix.length; i++) { if (!(prefix[i] in current.children)) { return false; } current = current.children[prefix[i]]; } return true; } }
var variant_desc = "Chose a particular variant of a border, or set of borders. E.g. `somalia=1` or `somalia=2`. Multiple variants can be semicolon separated." var config = { apiVersion: "v1", modules: { data: { file: "data.js", description: "Returns data (such as names and dates) on political entities.", parameters: { get: { data_props: { description: "Data to retrieve. Will depend on the dataset, but `shapeid` (corresponding shape in the geo module), `name`, `sdate` (first date the entity should be present on a map), `edate` (last date), will always be available (use the `info` modul to find out more). Properties will be grouped by shape, and each shape will have an array of one or more political entities connected to it.", default: "id" }, data_lang: { description: "Laguage to use for translatable properties, such as name. Available and default languages will depend on dataset chosen (use the `info` modul to find out more)." }, language: { description: "Deprecated. Use data_lang.", deprecated: true, }, data_variant: { description: variant_desc } } } }, "info": { file: "info.js", description: "Returns metadata on a dataset." }, "geo": { file: "geo.js", description: "Returns geodata, as geojson or topojson.", parameters: { get: { geo_type: { description: "Format. Topojson is significantly smaller, but will take slightly longer for the API to produce.", default: "geojson", allowed: ["geojson", "topojson"] }, geo_crs: { description: "Coordinate reference system. Anything other that wgs84 will be reprojected, and therefore slower.", default: "wgs84", allowed: ["sweref99", "wgs84", "rt90", "tm35fin", "kkj", "etrs89"] //"ch1903" }, geo_variant: { description: variant_desc }, geo_scale: { description: "Scale. Use a larger scale for very large or zoomable maps.", default: "s", allowed: ["s", "m", "l"] }, geo_props: { description: "Data from the data module, to include in shape properties", default: "" }, geo_lang: { description: "Laguage to use for translatable properties, such as name. Available and default languages will depend on dataset chosen (use the `info` modul to find out more).", }, geo_flatten_props: { description: "Create a flat entity/property structure, rather than a two or three dimensional? There will not always be a one-to-one relation between geoshapes and data entities, but if you are fetching geo data from only one specific date, it might be useful to flatten the properties. Set this to `true` if you want to use the geodata in e.g. CartoDB. This will flatten not only entities, but also their properties.", allowed: ["true", "false"], default: "false" } } } }, "svg": { file: "svg.js", description: "Returns an SVG representation of the borders from a dataset at a certain time.", parameters: { get: { svg_proj: { description: "Defaults to the first recommended projection for this dataset. Use the info module to see all recommended projections.", }, projection: { description: "Deprecated. Use svg_proj.", deprecated: true, }, /* mode: { description: "Should we return a fully functional SVG images, or an array of paths for further processing?", allowed: ["paths", "full"], default: "full" },*/ width: { description: "Deprecated. Use svg_width.", deprecated: true, }, height: { description: "Deprecated. Use svg_height.", deprecated: true, }, svg_width: { description: "Used for viewport size, and, if mode=full, svg width attribute. (px)", default: 600 }, svg_height: { description: "Used for viewport size, and, if mode=full, svg heigh tattribute. (px)", default: 600 }, svg_variant: { description: variant_desc }, svg_props: { description: "Data from the data module, to include as data attributes", default: "" }, svg_lang: { description: "Laguage to use for translatable properties, such as name. Available and default languages will depend on dataset chosen (use the `info` modul to find out more).", }, } } } }, datasets: { /* bbox: always use WGS 84 recommendedProjections: The first of these this be used as default for SVG maps */ "fi-8": { description: "Finnish municipalities, from 2010", bbox: [19.1, 59.5, 31.6, 70.1], languages: ["sv", "fi", "en", "ru", "se", "et", "no"], defaultLanguage: "fi", recommendedProjections: ["tm35fin"] }, "ch-8": { description: "Swiss municipalities, from 2010. Data source: Federal Office of Topography. Please note the source when reusing the data.", bbox: [5.9,45.8,10.5,47.9], languages: ["als", "frp", "lmo", "de", "fr", "it", "rm", "en", "sq", "es", "tr", "pt"], defaultLanguage: "de", recommendedProjections: ["swissgrid"] }, "no-7": { description: "Norwegian municipalities, from 2012", bbox: [10, 54, 25, 70], languages: ["nb", "nn", "en", "se", "fi", "da"], defaultLanguage: "nb", recommendedProjections: ["euref89no"] }, "se-7": { description: "Swedish municipalities, from 1974 (a few borders in southern Sweden still missing from 1973)", bbox: [10, 54, 25, 70], languages: ["sv", "en", "fi", "se"], defaultLanguage: "sv", recommendedProjections: ["sweref99tm"] }, "se-4": { description: "Swedish counties, from 1968", bbox: [10, 54, 25, 70], languages: ["sv", "en", "fi", "se"], defaultLanguage: "sv", recommendedProjections: ["sweref99tm"] }, "us-4": { description: "US states", bbox: [-125,24,-67,49], languages: ["sv", "en", "es", "zh", "fr", "de", "it", "nl", "tl", "vi", "ik", "ko", "ru", "fa", "nv", "th", "chr", "ar"], defaultLanguage: "en", recommendedProjections: ["albersUsa"] }, "gl-7": { description: "Municipalities of Greenland since the home rule", bbox: [-74,59.5,-14,84], languages: ["kl", "da", "sv", "no", "en"], defaultLanguage: "kl", recommendedProjections: ["gr96"] }, "world-2": { description: "Countries of the world. Generally speaking, de-facto independent nation are included, even if when they enjoy limited international recognition.", bbox: [-180, -90, 180, 90], languages: ["sv","en","fi","fr","de","es","ru","it","nl","pl","zh","pt","ar","ja","fa","nn","no","he","tr","da","uk","ca","id","hu","vi","ko","et","cs","hi","sr","bg", "nn"], defaultLanguage: "en", recommendedProjections: ["robinson", "eckert4", "winkel3", "kavrayskiy7", "wagner6", "winkel3-pacific"] } }, datasetAliases: { "sweden-7": "se-7", "sweden7": "se-7", "se7": "se-7", "finland-8": "fi-8", "finland8": "fi-8", "fi8": "fi-8", "finland": "fi-8", "fi": "fi-8", "sweden-4": "se-4", "sweden4": "se-4", "se4": "se-4", "sweden": "se-7", "se": "se-7", "norway": "no-7", "no": "no-7", "world": "world-2", "us4": "us-4", "us": "us-4", "ch8": "ch-8", "ch": "ch-8", }, languageFallbacks: { //https://github.com/wikimedia/jquery.i18n/blob/master/src/jquery.i18n.fallbacks.js fit: "fi", fkv: "fi", nn: "nb", no: "nb", nn: "nn", sr: "sr-ec", uk: "ru", zh: "zh-hans", kl: "da", li: "nl", wa: "fr", als: "de", frp: "fr", lmo: "it" } } module.exports = config
// Generated by CoffeeScript 1.7.1 (function() { var es, isFunction, _; es = require('event-stream'); _ = require('lodash'); isFunction = function(f) { return {}.toString.call(f) === '[object Function]'; }; module.exports = function(opts, callback) { var buffer, bufferOrder, debouncedCallback, generateAggregatedStream; if (isFunction(opts)) { callback = opts; opts = {}; } if (!isFunction(callback)) { throw new Error("Invalid callback provided: " + callback); } if (opts.debounce == null) { opts.debounce = 50; } debouncedCallback = null; if (opts.debounce === 0) { debouncedCallback = function() { return callback(generateAggregatedStream()); }; } else { debouncedCallback = _.debounce(function() { return callback(generateAggregatedStream()); }, opts.debounce); } bufferOrder = []; buffer = {}; generateAggregatedStream = function() { var nextReadIndex, thisBuffer, thisBufferOrder; thisBufferOrder = _.clone(bufferOrder); thisBuffer = _.clone(buffer); nextReadIndex = 0; return es.readable(function(count, endRead) { while (count > 0) { if (nextReadIndex >= thisBufferOrder.length) { this.emit('end'); break; } this.emit('data', thisBuffer[thisBufferOrder[nextReadIndex]]); nextReadIndex++; count--; } return endRead(); }); }; return es.map(function(file, sendThrough) { if (buffer[file.path] == null) { bufferOrder.push(file.path); } buffer[file.path] = file; debouncedCallback(); return sendThrough(null, file); }); }; }).call(this);
version https://git-lfs.github.com/spec/v1 oid sha256:f808f0aa32fbe90fb9c9c846917faff3fdd4e236c284b76c02dd33753dc90177 size 35168
'use strict'; // Dependencies var controller = require('../controllers/login'); var basePath = '/login'; // Routes module.exports = function(app) { app.get(basePath, controller.renderPage); app.post(basePath, controller.authenticate); };
if (process.env.BROWSER) { require ('../../Sass/ImageLoader.sass'); } import React from 'react'; class ImageLoader extends React.Component{ constructor(props) { super(props); this.state = { show: props.showTransition }; this.handleImageLoaded = this.handleImageLoaded.bind(this); } componentDidMount() { let img = this.Img; if (img && img.complete && img.naturalHeight !== 0){ this.setState({show: true}); } } componentWillReceiveProps(nextProps){ if (nextProps.src === this.props.src || nextProps.reset===false) return; this.setState({show: false}); } handleImageLoaded(e){ this.setState({show: true}); } render() { let {src, cssClass, alt, minHeight, showLoading, showTransition} = this.props; let imgCssClass = (showTransition===false?" ":" transition"); cssClass += showLoading===false?" non-loading-div":" loading-div"; let loadingStyle={ minHeight: minHeight, backgroundImage: this.state.show?"none":this.props.loadingGif }; return( <div className={cssClass} style={loadingStyle}> <img src={src} alt={alt} style={{opacity: this.state.show?"1":"0"}} className={imgCssClass} title={this.props.title} onLoad={this.handleImageLoaded} ref={(el) => { this.Img = el; }} /> </div> ); } } ImageLoader.propTypes = { src: React.PropTypes.string, cssClass: React.PropTypes.string, alt: React.PropTypes.string, title: React.PropTypes.string, minHeight: React.PropTypes.string, showLoading: React.PropTypes.bool, showTransition: React.PropTypes.bool, loadingGif: React.PropTypes.string, }; ImageLoader.defaultProps = { loadingGif: "url('/build/img/ajax-loader.gif')" }; export {ImageLoader};
export default { shortLinks: {}, loading: false, error: null, };
version https://git-lfs.github.com/spec/v1 oid sha256:e06968c5eb518123341e410c88081b3f8a2a18719fb201471c893f399a6350ab size 156515
var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); var Post = mongoose.model('Post'); function isAuthenticated(req, res, next) { if (req.method === "GET") { return next(); } if (req.isAuthenticated()) { // user authenticated, continue return next(); } // user not authenticated, redirect to login page return res.redirect('/#login'); } //Register the authentication middleware router.use('/posts', isAuthenticated); router.route('/posts') // return all posts .get(function (req, res) { Post.find(function (err, data) { if (err) { return res.send(500, err); } return res.send(data); }); }) // add new post .post(function (req, res) { var post = new Post(); post.text = req.body.text; post.created_by = req.body.created_by; post.save(function (err, post) { if (err) { return res.send(500, err); } return res.json(post); }); }); router.route('/posts/:id') .get(function (req, res) { Post.findById(req.params.id, function (err, post) { if (err) { res.send(err); } res.json(post); }); }) .put(function (req, res) { Post.findById(req.params.id, function (err, post) { if (err) { res.send(err); } post.text = req.body.text; post.created_by = req.body.created_by; post.save(function (err, post) { if (err) { return res.send(err); } return res.json(post); }); }); }) .delete(function (req, res) { Post.remove({ _id: req.params.id }, function (err) { if (err) { return res.send(err); } return res.json("post deleted!"); }); }); module.exports = router;
"use strict"; var Promise = require("bluebird"), twitter = include("twitter-oauth"), querystring = require("querystring"), moment = require("moment"); module.exports = function(token, secret) { return function(term, sinceId) { return new Promise(function(resolve, reject) { twitter.search({ q: term, count: 100 }, token, secret, function(err, data) { if (err) reject(err); else resolve(data.statuses); }); }); }; }; function _buildUrl(url, term, sinceId) { var params = { q: term, count: 100, }; if (sinceId) params.sinceId = sinceId; else params.since = moment().format("YYYY-MM-DD"); return url + "?" + querystring.stringify(params); }
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["react-syntax-highlighter_languages_highlight_fsharp"],{ /***/ "./node_modules/highlight.js/lib/languages/fsharp.js": /*!***********************************************************!*\ !*** ./node_modules/highlight.js/lib/languages/fsharp.js ***! \***********************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function(hljs) { var TYPEPARAM = { begin: '<', end: '>', contains: [ hljs.inherit(hljs.TITLE_MODE, {begin: /'[a-zA-Z0-9_]+/}) ] }; return { aliases: ['fs'], keywords: 'abstract and as assert base begin class default delegate do done ' + 'downcast downto elif else end exception extern false finally for ' + 'fun function global if in inherit inline interface internal lazy let ' + 'match member module mutable namespace new null of open or ' + 'override private public rec return sig static struct then to ' + 'true try type upcast use val void when while with yield', illegal: /\/\*/, contains: [ { // monad builder keywords (matches before non-bang kws) className: 'keyword', begin: /\b(yield|return|let|do)!/ }, { className: 'string', begin: '@"', end: '"', contains: [{begin: '""'}] }, { className: 'string', begin: '"""', end: '"""' }, hljs.COMMENT('\\(\\*', '\\*\\)'), { className: 'class', beginKeywords: 'type', end: '\\(|=|$', excludeEnd: true, contains: [ hljs.UNDERSCORE_TITLE_MODE, TYPEPARAM ] }, { className: 'meta', begin: '\\[<', end: '>\\]', relevance: 10 }, { className: 'symbol', begin: '\\B(\'[A-Za-z])\\b', contains: [hljs.BACKSLASH_ESCAPE] }, hljs.C_LINE_COMMENT_MODE, hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: null}), hljs.C_NUMBER_MODE ] }; }; /***/ }) }]); //# sourceMappingURL=react-syntax-highlighter_languages_highlight_fsharp.js.map
/* * Signal2 * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var SignalAbstract_1 = require("./SignalAbstract"); /** * @namespace createts.events * @module createts * @class Signal2 */ var Signal2 = (function (_super) { __extends(Signal2, _super); function Signal2() { return _super.apply(this, arguments) || this; } /** * Emit the signal, notifying each connected listener. * * @method emit */ Signal2.prototype.emit = function (arg1, arg2) { var _this = this; if (this.dispatching()) { this.defer(function () { return _this.emitImpl(arg1, arg2); }); } else { this.emitImpl(arg1, arg2); } }; Signal2.prototype.emitImpl = function (arg1, arg2) { var head = this.willEmit(); var p = head; while (p != null) { p._listener(arg1, arg2); if (!p.stayInList) { p.dispose(); } p = p._next; } this.didEmit(head); }; return Signal2; }(SignalAbstract_1.SignalAbstract)); exports.Signal2 = Signal2;
export default (verifedType) => { if (!verifedType) { return false } let regexStr = '' let dataTypeNameStr = '' switch (verifedType) { case 'number': { regexStr = /^[0-9]*$/ dataTypeNameStr = '数字' break } case 'url': { regexStr = /^((http:|https:|)\/\/)(www.)?\w+.\w+/ dataTypeNameStr = '超链接' break } case 'mobile': { regexStr = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/ dataTypeNameStr = '手机' break } case 'tel': { regexStr = /^(0[1-9]{2})-\d{8}$|^(0[1-9]{3}-(\d{7,8}))$/ dataTypeNameStr = '电话' break } case 'email': { regexStr = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/ dataTypeNameStr = '邮箱地址' break } case 'password': { regexStr = /^[\@A-Za-z0-9\_]{6,18}$/ dataTypeNameStr = '密码' break } default: { regexStr = new RegExp(regexStr) dataTypeNameStr = '格式不對' break } } return { regex: regexStr, dataTypeName: dataTypeNameStr } }
'use strict'; module.exports = function(array) { if (!array.length) { return Promise.reject(new Error('Randomize error: Array is empty.')); } return Promise.all(array.slice().sort(function() { return 0.5 - Math.random(); })); };
(function (factory) { if (typeof define === "function" && define.amd) { // AMD anonymous module define(["knockout", "jquery", "handsontable","numeral"], factory); } else { // No module loader (plain <script> tag) - put directly in global namespace factory(window.ko, jQuery, window.handsontable); } })(function (ko, $, undefined) { var unwrap = ko.utils.unwrapObservable; var peekByString = function (o, s) { if(s) { s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties s = s.replace(/^\./, ''); // strip a leading dot var a = s.split('.'); while (a.length) { var n = a.shift(); if (n in o) { o = o[n]; } else { return; } } return o; } }; function setData(key, val, obj) { if (!obj) obj = data; //outside (non-recursive) call, use "data" as our base object var ka = key.split(/\./); //split the key by the dots if (ka.length < 2) { obj[ka[0]] = val; //only one part (no dots) in key, just set value } else { if (!obj[ka[0]]) obj[ka[0]] = {}; //create our "new" base obj if it doesn't exist obj = obj[ka.shift()]; //remove the new "base" obj from string array, and hold actual object for recursive call setData(ka.join("."), val, obj); //join the remaining parts back up with dots, and recursively set data on our new "base" obj } } //connect items with observableArrays var prepareColumnOptions = function (columns) { var props = '', mappedColumns; if(columns){ mappedColumns = $.map(columns, function (propertyName, index) { return {data: (function (attr) { return function (row, value) { prop = peekByString(row, propertyName.data); if (prop != null) { if (typeof value === 'undefined') { // GET return ko.utils.unwrapObservable(prop); } else { // SET if (typeof prop === 'function') { prop(value); } else { setData(propertyName.data, value, row); //prop = value; } } } } } )(),type:(function (attr) { if (propertyName.type){ return propertyName.type; }else return 'text'; })(), source:(function (attr) { if (propertyName.source){ return propertyName.source; }})(), renderer:(function (attr) { if (propertyName.renderer){ return propertyName.renderer; }})(), readOnly:(function (attr) { if (propertyName.readOnly){ return propertyName.readOnly; }else return false; })() } }); return mappedColumns; } } ko.bindingHandlers.handsontable = { init: function (element, valueAccessor, allBindingsAccessor, data, context) { var $element = $(element), options = unwrap(valueAccessor()) || {}, // tipos= allBindingsAccessor columns = unwrap(options.columns) || {}; options.columns = prepareColumnOptions(columns); // return data in array format $element.handsontable(options); //$element.find("table").addClass("table table-condensed table-hover"); if(options.panel){ options.panel($element.handsontable("getInstance")); ko.utils.domNodeDisposal.addDisposeCallback(element, function() { options.panel(null); }); } }, update: function (element, valueAccessor, allBindingsAccessor, data, context) { $(element).handsontable('render'); }, }; });
angular .controller('pdfviewerCtrl', loadFunction); loadFunction.$inject = ['$scope', '$filter', 'structureService', '$location']; function loadFunction($scope, $filter, structureService, $location) { //Register upper level modules structureService.registerModule($location, $scope, "pdfviewer"); $scope.init = function () { var url = $scope.pdfviewer.modulescope.value; $scope.iframeSrc = "https://docs.google.com/viewer?url=" + url + "&embedded=true"; }; }
import Chest from './Chest.js' class RoomCreator extends Phaser.Group { constructor(game) { super(game, null, 'decoration') const world = this.game.world this.game.add.sprite(0, 0, 'stage01') var puerta = this.game.add.sprite(this.game.world.width + 115, this.game.world.centerY, 'puerta') puerta.anchor.setTo(1, 0.5) this.floor = this.addChild(this.game.make.group()) this.game.behindEverything = this.addChild(this.game.make.group()) var steps = 0 for (var n = 0; n < 4; n++) { if(steps++ > 10000) break var randomPos = new Phaser.Point(200 + Math.random() * (world.width - 600), 150 + Math.random() * (world.height - 250)) if (this.checkCloseObjects(randomPos, 300, 'alfombra')) { const alfombra = this.floor.create(randomPos.x, randomPos.y, 'alfombra_1') alfombra.anchor.set(0.5) alfombra.scale.set(1.8) alfombra.type = 'alfombra' } else n-- } steps = 0 for (var n = 0; n < 4; n++) { if(steps++ > 10000) break var randomPos = new Phaser.Point(200 + Math.random() * (world.width - 500), 70) if (this.checkCloseObjects(randomPos, 100)) { const estanteria = this.create(randomPos.x, randomPos.y, 'estanteria') this.game.physics.p2.enable(estanteria) estanteria.scale.set(1.4) estanteria.body.kinematic = true } else n-- } steps = 0 for (var n = 0; n < 8; n++) { if(steps++ > 10000) break var randomPos = new Phaser.Point(200 + Math.random() * (world.width - 500), 100 + Math.random() * (world.height - 150)) if (this.checkCloseObjects(randomPos, 250)) { const sprite = Math.random() < 0.5 ? 'mesa_1' : 'mesa_2' if (Math.random() < 0.25) { const alfombra = this.floor.create(randomPos.x, randomPos.y, 'alfombra_1') alfombra.anchor.set(0.5) alfombra.scale.set(1.4) } const mesa = this.create(randomPos.x, randomPos.y, sprite) this.game.physics.p2.enable(mesa) mesa.body.kinematic = true } else n-- } steps = 0 for (var n = 0; n < 4; n++) { if(steps++ > 10000) break var randomPos = new Phaser.Point(200 + Math.random() * (world.width - 500), 100 + Math.random() * (world.height - 150)) if (this.checkCloseObjects(randomPos, 100)) { const cofre = this.add(new Chest(this.game, randomPos.x, randomPos.y)) } else n-- } } update() { super.update() } checkCloseObjects(point, maxDistance, type = false) { var chkGroup = group => { var result = true group.forEach(val => { if (val.children.length) result = result && chkGroup(val.children) if ((!type || type == val.type) && Phaser.Math.distance(val.x, val.y, point.x, point.y) <= maxDistance) { result = false } }) return result } return chkGroup(this.children) } } module.exports = RoomCreator
var zomato = require('zomato'); var Restaurant = require('./zomato/Restaurant.js'); let selectedCuisines = ["British", "Chinese"]; let client = zomato.createClient({ userKey: '4a3b30ef356a829e79e73f8886f0aa0e', }); //3rd function restaurants(locations, cuisines, callback) { let cuisineIds = new Array(); selectedCuisines.forEach(function(cuisine) { let cuisineId = getcuisineId(cuisine, cuisines); console.log("cuisineId returned " + cuisineId); cuisineIds.push(cuisineId); }) client.search({ entity_id: locations[0].id, //location id entity_type: "city", // location type (city,subzone,zone , landmark, metro,group) count: "3", // number of maximum result to display start: "1", //fetch results after offset radius: "10000", //radius around (lat,lon); to define search area, defined in meters(M) cuisines: cuisineIds, //list of cuisine id's separated by comma sort: "rating", //choose any one out of these available choices order: "asc" // used with 'sort' parameter to define ascending(asc )/ descending(desc) }, function(err, restaurants) { if (!err) { let parsedResponse = JSON.parse(restaurants); let sortedRestaurents = new Array(); parsedResponse.restaurants.forEach(function(restaurantData) { var restaurant = new Restaurant(restaurantData.restaurant); sortedRestaurents.push(restaurant); console.log('Restaurant added') }) callback(err, sortedRestaurents) } else { console.log(err); } }); } //2nd function getCuisines(locations, callback) { client.getCuisines({ city_id: locations[0].id, }, function(err, result) { if (!err) { let cuisineResult = JSON.parse(result); let cuisines = cuisineResult.cuisines; restaurants(locations, cuisines, callback); } else { console.log(err); } }); } function getCity(lat, long) { } //utils function getcuisineId(cuisineName, cuisines) { let availableCuisines = cuisines; let cuisineId = ""; availableCuisines.forEach(function(availableCuisine) { if (availableCuisine.cuisine.cuisine_name == cuisineName) { console.log("entered loop returning " + availableCuisine.cuisine.cuisine_id) cuisineId = availableCuisine.cuisine.cuisine_id; } }) return cuisineId; } function addQuotes(string) { return '"' + string + '"'; } module.exports = { requestLocations: function(callback) { client.getCities({ q: "Belfast", count: "1" }, function(err, result) { if (!err) { let cityResponse = JSON.parse(result); let locations = cityResponse.location_suggestions; let cuisines = getCuisines(locations, callback); console.log('Function returned ${cuisines}') } else { console.log(err); } }) } } var Buz = function () {}; Buz.prototype.requestLocations = function(callback) { client.getCities({ q: "Belfast", count: "1" }, function(err, result) { if (!err) { let cityResponse = JSON.parse(result); let locations = cityResponse.location_suggestions; let cuisines = getCuisines(locations, callback); console.log('Function returned ${cuisines}') } else { console.log(err); } }) } module.exports = new Buz(); require('make-runnable');
import React from 'react'; import _ from 'underscore'; import * as Babel from 'babel-standalone'; export function createCompiler(context) { const iframe = createIframe(); return createEvalWithContext(iframe, context); } export function createIframe(_document = document) { let iframe = _document.createElement('iframe'); if (!iframe.style) iframe.style = {}; iframe.style.display = 'none'; _document.body.appendChild(iframe); return iframe; } export function removeIframe(iframe) { iframe && iframe.parent && iframe.parent.removeChild(iframe); } function createEvalWithContext(iframe, context = {}) { let win = iframe.contentWindow; _.extend(win, context, {React}); return (input) => { // defensive measures if (typeof input !== 'string') return null; input = input.trim(); if (!input) return null; const jsCode = Babel.transform(input.trim(), { presets: ['es2015', 'react'] }).code; return win.eval.call(win, jsCode); }; }
/** * Copyright (c) 2015 Trent Mick. * Copyright (c) 2015 Joyent Inc. * * The bunyan logging library for node.js. * * -*- mode: js -*- * vim: expandtab:ts=4:sw=4 */ var VERSION = '1.8.5'; /* * Bunyan log format version. This becomes the 'v' field on all log records. * This will be incremented if there is any backward incompatible change to * the log record format. Details will be in 'CHANGES.md' (the change log). */ var LOG_VERSION = 0; var xxx = function xxx(s) { // internal dev/debug logging var args = ['XX' + 'X: '+s].concat( Array.prototype.slice.call(arguments, 1)); console.error.apply(this, args); }; var xxx = function xxx() {}; // comment out to turn on debug logging /* * Runtime environment notes: * * Bunyan is intended to run in a number of runtime environments. Here are * some notes on differences for those envs and how the code copes. * * - node.js: The primary target environment. * - NW.js: http://nwjs.io/ An *app* environment that feels like both a * node env -- it has node-like globals (`process`, `global`) and * browser-like globals (`window`, `navigator`). My *understanding* is that * bunyan can operate as if this is vanilla node.js. * - browser: Failing the above, we sniff using the `window` global * <https://developer.mozilla.org/en-US/docs/Web/API/Window/window>. * - browserify: http://browserify.org/ A browser-targetting bundler of * node.js deps. The runtime is a browser env, so can't use fs access, * etc. Browserify's build looks for `require(<single-string>)` imports * to bundle. For some imports it won't be able to handle, we "hide" * from browserify with `require('frobshizzle' + '')`. * - Other? Please open issues if things are broken. */ var runtimeEnv; if (typeof (process) !== 'undefined' && process.versions) { if (process.versions.nw) { runtimeEnv = 'nw'; } else if (process.versions.node) { runtimeEnv = 'node'; } } if (!runtimeEnv && typeof (window) !== 'undefined' && window.window === window) { runtimeEnv = 'browser'; } if (!runtimeEnv) { throw new Error('unknown runtime environment'); } var os, fs, dtrace; if (runtimeEnv === 'browser') { os = { hostname: function () { return window.location.host; } }; fs = {}; dtrace = null; } else { os = require('os'); fs = require('fs'); try { dtrace = require('dtrace-provider' + ''); } catch (e) { dtrace = null; } } var util = require('util'); var assert = require('assert'); var EventEmitter = require('events').EventEmitter; var stream = require('stream'); try { var safeJsonStringify = require('safe-json-stringify'); } catch (e) { safeJsonStringify = null; } if (process.env.BUNYAN_TEST_NO_SAFE_JSON_STRINGIFY) { safeJsonStringify = null; } // The 'mv' module is required for rotating-file stream support. try { var mv = require('mv' + ''); } catch (e) { mv = null; } try { var sourceMapSupport = require('source-map-support' + ''); } catch (_) { sourceMapSupport = null; } //---- Internal support stuff /** * A shallow copy of an object. Bunyan logging attempts to never cause * exceptions, so this function attempts to handle non-objects gracefully. */ function objCopy(obj) { if (obj == null) { // null or undefined return obj; } else if (Array.isArray(obj)) { return obj.slice(); } else if (typeof (obj) === 'object') { var copy = {}; Object.keys(obj).forEach(function (k) { copy[k] = obj[k]; }); return copy; } else { return obj; } } var format = util.format; if (!format) { // If node < 0.6, then use its `util.format`: // <https://github.com/joyent/node/blob/master/lib/util.js#L22>: var inspect = util.inspect; var formatRegExp = /%[sdj%]/g; format = function format(f) { if (typeof (f) !== 'string') { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function (x) { if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': return JSON.stringify(args[i++], safeCycles()); case '%%': return '%'; default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (x === null || typeof (x) !== 'object') { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; } /** * Gather some caller info 3 stack levels up. * See <http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi>. */ function getCaller3Info() { if (this === undefined) { // Cannot access caller info in 'strict' mode. return; } var obj = {}; var saveLimit = Error.stackTraceLimit; var savePrepare = Error.prepareStackTrace; Error.stackTraceLimit = 3; Error.prepareStackTrace = function (_, stack) { var caller = stack[2]; if (sourceMapSupport) { caller = sourceMapSupport.wrapCallSite(caller); } obj.file = caller.getFileName(); obj.line = caller.getLineNumber(); var func = caller.getFunctionName(); if (func) obj.func = func; }; Error.captureStackTrace(this, getCaller3Info); this.stack; Error.stackTraceLimit = saveLimit; Error.prepareStackTrace = savePrepare; return obj; } function _indent(s, indent) { if (!indent) indent = ' '; var lines = s.split(/\r?\n/g); return indent + lines.join('\n' + indent); } /** * Warn about an bunyan processing error. * * @param msg {String} Message with which to warn. * @param dedupKey {String} Optional. A short string key for this warning to * have its warning only printed once. */ function _warn(msg, dedupKey) { assert.ok(msg); if (dedupKey) { if (_warned[dedupKey]) { return; } _warned[dedupKey] = true; } process.stderr.write(msg + '\n'); } function _haveWarned(dedupKey) { return _warned[dedupKey]; } var _warned = {}; function ConsoleRawStream() {} ConsoleRawStream.prototype.write = function (rec) { if (rec.level < defaultLevels.INFO) { console.log(rec); } else if (rec.level < defaultLevels.WARN) { console.info(rec); } else if (rec.level < defaultLevels.ERROR) { console.warn(rec); } else { console.error(rec); } }; //---- Levels var defaultLevels = { TRACE: 10, DEBUG: 20, INFO: 30, WARN: 40, ERROR: 50, FATAL: 60 }; var levelFromName = { 'trace': defaultLevels.TRACE, 'debug': defaultLevels.DEBUG, 'info': defaultLevels.INFO, 'warn': defaultLevels.WARN, 'error': defaultLevels.ERROR, 'fatal': defaultLevels.FATAL }; var nameFromLevel = {}; Object.keys(levelFromName).forEach(function (name) { nameFromLevel[levelFromName[name]] = name; }); // Dtrace probes. var dtp = undefined; var probes = dtrace && {}; /** * Resolve a level number, name (upper or lowercase) to a level number value. * * @param nameOrNum {String|Number} A level name (case-insensitive) or positive * integer level. * @api public */ function resolveLevel(nameOrNum) { var level; var type = typeof (nameOrNum); if (type === 'string') { level = levelFromName[nameOrNum.toLowerCase()]; if (!level) { throw new Error(format('unknown level name: "%s"', nameOrNum)); } } else if (type !== 'number') { throw new TypeError(format('cannot resolve level: invalid arg (%s):', type, nameOrNum)); } else if (nameOrNum < 0 || Math.floor(nameOrNum) !== nameOrNum) { throw new TypeError(format('level is not a positive integer: %s', nameOrNum)); } else { level = nameOrNum; } return level; } function isWritable(obj) { if (obj instanceof stream.Writable) { return true; } return typeof (obj.write) === 'function'; } /** * Create a new logging level, and expose it. Name must be case-insensitive * unique, and is normalized to lowercase. Level must not exist, and is * normalized to the floor of its absolute value (e.g., -2.3 becomes 2, -32 * becomes 32). * * If you need DTrace support, create new levels *prior* to creating any * loggers (levels created after Loggers will work, they just won't trigger * DTrace). * * @api public */ function createLevel(name, level) { if (typeof name !== 'string' || !name.trim()) { throw new TypeError('name (string) is required'); } name = name.toLowerCase(); if (!name.match(/^[a-z_]+$/)) { throw new Error('level \'' + name + '\' is invalid'); } if (levelFromName[name]) { throw new Error('level \'' + name + '\' already exists'); } if (Logger.prototype[name]) { throw new Error('level \'' + name + '\' is invalid'); } if (typeof level !== 'number') { throw new TypeError('level (number) is required') } level = Math.floor(Math.abs(level)); if (nameFromLevel[level]) { throw new Error('level \'' + name + '\' would duplicate \'' + nameFromLevel[level] + '\''); } levelFromName[name] = level; nameFromLevel[level] = name; Logger.prototype[name] = mkLogEmitter(level); return Logger.prototype[name]; } //---- Logger class /** * Create a Logger instance. * * @param options {Object} See documentation for full details. At minimum * this must include a 'name' string key. Configuration keys: * - `streams`: specify the logger output streams. This is an array of * objects with these fields: * - `type`: The stream type. See README.md for full details. * Often this is implied by the other fields. Examples are * 'file', 'stream' and "raw". * - `level`: Defaults to 'info'. * - `path` or `stream`: The specify the file path or writeable * stream to which log records are written. E.g. * `stream: process.stdout`. * - `closeOnExit` (boolean): Optional. Default is true for a * 'file' stream when `path` is given, false otherwise. * See README.md for full details. * - `level`: set the level for a single output stream (cannot be used * with `streams`) * - `stream`: the output stream for a logger with just one, e.g. * `process.stdout` (cannot be used with `streams`) * - `serializers`: object mapping log record field names to * serializing functions. See README.md for details. * - `src`: Boolean (default false). Set true to enable 'src' automatic * field with log call source info. * All other keys are log record fields. * * An alternative *internal* call signature is used for creating a child: * new Logger(<parent logger>, <child options>[, <child opts are simple>]); * * @param _childSimple (Boolean) An assertion that the given `_childOptions` * (a) only add fields (no config) and (b) no serialization handling is * required for them. IOW, this is a fast path for frequent child * creation. */ function Logger(options, _childOptions, _childSimple) { xxx('Logger start:', options) if (!(this instanceof Logger)) { return new Logger(options, _childOptions); } // Input arg validation. var parent; if (_childOptions !== undefined) { parent = options; options = _childOptions; if (!(parent instanceof Logger)) { throw new TypeError( 'invalid Logger creation: do not pass a second arg'); } } if (!options) { throw new TypeError('options (object) is required'); } if (!parent) { if (!options.name) { throw new TypeError('options.name (string) is required'); } } else { if (options.name) { throw new TypeError( 'invalid options.name: child cannot set logger name'); } } if (options.stream && options.streams) { throw new TypeError('cannot mix "streams" and "stream" options'); } if (options.streams && !Array.isArray(options.streams)) { throw new TypeError('invalid options.streams: must be an array') } if (options.serializers && (typeof (options.serializers) !== 'object' || Array.isArray(options.serializers))) { throw new TypeError('invalid options.serializers: must be an object') } EventEmitter.call(this); // Fast path for simple child creation. if (parent && _childSimple) { // `_isSimpleChild` is a signal to stream close handling that this child // owns none of its streams. this._isSimpleChild = true; this._level = parent._level; this.streams = parent.streams; this.serializers = parent.serializers; this.src = parent.src; var fields = this.fields = {}; var parentFieldNames = Object.keys(parent.fields); for (var i = 0; i < parentFieldNames.length; i++) { var name = parentFieldNames[i]; fields[name] = parent.fields[name]; } var names = Object.keys(options); for (var i = 0; i < names.length; i++) { var name = names[i]; fields[name] = options[name]; } return; } // Start values. var self = this; if (parent) { this._level = parent._level; this.streams = []; for (var i = 0; i < parent.streams.length; i++) { var s = objCopy(parent.streams[i]); s.closeOnExit = false; // Don't own parent stream. this.streams.push(s); } this.serializers = objCopy(parent.serializers); this.src = parent.src; this.fields = objCopy(parent.fields); if (options.level) { this.level(options.level); } } else { this._level = Number.POSITIVE_INFINITY; this.streams = []; this.serializers = null; this.src = false; this.fields = {}; } if (!dtp && dtrace) { dtp = dtrace.createDTraceProvider('bunyan'); for (var level in levelFromName) { var probe; probes[levelFromName[level]] = probe = dtp.addProbe('log-' + level, 'char *'); // Explicitly add a reference to dtp to prevent it from being GC'd probe.dtp = dtp; } dtp.enable(); } // Handle *config* options (i.e. options that are not just plain data // for log records). if (options.stream) { self.addStream({ type: 'stream', stream: options.stream, closeOnExit: false, level: options.level }); } else if (options.streams) { options.streams.forEach(function (s) { self.addStream(s, options.level); }); } else if (parent && options.level) { this.level(options.level); } else if (!parent) { if (runtimeEnv === 'browser') { /* * In the browser we'll be emitting to console.log by default. * Any console.log worth its salt these days can nicely render * and introspect objects (e.g. the Firefox and Chrome console) * so let's emit the raw log record. Are there browsers for which * that breaks things? */ self.addStream({ type: 'raw', stream: new ConsoleRawStream(), closeOnExit: false, level: options.level }); } else { self.addStream({ type: 'stream', stream: process.stdout, closeOnExit: false, level: options.level }); } } if (options.serializers) { self.addSerializers(options.serializers); } if (options.src) { this.src = true; } xxx('Logger: ', self) // Fields. // These are the default fields for log records (minus the attributes // removed in this constructor). To allow storing raw log records // (unrendered), `this.fields` must never be mutated. Create a copy for // any changes. var fields = objCopy(options); delete fields.stream; delete fields.level; delete fields.streams; delete fields.serializers; delete fields.src; if (this.serializers) { this._applySerializers(fields); } if (!fields.hostname && !self.fields.hostname) { fields.hostname = os.hostname(); } if (!fields.pid) { fields.pid = process.pid; } Object.keys(fields).forEach(function (k) { self.fields[k] = fields[k]; }); } util.inherits(Logger, EventEmitter); /** * Add a stream * * @param stream {Object}. Object with these fields: * - `type`: The stream type. See README.md for full details. * Often this is implied by the other fields. Examples are * 'file', 'stream' and "raw". * - `path` or `stream`: The specify the file path or writeable * stream to which log records are written. E.g. * `stream: process.stdout`. * - `level`: Optional. Falls back to `defaultLevel`. * - `closeOnExit` (boolean): Optional. Default is true for a * 'file' stream when `path` is given, false otherwise. * See README.md for full details. * @param defaultLevel {Number|String} Optional. A level to use if * `stream.level` is not set. If neither is given, this defaults to INFO. */ Logger.prototype.addStream = function addStream(s, defaultLevel) { var self = this; if (defaultLevel === null || defaultLevel === undefined) { defaultLevel = defaultLevels.INFO; } s = objCopy(s); // Implicit 'type' from other args. if (!s.type) { if (s.stream) { s.type = 'stream'; } else if (s.path) { s.type = 'file' } } s.raw = (s.type === 'raw'); // PERF: Allow for faster check in `_emit`. if (s.level !== undefined) { s.level = resolveLevel(s.level); } else { s.level = resolveLevel(defaultLevel); } if (s.level < self._level) { self._level = s.level; } switch (s.type) { case 'stream': assert.ok(isWritable(s.stream), '"stream" stream is not writable: ' + util.inspect(s.stream)); if (!s.closeOnExit) { s.closeOnExit = false; } break; case 'file': if (s.reemitErrorEvents === undefined) { s.reemitErrorEvents = true; } if (!s.stream) { s.stream = fs.createWriteStream(s.path, {flags: 'a', encoding: 'utf8'}); if (!s.closeOnExit) { s.closeOnExit = true; } } else { if (!s.closeOnExit) { s.closeOnExit = false; } } break; case 'rotating-file': assert.ok(!s.stream, '"rotating-file" stream should not give a "stream"'); assert.ok(s.path); assert.ok(mv, '"rotating-file" stream type is not supported: ' + 'missing "mv" module'); s.stream = new RotatingFileStream(s); if (!s.closeOnExit) { s.closeOnExit = true; } break; case 'raw': if (!s.closeOnExit) { s.closeOnExit = false; } break; default: throw new TypeError('unknown stream type "' + s.type + '"'); } if (s.reemitErrorEvents && typeof (s.stream.on) === 'function') { // TODO: When we have `<logger>.close()`, it should remove event // listeners to not leak Logger instances. s.stream.on('error', function onStreamError(err) { self.emit('error', err, s); }); } self.streams.push(s); delete self.haveNonRawStreams; // reset } /** * Add serializers * * @param serializers {Object} Optional. Object mapping log record field names * to serializing functions. See README.md for details. */ Logger.prototype.addSerializers = function addSerializers(serializers) { var self = this; if (!self.serializers) { self.serializers = {}; } Object.keys(serializers).forEach(function (field) { var serializer = serializers[field]; if (typeof (serializer) !== 'function') { throw new TypeError(format( 'invalid serializer for "%s" field: must be a function', field)); } else { self.serializers[field] = serializer; } }); } /** * Create a child logger, typically to add a few log record fields. * * This can be useful when passing a logger to a sub-component, e.g. a * 'wuzzle' component of your service: * * var wuzzleLog = log.child({component: 'wuzzle'}) * var wuzzle = new Wuzzle({..., log: wuzzleLog}) * * Then log records from the wuzzle code will have the same structure as * the app log, *plus the component='wuzzle' field*. * * @param options {Object} Optional. Set of options to apply to the child. * All of the same options for a new Logger apply here. Notes: * - The parent's streams are inherited and cannot be removed in this * call. Any given `streams` are *added* to the set inherited from * the parent. * - The parent's serializers are inherited, though can effectively be * overwritten by using duplicate keys. * - Can use `level` to set the level of the streams inherited from * the parent. The level for the parent is NOT affected. * @param simple {Boolean} Optional. Set to true to assert that `options` * (a) only add fields (no config) and (b) no serialization handling is * required for them. IOW, this is a fast path for frequent child * creation. See 'tools/timechild.js' for numbers. */ Logger.prototype.child = function (options, simple) { return new (this.constructor)(this, options || {}, simple); } /** * A convenience method to reopen 'file' streams on a logger. This can be * useful with external log rotation utilities that move and re-open log files * (e.g. logrotate on Linux, logadm on SmartOS/Illumos). Those utilities * typically have rotation options to copy-and-truncate the log file, but * you may not want to use that. An alternative is to do this in your * application: * * var log = bunyan.createLogger(...); * ... * process.on('SIGUSR2', function () { * log.reopenFileStreams(); * }); * ... * * See <https://github.com/trentm/node-bunyan/issues/104>. */ Logger.prototype.reopenFileStreams = function () { var self = this; self.streams.forEach(function (s) { if (s.type === 'file') { if (s.stream) { // Not sure if typically would want this, or more immediate // `s.stream.destroy()`. s.stream.end(); s.stream.destroySoon(); delete s.stream; } s.stream = fs.createWriteStream(s.path, {flags: 'a', encoding: 'utf8'}); s.stream.on('error', function (err) { self.emit('error', err, s); }); } }); }; /* BEGIN JSSTYLED */ /** * Close this logger. * * This closes streams (that it owns, as per 'endOnClose' attributes on * streams), etc. Typically you **don't** need to bother calling this. Logger.prototype.close = function () { if (this._closed) { return; } if (!this._isSimpleChild) { self.streams.forEach(function (s) { if (s.endOnClose) { xxx('closing stream s:', s); s.stream.end(); s.endOnClose = false; } }); } this._closed = true; } */ /* END JSSTYLED */ /** * Get/set the level of all streams on this logger. * * Get Usage: * // Returns the current log level (lowest level of all its streams). * log.level() -> INFO * * Set Usage: * log.level(INFO) // set all streams to level INFO * log.level('info') // can use 'info' et al aliases */ Logger.prototype.level = function level(value) { if (value === undefined) { return this._level; } var newLevel = resolveLevel(value); var len = this.streams.length; for (var i = 0; i < len; i++) { this.streams[i].level = newLevel; } this._level = newLevel; } /** * Get/set the level of a particular stream on this logger. * * Get Usage: * // Returns an array of the levels of each stream. * log.levels() -> [TRACE, INFO] * * // Returns a level of the identified stream. * log.levels(0) -> TRACE // level of stream at index 0 * log.levels('foo') // level of stream with name 'foo' * * Set Usage: * log.levels(0, INFO) // set level of stream 0 to INFO * log.levels(0, 'info') // can use 'info' et al aliases * log.levels('foo', WARN) // set stream named 'foo' to WARN * * Stream names: When streams are defined, they can optionally be given * a name. For example, * log = new Logger({ * streams: [ * { * name: 'foo', * path: '/var/log/my-service/foo.log' * level: 'trace' * }, * ... * * @param name {String|Number} The stream index or name. * @param value {Number|String} The level value (INFO) or alias ('info'). * If not given, this is a 'get' operation. * @throws {Error} If there is no stream with the given name. */ Logger.prototype.levels = function levels(name, value) { if (name === undefined) { assert.equal(value, undefined); return this.streams.map( function (s) { return s.level }); } var stream; if (typeof (name) === 'number') { stream = this.streams[name]; if (stream === undefined) { throw new Error('invalid stream index: ' + name); } } else { var len = this.streams.length; for (var i = 0; i < len; i++) { var s = this.streams[i]; if (s.name === name) { stream = s; break; } } if (!stream) { throw new Error(format('no stream with name "%s"', name)); } } if (value === undefined) { return stream.level; } else { var newLevel = resolveLevel(value); stream.level = newLevel; if (newLevel < this._level) { this._level = newLevel; } } } /** * Apply registered serializers to the appropriate keys in the given fields. * * Pre-condition: This is only called if there is at least one serializer. * * @param fields (Object) The log record fields. * @param excludeFields (Object) Optional mapping of keys to `true` for * keys to NOT apply a serializer. */ Logger.prototype._applySerializers = function (fields, excludeFields) { var self = this; xxx('_applySerializers: excludeFields', excludeFields); // Check each serializer against these (presuming number of serializers // is typically less than number of fields). Object.keys(this.serializers).forEach(function (name) { if (fields[name] === undefined || (excludeFields && excludeFields[name])) { return; } xxx('_applySerializers; apply to "%s" key', name) try { fields[name] = self.serializers[name](fields[name]); } catch (err) { _warn(format('bunyan: ERROR: Exception thrown from the "%s" ' + 'Bunyan serializer. This should never happen. This is a bug' + 'in that serializer function.\n%s', name, err.stack || err)); fields[name] = format('(Error in Bunyan log "%s" serializer ' + 'broke field. See stderr for details.)', name); } }); } /** * Emit a log record. * * @param rec {log record} * @param noemit {Boolean} Optional. Set to true to skip emission * and just return the JSON string. */ Logger.prototype._emit = function (rec, noemit) { var i; // Lazily determine if this Logger has non-'raw' streams. If there are // any, then we need to stringify the log record. if (this.haveNonRawStreams === undefined) { this.haveNonRawStreams = false; for (i = 0; i < this.streams.length; i++) { if (!this.streams[i].raw) { this.haveNonRawStreams = true; break; } } } // Stringify the object. Attempt to warn/recover on error. var str; if (noemit || this.haveNonRawStreams) { try { str = JSON.stringify(rec, safeCycles()) + '\n'; } catch (e) { if (safeJsonStringify) { str = safeJsonStringify(rec) + '\n'; } else { var dedupKey = e.stack.split(/\n/g, 2).join('\n'); _warn('bunyan: ERROR: Exception in ' + '`JSON.stringify(rec)`. You can install the ' + '"safe-json-stringify" module to have Bunyan fallback ' + 'to safer stringification. Record:\n' + _indent(format('%s\n%s', util.inspect(rec), e.stack)), dedupKey); str = format('(Exception in JSON.stringify(rec): %j. ' + 'See stderr for details.)\n', e.message); } } } if (noemit) return str; var level = rec.level; for (i = 0; i < this.streams.length; i++) { var s = this.streams[i]; if (s.level <= level) { xxx('writing log rec "%s" to "%s" stream (%d <= %d): %j', rec.msg, s.type, s.level, level, rec); s.stream.write(s.raw ? rec : str); } }; return str; } /** * Build a record object suitable for emitting from the arguments * provided to the a log emitter. */ function mkRecord(log, minLevel, args) { var excludeFields, fields, msgArgs; if (args[0] instanceof Error) { // `log.<level>(err, ...)` fields = { // Use this Logger's err serializer, if defined. err: (log.serializers && log.serializers.err ? log.serializers.err(args[0]) : Logger.stdSerializers.err(args[0])) }; excludeFields = {err: true}; if (args.length === 1) { msgArgs = [fields.err.message]; } else { msgArgs = args.slice(1); } } else if (typeof (args[0]) !== 'object' || Array.isArray(args[0])) { // `log.<level>(msg, ...)` fields = null; msgArgs = args.slice(); } else if (Buffer.isBuffer(args[0])) { // `log.<level>(buf, ...)` // Almost certainly an error, show `inspect(buf)`. See bunyan // issue #35. fields = null; msgArgs = args.slice(); msgArgs[0] = util.inspect(msgArgs[0]); } else { // `log.<level>(fields, msg, ...)` fields = args[0]; if (fields && args.length === 1 && fields.err && fields.err instanceof Error) { msgArgs = [fields.err.message]; } else { msgArgs = args.slice(1); } } // Build up the record object. var rec = objCopy(log.fields); var level = rec.level = minLevel; var recFields = (fields ? objCopy(fields) : null); if (recFields) { if (log.serializers) { log._applySerializers(recFields, excludeFields); } Object.keys(recFields).forEach(function (k) { rec[k] = recFields[k]; }); } rec.msg = format.apply(log, msgArgs); if (!rec.time) { rec.time = (new Date()); } // Get call source info if (log.src && !rec.src) { rec.src = getCaller3Info() } rec.v = LOG_VERSION; return rec; }; /** * Build an array that dtrace-provider can use to fire a USDT probe. If we've * already built the appropriate string, we use it. Otherwise, build the * record object and stringify it. */ function mkProbeArgs(str, log, minLevel, msgArgs) { return [ str || log._emit(mkRecord(log, minLevel, msgArgs), true) ]; } /** * Build a log emitter function for level minLevel. I.e. this is the * creator of `log.info`, `log.error`, etc. */ function mkLogEmitter(minLevel) { return function () { var log = this; var str = null; var rec = null; if (!this._emit) { /* * Show this invalid Bunyan usage warning *once*. * * See <https://github.com/trentm/node-bunyan/issues/100> for * an example of how this can happen. */ var dedupKey = 'unbound'; if (!_haveWarned[dedupKey]) { var caller = getCaller3Info(); _warn(format('bunyan usage error: %s:%s: attempt to log ' + 'with an unbound log method: `this` is: %s', caller.file, caller.line, util.inspect(this)), dedupKey); } return; } else if (arguments.length === 0) { // `log.<level>()` return (this._level <= minLevel); } var msgArgs = new Array(arguments.length); for (var i = 0; i < msgArgs.length; ++i) { msgArgs[i] = arguments[i]; } if (this._level <= minLevel) { rec = mkRecord(log, minLevel, msgArgs); str = this._emit(rec); } if (probes && probes[minLevel]) { probes[minLevel].fire(mkProbeArgs, str, log, minLevel, msgArgs); } } } /** * The functions below log a record at a specific level. * * Usages: * log.<level>() -> boolean is-trace-enabled * log.<level>(<Error> err, [<string> msg, ...]) * log.<level>(<string> msg, ...) * log.<level>(<object> fields, <string> msg, ...) * * where <level> is the lowercase version of the log level. E.g.: * * log.info() * * @params fields {Object} Optional set of additional fields to log. * @params msg {String} Log message. This can be followed by additional * arguments that are handled like * [util.format](http://nodejs.org/docs/latest/api/all.html#util.format). */ Logger.prototype.trace = mkLogEmitter(defaultLevels.TRACE); Logger.prototype.debug = mkLogEmitter(defaultLevels.DEBUG); Logger.prototype.info = mkLogEmitter(defaultLevels.INFO); Logger.prototype.warn = mkLogEmitter(defaultLevels.WARN); Logger.prototype.error = mkLogEmitter(defaultLevels.ERROR); Logger.prototype.fatal = mkLogEmitter(defaultLevels.FATAL); //---- Standard serializers // A serializer is a function that serializes a JavaScript object to a // JSON representation for logging. There is a standard set of presumed // interesting objects in node.js-land. Logger.stdSerializers = {}; // Serialize an HTTP request. Logger.stdSerializers.req = function req(req) { if (!req || !req.connection) return req; return { method: req.method, url: req.url, headers: req.headers, remoteAddress: req.connection.remoteAddress, remotePort: req.connection.remotePort }; // Trailers: Skipping for speed. If you need trailers in your app, then // make a custom serializer. //if (Object.keys(trailers).length > 0) { // obj.trailers = req.trailers; //} }; // Serialize an HTTP response. Logger.stdSerializers.res = function res(res) { if (!res || !res.statusCode) return res; return { statusCode: res.statusCode, header: res._header } }; /* * This function dumps long stack traces for exceptions having a cause() * method. The error classes from * [verror](https://github.com/davepacheco/node-verror) and * [restify v2.0](https://github.com/mcavage/node-restify) are examples. * * Based on `dumpException` in * https://github.com/davepacheco/node-extsprintf/blob/master/lib/extsprintf.js */ function getFullErrorStack(ex) { var ret = ex.stack || ex.toString(); if (ex.cause && typeof (ex.cause) === 'function') { var cex = ex.cause(); if (cex) { ret += '\nCaused by: ' + getFullErrorStack(cex); } } return (ret); } // Serialize an Error object // (Core error properties are enumerable in node 0.4, not in 0.6). var errSerializer = Logger.stdSerializers.err = function err(err) { if (!err || !err.stack) return err; var obj = { message: err.message, name: err.name, stack: getFullErrorStack(err), code: err.code, signal: err.signal } return obj; }; // A JSON stringifier that handles cycles safely. // Usage: JSON.stringify(obj, safeCycles()) function safeCycles() { var seen = []; return function (key, val) { if (!val || typeof (val) !== 'object') { return val; } if (seen.indexOf(val) !== -1) { return '[Circular]'; } seen.push(val); return val; }; } var RotatingFileStream = null; if (mv) { RotatingFileStream = function RotatingFileStream(options) { this.path = options.path; this.count = (options.count == null ? 10 : options.count); assert.equal(typeof (this.count), 'number', format('rotating-file stream "count" is not a number: %j (%s) in %j', this.count, typeof (this.count), this)); assert.ok(this.count >= 0, format('rotating-file stream "count" is not >= 0: %j in %j', this.count, this)); // Parse `options.period`. if (options.period) { // <number><scope> where scope is: // h hours (at the start of the hour) // d days (at the start of the day, i.e. just after midnight) // w weeks (at the start of Sunday) // m months (on the first of the month) // y years (at the start of Jan 1st) // with special values 'hourly' (1h), 'daily' (1d), "weekly" (1w), // 'monthly' (1m) and 'yearly' (1y) var period = { 'hourly': '1h', 'daily': '1d', 'weekly': '1w', 'monthly': '1m', 'yearly': '1y' }[options.period] || options.period; var m = /^([1-9][0-9]*)([hdwmy]|ms)$/.exec(period); if (!m) { throw new Error(format('invalid period: "%s"', options.period)); } this.periodNum = Number(m[1]); this.periodScope = m[2]; } else { this.periodNum = 1; this.periodScope = 'd'; } var lastModified = null; try { var fileInfo = fs.statSync(this.path); lastModified = fileInfo.mtime.getTime(); } catch (err) { // file doesn't exist } var rotateAfterOpen = false; if (lastModified) { var lastRotTime = this._calcRotTime(0); if (lastModified < lastRotTime) { rotateAfterOpen = true; } } // TODO: template support for backup files // template: <path to which to rotate> // default is %P.%n // '/var/log/archive/foo.log' -> foo.log.%n // '/var/log/archive/foo.log.%n' // codes: // XXX support strftime codes (per node version of those) // or whatever module. Pick non-colliding for extra // codes // %P `path` base value // %n integer number of rotated log (1,2,3,...) // %d datetime in YYYY-MM-DD_HH-MM-SS // XXX what should default date format be? // prior art? Want to avoid ':' in // filenames (illegal on Windows for one). this.stream = fs.createWriteStream(this.path, {flags: 'a', encoding: 'utf8'}); this.rotQueue = []; this.rotating = false; if (rotateAfterOpen) { this._debug('rotateAfterOpen -> call rotate()'); this.rotate(); } else { this._setupNextRot(); } } util.inherits(RotatingFileStream, EventEmitter); RotatingFileStream.prototype._debug = function () { // Set this to `true` to add debug logging. if (false) { if (arguments.length === 0) { return true; } var args = Array.prototype.slice.call(arguments); args[0] = '[' + (new Date().toISOString()) + ', ' + this.path + '] ' + args[0]; console.log.apply(this, args); } else { return false; } }; RotatingFileStream.prototype._setupNextRot = function () { this.rotAt = this._calcRotTime(1); this._setRotationTimer(); } RotatingFileStream.prototype._setRotationTimer = function () { var self = this; var delay = this.rotAt - Date.now(); // Cap timeout to Node's max setTimeout, see // <https://github.com/joyent/node/issues/8656>. var TIMEOUT_MAX = 2147483647; // 2^31-1 if (delay > TIMEOUT_MAX) { delay = TIMEOUT_MAX; } this.timeout = setTimeout( function () { self._debug('_setRotationTimer timeout -> call rotate()'); self.rotate(); }, delay); if (typeof (this.timeout.unref) === 'function') { this.timeout.unref(); } } RotatingFileStream.prototype._calcRotTime = function _calcRotTime(periodOffset) { this._debug('_calcRotTime: %s%s', this.periodNum, this.periodScope); var d = new Date(); this._debug(' now local: %s', d); this._debug(' now utc: %s', d.toISOString()); var rotAt; switch (this.periodScope) { case 'ms': // Hidden millisecond period for debugging. if (this.rotAt) { rotAt = this.rotAt + this.periodNum * periodOffset; } else { rotAt = Date.now() + this.periodNum * periodOffset; } break; case 'h': if (this.rotAt) { rotAt = this.rotAt + this.periodNum * 60 * 60 * 1000 * periodOffset; } else { // First time: top of the next hour. rotAt = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours() + periodOffset); } break; case 'd': if (this.rotAt) { rotAt = this.rotAt + this.periodNum * 24 * 60 * 60 * 1000 * periodOffset; } else { // First time: start of tomorrow (i.e. at the coming midnight) UTC. rotAt = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() + periodOffset); } break; case 'w': // Currently, always on Sunday morning at 00:00:00 (UTC). if (this.rotAt) { rotAt = this.rotAt + this.periodNum * 7 * 24 * 60 * 60 * 1000 * periodOffset; } else { // First time: this coming Sunday. var dayOffset = (7 - d.getUTCDay()); if (periodOffset < 1) { dayOffset = -d.getUTCDay(); } if (periodOffset > 1 || periodOffset < -1) { dayOffset += 7 * periodOffset; } rotAt = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() + dayOffset); } break; case 'm': if (this.rotAt) { rotAt = Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + this.periodNum * periodOffset, 1); } else { // First time: the start of the next month. rotAt = Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + periodOffset, 1); } break; case 'y': if (this.rotAt) { rotAt = Date.UTC(d.getUTCFullYear() + this.periodNum * periodOffset, 0, 1); } else { // First time: the start of the next year. rotAt = Date.UTC(d.getUTCFullYear() + periodOffset, 0, 1); } break; default: assert.fail(format('invalid period scope: "%s"', this.periodScope)); } if (this._debug()) { this._debug(' **rotAt**: %s (utc: %s)', rotAt, new Date(rotAt).toUTCString()); var now = Date.now(); this._debug(' now: %s (%sms == %smin == %sh to go)', now, rotAt - now, (rotAt-now)/1000/60, (rotAt-now)/1000/60/60); } return rotAt; }; RotatingFileStream.prototype.rotate = function rotate() { // XXX What about shutdown? var self = this; // If rotation period is > ~25 days, we have to break into multiple // setTimeout's. See <https://github.com/joyent/node/issues/8656>. if (self.rotAt && self.rotAt > Date.now()) { return self._setRotationTimer(); } this._debug('rotate'); if (self.rotating) { throw new TypeError('cannot start a rotation when already rotating'); } self.rotating = true; self.stream.end(); // XXX can do moves sync after this? test at high rate function del() { var toDel = self.path + '.' + String(n - 1); if (n === 0) { toDel = self.path; } n -= 1; self._debug(' rm %s', toDel); fs.unlink(toDel, function (delErr) { //XXX handle err other than not exists moves(); }); } function moves() { if (self.count === 0 || n < 0) { return finish(); } var before = self.path; var after = self.path + '.' + String(n); if (n > 0) { before += '.' + String(n - 1); } n -= 1; fs.exists(before, function (exists) { if (!exists) { moves(); } else { self._debug(' mv %s %s', before, after); mv(before, after, function (mvErr) { if (mvErr) { self.emit('error', mvErr); finish(); // XXX finish here? } else { moves(); } }); } }) } function finish() { self._debug(' open %s', self.path); self.stream = fs.createWriteStream(self.path, {flags: 'a', encoding: 'utf8'}); var q = self.rotQueue, len = q.length; for (var i = 0; i < len; i++) { self.stream.write(q[i]); } self.rotQueue = []; self.rotating = false; self.emit('drain'); self._setupNextRot(); } var n = this.count; del(); }; RotatingFileStream.prototype.write = function write(s) { if (this.rotating) { this.rotQueue.push(s); return false; } else { return this.stream.write(s); } }; RotatingFileStream.prototype.end = function end(s) { this.stream.end(); }; RotatingFileStream.prototype.destroy = function destroy(s) { this.stream.destroy(); }; RotatingFileStream.prototype.destroySoon = function destroySoon(s) { this.stream.destroySoon(); }; } /* if (mv) */ /** * RingBuffer is a Writable Stream that just stores the last N records in * memory. * * @param options {Object}, with the following fields: * * - limit: number of records to keep in memory */ function RingBuffer(options) { this.limit = options && options.limit ? options.limit : 100; this.writable = true; this.records = []; EventEmitter.call(this); } util.inherits(RingBuffer, EventEmitter); RingBuffer.prototype.write = function (record) { if (!this.writable) throw (new Error('RingBuffer has been ended already')); this.records.push(record); if (this.records.length > this.limit) this.records.shift(); return (true); }; RingBuffer.prototype.end = function () { if (arguments.length > 0) this.write.apply(this, Array.prototype.slice.call(arguments)); this.writable = false; }; RingBuffer.prototype.destroy = function () { this.writable = false; this.emit('close'); }; RingBuffer.prototype.destroySoon = function () { this.destroy(); }; //---- Exports module.exports = Logger; module.exports.TRACE = defaultLevels.TRACE; module.exports.DEBUG = defaultLevels.DEBUG; module.exports.INFO = defaultLevels.INFO; module.exports.WARN = defaultLevels.WARN; module.exports.ERROR = defaultLevels.ERROR; module.exports.FATAL = defaultLevels.FATAL; module.exports.resolveLevel = resolveLevel; module.exports.levelFromName = levelFromName; module.exports.nameFromLevel = nameFromLevel; module.exports.createLevel = createLevel; module.exports.VERSION = VERSION; module.exports.LOG_VERSION = LOG_VERSION; module.exports.createLogger = function createLogger(options) { return new Logger(options); }; module.exports.RingBuffer = RingBuffer; module.exports.RotatingFileStream = RotatingFileStream; // Useful for custom `type == 'raw'` streams that may do JSON stringification // of log records themselves. Usage: // var str = JSON.stringify(rec, bunyan.safeCycles()); module.exports.safeCycles = safeCycles;
var classifier = require('..'); var Classifier = classifier.Classifier; var DataSet = classifier.DataSet; var Document = classifier.Document; var data = new DataSet(); var item1 = new Document('item1', ['a','b','c']); var item2 = new Document('item2', ['a','b','c']); var item3 = new Document('item3', ['a','d','e']); data.add('bad', [item1, item2, item3]); var itemA = new Document('itemA', ['c', 'd']); var itemB = new Document('itemB', ['e']); var itemC = new Document('itemC', ['b','d','e']); data.add('good', [itemA, itemB, itemC]); console.log('Training data set: ' + JSON.stringify(data, null, 4)); var options = { applyInverse: true }; var classifier1 = new Classifier(options); classifier1.train(data); console.log('Classifier trained.'); console.log(JSON.stringify(classifier1.probabilities, null, 4)); var testDoc = new Document('testDoc', ['b','d', 'e']); var result1 = classifier1.classify(testDoc); console.log(result1); var classifier2 = new Classifier(); classifier2.train(data); console.log('Classifier trained.'); console.log(JSON.stringify(classifier2.probabilities, null, 4)); var result2 = classifier2.classify(testDoc); console.log(result2);
/** * @author mrdoob / http://mrdoob.com/ */ THREE.ObjectLoader = function ( manager ) { this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; this.texturePath = ''; }; THREE.ObjectLoader.prototype = { constructor: THREE.ObjectLoader, load: function ( url, onLoad, onProgress, onError ) { if ( this.texturePath === '' ) { this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 ); } var scope = this; var loader = new THREE.XHRLoader( scope.manager ); loader.setCrossOrigin( this.crossOrigin ); loader.load( url, function ( text ) { scope.parse( JSON.parse( text ), onLoad ); }, onProgress, onError ); }, setTexturePath: function ( value ) { this.texturePath = value; }, setCrossOrigin: function ( value ) { this.crossOrigin = value; }, parse: function ( json, onLoad ) { var geometries = this.parseGeometries( json.geometries ); var images = this.parseImages( json.images, function () { if ( onLoad !== undefined ) onLoad( object ); } ); var textures = this.parseTextures( json.textures, images ); var materials = this.parseMaterials( json.materials, textures ); var object = this.parseObject( json.object, geometries, materials ); if ( json.images === undefined || json.images.length === 0 ) { if ( onLoad !== undefined ) onLoad( object ); } return object; }, parseGeometries: function ( json ) { var geometries = {}; if ( json !== undefined ) { var geometryLoader = new THREE.JSONLoader(); var bufferGeometryLoader = new THREE.BufferGeometryLoader(); for ( var i = 0, l = json.length; i < l; i ++ ) { var geometry; var data = json[ i ]; switch ( data.type ) { case 'PlaneGeometry': geometry = new THREE.PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments ); break; case 'BoxGeometry': case 'CubeGeometry': // backwards compatible geometry = new THREE.BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments ); break; case 'CircleGeometry': geometry = new THREE.CircleGeometry( data.radius, data.segments ); break; case 'CylinderGeometry': geometry = new THREE.CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded ); break; case 'SphereGeometry': geometry = new THREE.SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength ); break; case 'IcosahedronGeometry': geometry = new THREE.IcosahedronGeometry( data.radius, data.detail ); break; case 'TorusGeometry': geometry = new THREE.TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc ); break; case 'TorusKnotGeometry': geometry = new THREE.TorusKnotGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.p, data.q, data.heightScale ); break; case 'BufferGeometry': geometry = bufferGeometryLoader.parse( data.data ); break; case 'Geometry': geometry = geometryLoader.parse( data.data ).geometry; break; } geometry.uuid = data.uuid; if ( data.name !== undefined ) geometry.name = data.name; geometries[ data.uuid ] = geometry; } } return geometries; }, parseMaterials: function ( json, textures ) { var materials = {}; if ( json !== undefined ) { var getTexture = function ( name ) { if ( textures[ name ] === undefined ) { THREE.warn( 'THREE.ObjectLoader: Undefined texture', name ); } return textures[ name ]; }; var loader = new THREE.MaterialLoader(); for ( var i = 0, l = json.length; i < l; i ++ ) { var data = json[ i ]; var material = loader.parse( data ); material.uuid = data.uuid; if ( data.name !== undefined ) material.name = data.name; if ( data.map !== undefined ) { material.map = getTexture( data.map ); } if ( data.bumpMap !== undefined ) { material.bumpMap = getTexture( data.bumpMap ); if ( data.bumpScale ) { material.bumpScale = new THREE.Vector2( data.bumpScale, data.bumpScale ); } } if ( data.alphaMap !== undefined ) { material.alphaMap = getTexture( data.alphaMap ); } if ( data.envMap !== undefined ) { material.envMap = getTexture( data.envMap ); } if ( data.normalMap !== undefined ) { material.normalMap = getTexture( data.normalMap ); if ( data.normalScale ) { material.normalScale = new THREE.Vector2( data.normalScale, data.normalScale ); } } if ( data.lightMap !== undefined ) { material.lightMap = getTexture( data.lightMap ); } if ( data.specularMap !== undefined ) { material.specularMap = getTexture( data.specularMap ); } materials[ data.uuid ] = material; } } return materials; }, parseImages: function ( json, onLoad ) { var scope = this; var images = {}; if ( json !== undefined && json.length > 0 ) { var manager = new THREE.LoadingManager( onLoad ); var loader = new THREE.ImageLoader( manager ); loader.setCrossOrigin( this.crossOrigin ); var loadImage = function ( url ) { scope.manager.itemStart( url ); return loader.load( url, function () { scope.manager.itemEnd( url ); } ); }; for ( var i = 0, l = json.length; i < l; i ++ ) { var image = json[ i ]; images[ image.uuid ] = loadImage( scope.texturePath + image.url ); } } return images; }, parseTextures: function ( json, images ) { var textures = {}; if ( json !== undefined ) { for ( var i = 0, l = json.length; i < l; i ++ ) { var data = json[ i ]; if ( data.image === undefined ) { THREE.warn( 'THREE.ObjectLoader: No "image" speficied for', data.uuid ); } if ( images[ data.image ] === undefined ) { THREE.warn( 'THREE.ObjectLoader: Undefined image', data.image ); } var texture = new THREE.Texture( images[ data.image ] ); texture.needsUpdate = true; texture.uuid = data.uuid; if ( data.name !== undefined ) texture.name = data.name; if ( data.repeat !== undefined ) texture.repeat = new THREE.Vector2( data.repeat[ 0 ], data.repeat[ 1 ] ); if ( data.minFilter !== undefined ) texture.minFilter = THREE[ data.minFilter ]; if ( data.magFilter !== undefined ) texture.magFilter = THREE[ data.magFilter ]; if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy; if ( data.wrap instanceof Array ) { texture.wrapS = THREE[ data.wrap[ 0 ] ]; texture.wrapT = THREE[ data.wrap[ 1 ] ]; } textures[ data.uuid ] = texture; } } return textures; }, parseObject: function () { var matrix = new THREE.Matrix4(); return function ( data, geometries, materials ) { var object; var getGeometry = function ( name ) { if ( geometries[ name ] === undefined ) { THREE.warn( 'THREE.ObjectLoader: Undefined geometry', name ); } return geometries[ name ]; }; var getMaterial = function ( name ) { if ( materials[ name ] === undefined ) { THREE.warn( 'THREE.ObjectLoader: Undefined material', name ); } return materials[ name ]; }; switch ( data.type ) { case 'Scene': object = new THREE.Scene(); break; case 'PerspectiveCamera': object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); break; case 'OrthographicCamera': object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); break; case 'AmbientLight': object = new THREE.AmbientLight( data.color ); break; case 'DirectionalLight': object = new THREE.DirectionalLight( data.color, data.intensity ); break; case 'PointLight': object = new THREE.PointLight( data.color, data.intensity, data.distance, data.decay ); break; case 'SpotLight': object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent, data.decay ); break; case 'HemisphereLight': object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity ); break; case 'Mesh': object = new THREE.Mesh( getGeometry( data.geometry ), getMaterial( data.material ) ); break; case 'Line': object = new THREE.Line( getGeometry( data.geometry ), getMaterial( data.material ) ); break; case 'PointCloud': object = new THREE.PointCloud( getGeometry( data.geometry ), getMaterial( data.material ) ); break; case 'Sprite': object = new THREE.Sprite( getMaterial( data.material ) ); break; case 'Group': object = new THREE.Group(); break; default: object = new THREE.Object3D(); } object.uuid = data.uuid; if ( data.name !== undefined ) object.name = data.name; if ( data.matrix !== undefined ) { matrix.fromArray( data.matrix ); matrix.decompose( object.position, object.quaternion, object.scale ); } else { if ( data.position !== undefined ) object.position.fromArray( data.position ); if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation ); if ( data.scale !== undefined ) object.scale.fromArray( data.scale ); } if ( data.visible !== undefined ) object.visible = data.visible; if ( data.userData !== undefined ) object.userData = data.userData; if ( data.children !== undefined ) { for ( var child in data.children ) { object.add( this.parseObject( data.children[ child ], geometries, materials ) ); } } return object; } }() };
'use strict'; const fs = require('fs'); const express = require('express'); const request = require('supertest'); const webpackIsomorphicDevMiddleware = require('../'); const createCompiler = require('./util/createCompiler'); const normalizeHtmlError = require('./util/normalizeHtmlError'); const configClientBasic = require('./configs/client-basic'); const configServerBasic = require('./configs/server-basic'); const configClientSyntaxError = require('./configs/client-syntax-error'); const configServerRuntimeError = require('./configs/server-runtime-error'); afterEach(() => createCompiler.teardown()); it('should wait for a successful compilation and call next()', () => { const app = express(); const compiler = createCompiler(configClientBasic, configServerBasic); app.use(webpackIsomorphicDevMiddleware(compiler, { report: false, })); return request(app) .get('/client.js') .expect(200) .expect(/Hello!/); }); it('should wait for a failed compilation and render the webpack stats', () => { const app = express(); const compiler = createCompiler(configClientSyntaxError, configServerBasic); app.use(webpackIsomorphicDevMiddleware(compiler, { report: false, })); return request(app) .get('/client.js') .expect(500) .expect((res) => { expect(normalizeHtmlError(res.text)).toMatchSnapshot(); }); }); it('should render error if an error occurred while reading the server file', () => { const app = express(); const compiler = createCompiler(configClientBasic, configServerRuntimeError); app.use(webpackIsomorphicDevMiddleware(compiler, { report: false, })); compiler.server.webpackCompiler.outputFileSystem.readFile = (...args) => { args[args.length - 1](new Error('Failed to read file')); }; return request(app) .get('/client.js') .expect(500) .expect((res) => { expect(normalizeHtmlError(res.text)).toMatchSnapshot(); }); }); it('should render error if the server file has a runtime error', () => { const app = express(); const compiler = createCompiler(configClientBasic, configServerRuntimeError); app.use(webpackIsomorphicDevMiddleware(compiler, { report: false, })); return request(app) .get('/client.js') .expect(500) .expect((res) => { expect(normalizeHtmlError(res.text)).toMatchSnapshot(); }); }); it('should call next(err) if not a middleware error', () => { const app = express(); const compiler = createCompiler(configClientBasic, configServerBasic); const contrivedError = new Error('foo'); app.use((req, res, next) => { next(contrivedError); }); app.use(webpackIsomorphicDevMiddleware(compiler, { report: false, })); app.use((err, req, res, next) => { // eslint-disable-line handle-callback-err, no-unused-vars expect(err).toBe(contrivedError); res.send(`Captured contrived error: ${err.message}`); }); return request(app) .get('/client.js') .expect(200) .expect('Captured contrived error: foo'); }); it('should set res.locals.isomorphicCompilation', async () => { const app = express(); const compiler = createCompiler(configClientBasic, configServerBasic); let isomorphicCompilation; let exports; app.use(webpackIsomorphicDevMiddleware(compiler, { report: false, })); app.get('*', (req, res) => { exports = res.locals.isomorphic.exports; isomorphicCompilation = res.locals.isomorphic.compilation; res.send('Yes it works!'); }); await request(app) .get('/') .expect(200) .expect('Yes it works!'); expect(isomorphicCompilation).toBeDefined(); expect(isomorphicCompilation).toHaveProperty('clientStats'); expect(isomorphicCompilation).toHaveProperty('serverStats'); expect(exports).toBeDefined(); expect(exports).toHaveProperty('render'); }); it('should cache the res.locals.isomorphicCompilation', async () => { const app = express(); const compiler = createCompiler(configClientBasic, configServerBasic); let isomorphicCompilation; app.use(webpackIsomorphicDevMiddleware(compiler, { report: false, })); app.get('*', (req, res) => { if (!isomorphicCompilation) { isomorphicCompilation = res.locals.isomorphicCompilation; } else { expect(res.locals.isomorphicCompilation).toBe(isomorphicCompilation); } res.send('Yes it works!'); }); const spy = jest.spyOn(compiler.server.webpackCompiler.outputFileSystem, 'readFile'); await request(app) .get('/') .expect(200) .expect('Yes it works!'); await request(app) .get('/') .expect(200) .expect('Yes it works!'); expect(spy.mock.calls).toHaveLength(1); }); it('should not re-require the server file if it has a runtime error', async () => { const app = express(); const compiler = createCompiler(configClientBasic, configServerRuntimeError); app.use(webpackIsomorphicDevMiddleware(compiler, { report: false, })); const spy = jest.spyOn(compiler.server.webpackCompiler.outputFileSystem, 'readFile'); let res = await request(app) .get('/') .expect(500); expect(normalizeHtmlError(res.text)).toMatchSnapshot(); res = await request(app) .get('/') .expect(500); expect(normalizeHtmlError(res.text)).toMatchSnapshot(); expect(spy.mock.calls).toHaveLength(1); expect(spy.mock.calls[0][0]).toMatch(/server\.js$/); }); it('should not use in-memory filesystem if options.memoryFs is false', async () => { const app = express(); const compiler = createCompiler(configClientBasic, configServerBasic); app.use(webpackIsomorphicDevMiddleware(compiler, { memoryFs: false, report: false, })); await request(app) .get('/client.js') .expect(200); expect(fs.existsSync(`${compiler.client.webpackConfig.output.path}/client.js`)).toBe(true); expect(fs.existsSync(`${compiler.server.webpackConfig.output.path}/server.js`)).toBe(true); }); it('should watch() with the specified options.watchDelay', (next) => { const compiler = createCompiler(configClientBasic, configServerBasic); const now = Date.now(); webpackIsomorphicDevMiddleware(compiler, { watchDelay: 100 }); compiler.watch = () => { expect(Date.now() - now).toBeGreaterThanOrEqual(100); next(); }; }); it('should set headers as specified in options.headers', () => { const app = express(); const compiler = createCompiler(configClientBasic, configServerBasic); app.use(webpackIsomorphicDevMiddleware(compiler, { report: false, headers: { 'X-FOO': 'bar' }, })); return request(app) .get('/client.js') .expect(200) .expect('X-FOO', 'bar') .expect('Cache-Control', 'max-age=0, must-revalidate') .expect(/Hello!/); }); it('should allow removing the default Cache-Control header via options.headers', () => { const app = express(); const compiler = createCompiler(configClientBasic, configServerBasic); app.use(webpackIsomorphicDevMiddleware(compiler, { report: false, headers: { 'Cache-Control': null }, })); return request(app) .get('/client.js') .expect(200) .expect((res) => { expect(res.headers).not.toHaveProperty('cache-control'); }) .expect(/Hello!/); });
/* * * Settings actions * */ import { DEFAULT_ACTION, } from './constants'; export function defaultAction() { return { type: DEFAULT_ACTION, }; }
export default { set_user: ({ commit, state }, { user }) => { return state.user ? '' : state.user } }
/** * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/> * Build: `lodash modularize underscore exports="amd" -o ./underscore/` * Copyright 2012-2014 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.6.0 <http://underscorejs.org/LICENSE> * Copyright 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <http://lodash.com/license> */ define(['../objects/isFunction', '../arrays/slice'], function(isFunction, slice) { /** Used as a safe reference for `undefined` in pre ES5 environments */ var undefined; /** Used as the TypeError message for "Functions" methods */ var funcErrorText = 'Expected a function'; /** * Executes the `func` function after `wait` milliseconds. Additional arguments * will be provided to `func` when it is invoked. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay execution. * @param {...*} [args] The arguments to invoke the function with. * @returns {number} Returns the timer id. * @example * * _.delay(function(text) { console.log(text); }, 1000, 'later'); * // => logs 'later' after one second */ function delay(func, wait) { if (!isFunction(func)) { throw new TypeError(funcErrorText); } var args = slice(arguments, 2); return setTimeout(function() { func.apply(undefined, args); }, wait); } return delay; });
$(document).ready(function(){ uxControl.hideAll(); $("#bench-button").on("click", uxControl.showBench); $("#deadlift-button").on("click", uxControl.showDeadlift); $("#squat-button").on("click", uxControl.showSquat); }); var uxControl = { hideAll : function(){ $("#squat-logs").hide(); $("#deadlift-logs").hide(); $("#bench-press-logs").hide(); $("#button-div").hide(); }, showBench : function(){ $("#bench-press-logs").show(); $("#squat-logs").hide(); $("#deadlift-logs").hide(); }, showDeadlift : function(){ $("#deadlift-logs").show(); $("#bench-press-logs").hide(); $("#squat-logs").hide(); }, showSquat : function(){ $("#squat-logs").show(); $("#deadlift-logs").hide(); $("#bench-press-logs").hide(); } }; //end of object uxControl
var express = require('express'), config = require('./config/config'), glob = require('glob'), mongoose = require('mongoose') app = express() http = require('http').Server(app), io = require('socket.io')(http); mongoose.connect(config.db); var db = mongoose.connection; db.on('error', function () { throw new Error('unable to connect to database at ' + config.db); }); var models = glob.sync(config.root + '/app/models/*.js'); models.forEach(function (model) { require(model); }); require('./config/express')(app, config); http.listen(config.port, function () { console.log('Express server listening on port ' + config.port); }); var numberClients= 0; io.on('connection', function(socket){ console.log("A new socket.io client has arrived"); // chaque fois qu'un nouveau client se connecte on incrémente numberClients +=1; socket.emit('userNumber', numberClients); // // chaque fois qu'on reçois new on le rediffuse à tout le monde socket.on('news', function(data){ socket.emit('news', data); }); // lorsque l'évément btnYes est émit, il faut diffuser au niveau du server socket.on('btnYes', function(data){ console.log(data); io.emit('btnYes', data); }); // lorsque l'évément btnNo est émit, il faut diffuser au niveau du server, pour que tout les client se mettent à jour socket.on('btnNo', function(data){ console.log(data); io.emit('btnNo', data); }); // lorsque l'évément btnNo est émit, il faut diffuser au niveau du server, pour que tout les client se mettent à jour socket.on('dKnow', function(data){ console.log(data); io.emit('dKnow', data); }); });
'use strict'; /** * Created by Adrian on 20-Mar-16. */ module.exports = (IFace) => { return class SanitizeANY extends IFace { static code() { return "ANY" }; static publicName() { return "Any"; } /* Validate if the input is present. * OPTIONS: * max - the maximum JSON length. Defaults to 10000 * */ validate(d, opt) { if (typeof d === 'undefined') return false; if (!opt.max) opt.max = 10000; if (typeof d === 'object' && d) { try { let r = JSON.stringify(d); if (r.length > opt.max) throw 1; return { value: JSON.parse(r) }; } catch (e) { return false; } } if (typeof d === 'string' && d.length < opt.max) { return { value: d } } else if (typeof d === 'number' || typeof d === 'boolean') { return { value: d }; } return false; } } };
import React from 'react'; import PropTypes from 'prop-types'; import { classes } from '../Table.st.css'; /** TableSubtoolbar */ export const TableSubToolbar = ({ dataHook, children }) => { return ( <div className={classes.tableSubToolbar} data-hook={dataHook}> {children} </div> ); }; TableSubToolbar.displayName = 'Table.SubToolbar'; TableSubToolbar.propTypes = { /** Applied as data-hook HTML attribute that can be used in the tests */ dataHook: PropTypes.string, /** Any element to be rendered inside */ children: PropTypes.node, };
export { default } from 'ember-flexberry-designer/enums/s-t-o-r-m-c-a-s-e-repository-access-modifier';
Worm = Class.create(Enemy, // We extend the Sprite class { initialize: function(x, y) { //initialization this.super_initialize("Worm", x, y, 50, 50); //this.image = game.assets['images/worm_head_glow.png']; this.image = game.assets['images/worm_head_glow.png']; this.makeBody = 4; this.x = x; this.y = y; this.worm = 1; this.bodyLeft = 0; this.scoreValue = 10; this.health = 1; this.speed = 5; this.currentPathController = "followPlayer"; this.moveChoices = [ //[ "moveRandom", 45 ], [ "followPlayer", 70 ] ]; this.moveChoicesTotalWeight = 0; for (var i = 0; i < this.moveChoices.length; i++) this.moveChoicesTotalWeight += this.moveChoices[i][1]; }, onenterframe: function() { if (this.makeBody == 4) { this.makeBody--; enemyGroup.addChild(new WormBody(this.x, this.y, this, this.makeBody, this, 4.8)); this.bodyLeft++; } if (!this.super_onenterframe()) return; // Every 30 steps, choose random direction or follow if (!(this.age % 30 === 0)) return this[this.currentPathController](); var random = Math.floor(Math.random() * this.moveChoicesTotalWeight); var i, cumulativeWeight = 0; for (i = 0; i < this.moveChoices.length; i++) { cumulativeWeight += this.moveChoices[i][1]; if (random < cumulativeWeight) { this.currentPathController = this.moveChoices[i][0]; break; } } return this[this.currentPathController](); }, moveRandom: function() { if (this.age % 30 === 0) { this.randomX = Math.floor(Math.random() * (game.width - (this.width / 2))); this.randomY = Math.floor(Math.random() * (game.height - (this.height / 2))); this.randomAngle = Math.atan2(this.randomX, this.randomY); } this.randomXSpeed = this.speed * Math.cos(this.randomAngle); this.randomYSpeed = this.speed * Math.sin(this.randomAngle); if (this.randomXSpeed === 0 && this.randomYSpeed === 0) this.randomXSpeed = 1; this.x += this.randomXSpeed; this.y += this.randomYSpeed; if (this.y < 0) this.y = 0; if (this.x < 0) this.x = 0; if (this.x + this.width > game.width) this.x = game.width - this.width; if (this.y + this.height > game.height) this.y = game.height - this.height; } }); WormBody = Class.create(Enemy, { initialize: function(x, y, head, makeMore, topHead, speed) { this.super_initialize("WormBody", x, y, 33, 33); this.image = game.assets['images/worm_tail_piece_glow.png']; this.x = x - 20; this.y = y - 20; this.head = head; this.speed = speed; this.head = head; this.makeBody = makeMore; this.topMake = makeMore; this.topHead = topHead; this.wormBody = 1; this.currentPathController = "followWorm"; }, onenterframe: function() { if (!this.super_onenterframe()) return; sfxEnemy = game.assets['sounds/deadEnemy.wav']; // Collision detection on bomb, this is seperate from the one in the enemy class // because otherwise there's a bug, feel free to play around with it though for (i = bombGroup.childNodes.length - 1; i >= 0; i--) { bomb = bombGroup.childNodes[i]; if (this.intersect(bomb)) { scene.incrementScore(this.scoreValue); enemyGroup.removeChild(this); sfxEnemy.play(); //Particle effect on death for (var i = 0; i < 10; i++) game.currentScene.addChild(new ParticleBlast(4, 10, this.x, this.y, 90, 91, 'particle0')); // All done, return break; } } if (this.makeBody == this.topMake && this.topMake != 0) { this.makeBody--; enemyGroup.addChild(new WormBody(this.x, this.y, this, this.makeBody, this.topHead, this.speed-=0.1)); this.topHead.bodyLeft++; } return this[this.currentPathController](this.head); } });
(function(){ console.log('BOLA'); }());
const security = require('@tryghost/security'); class Invites { constructor({settingsCache, i18n, logging, mailService, urlUtils}) { this.settingsCache = settingsCache; this.i18n = i18n; this.logging = logging; this.mailService = mailService; this.urlUtils = urlUtils; } add({api, InviteModel, invites, options, user}) { let invite; let emailData; return InviteModel.findOne({email: invites[0].email}, options) .then((existingInvite) => { if (!existingInvite) { return; } return existingInvite.destroy(options); }) .then(() => { return InviteModel.add(invites[0], options); }) .then((createdInvite) => { invite = createdInvite; const adminUrl = this.urlUtils.urlFor('admin', true); emailData = { blogName: this.settingsCache.get('title'), invitedByName: user.name, invitedByEmail: user.email, resetLink: this.urlUtils.urlJoin(adminUrl, 'signup', security.url.encodeBase64(invite.get('token')), '/'), recipientEmail: invite.get('email') }; return this.mailService.utils.generateContent({data: emailData, template: 'invite-user'}); }) .then((emailContent) => { const payload = { mail: [{ message: { to: invite.get('email'), subject: this.i18n.t('common.api.users.mail.invitedByName', { invitedByName: emailData.invitedByName, blogName: emailData.blogName }), html: emailContent.html, text: emailContent.text }, options: {} }] }; return api.mail.send(payload, {context: {internal: true}}); }) .then(() => { return InviteModel.edit({ status: 'sent' }, Object.assign({id: invite.id}, options)); }) .then((editedInvite) => { return editedInvite; }) .catch((err) => { if (err && err.errorType === 'EmailError') { const errorMessage = this.i18n.t('errors.api.invites.errorSendingEmail.error', { message: err.message }); const helpText = this.i18n.t('errors.api.invites.errorSendingEmail.help'); err.message = `${errorMessage} ${helpText}`; this.logging.warn(err.message); } return Promise.reject(err); }); } } module.exports = Invites;
'use strict'; export default { baseUrl: { public: 'https://api.zaif.jp/api/1', private: 'https://api.zaif.jp/tapi', stream: 'ws://api.zaif.jp:8888/stream' } };
'use strict'; var path = require('path'); var assert = require('yeoman-generator').assert; var helpers = require('yeoman-generator').test; var os = require('os'); describe('simple-react-browserify:app', function() { before(function(done) { helpers.run(path.join(__dirname, '../app')) .inDir(path.join(os.tmpdir(), './temp-test')) .withOptions({ 'skip-install': true }) .withPrompt({ someOption: true }) .on('end', done); }); it('creates files', function() { assert.file([ '.editorconfig', '.jshintrc', 'src/package.json', 'src/gulpfile.js', 'src/App/app.js', 'src/App/index.html', 'src/App/Components/Menu.js', 'src/App/Components/MenuItem.js', 'src/App/Core/App.js', 'src/App/Core/Layout.js', 'src/App/Core/Routes.js', 'src/App/Views/Dashboard.js', 'src/App/Views/Home.js' ]); }); });
import React from 'react' import PropTypes from 'prop-types' import { Button } from 'antd' import CountUp from 'react-countup' import { color } from 'utils' import styles from './user.less' const countUpProps = { start: 0, duration: 2.75, useEasing: true, useGrouping: true, separator: ',', } function User ({ avatar, name, email, sales, sold }) { return (<div className={styles.user}> <div className={styles.header}> <div className={styles.headerinner}> <div className={styles.avatar} style={{ backgroundImage: `url(${avatar})` }} /> <h5 className={styles.name}>{name}</h5> <p>{email}</p> </div> </div> <div className={styles.number}> <div className={styles.item}> <p>今日营业额</p> <p style={{ color: color.green }}><CountUp end={sales} prefix="¥" {...countUpProps} /></p> </div> <div className={styles.item}> <p>销售数量</p> <p style={{ color: color.blue }}><CountUp end={sold} {...countUpProps} /></p> </div> </div> <div className={styles.footer}> <Button type="ghost" size="large">查看详情</Button> </div> </div>) } User.propTypes = { avatar: PropTypes.string, name: PropTypes.string, email: PropTypes.string, sales: PropTypes.number, sold: PropTypes.number, } export default User
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { withStyles } from '@material-ui/core/styles'; import Card from '@material-ui/core/Card'; import CardActions from '@material-ui/core/CardActions'; import CardContent from '@material-ui/core/CardContent'; import Typography from '@material-ui/core/Typography'; import List from '@material-ui/core/List'; import ListItem from '@material-ui/core/ListItem'; import ListItemText from '@material-ui/core/ListItemText'; import Collapse from '@material-ui/core/Collapse'; import Button from '@material-ui/core/Button'; import ExpandLess from '@material-ui/icons/ExpandLess'; import ExpandMore from '@material-ui/icons/ExpandMore'; import PlaylistPlay from '@material-ui/icons/PlaylistPlay'; import AddCircle from '@material-ui/icons/AddCircle'; import RemoveCircle from '@material-ui/icons/RemoveCircle'; import Edit from '@material-ui/icons/Edit'; import Cancel from '@material-ui/icons/Cancel'; import withWidth from '@material-ui/core/withWidth'; import Egg from './egg.js' import RequestButton from './RequestButton.js'; import EditFavoriteDialog from './EditFavoriteDialog.js'; import AddFavoritesCollectionDialog from './AddFavoritesCollectionDialog.js'; import RemoveFavoritesCollectionDialog from './RemoveFavoritesCollectionDialog.js'; import AlertDialog from './AlertDialog.js'; import ws_client from './WebSocketClient.js'; const styles = theme => ({ thumbnail: { width: "5%" }, leftIcon: { marginRight: theme.spacing.unit, }, iconSmall: { fontSize: 20, }, card: { alignItems: 'center', }, details: { display: 'flex', flexDirection: 'column', alignItems: 'center', }, content: { flex: '1 0 auto', alignItems: 'center', }, }); class Favorites extends Component { constructor(props){ super(props); this.props = props; this.state = { favorites: [], playlistMode: false, showEditDialog: false, selectedFavorite: null, selectedParent: null, showAddCollectionDialog: false, showRemoveCollectionDialog: false, }; this.loadFavorites(true); window.dirty_favorites = false; new Egg(atob("bGVmdCxtLHUscyxpLGM="), ()=> { this.setState({ playlistMode: !this.state.playlistMode }) }).listen() setInterval(()=>this.watchDog(), 100); } watchDog(){ if(window.dirty_favorites){ console.log("dirty"); let storage = JSON.parse(localStorage.getItem("favorites")); this.setState({ favorites: []}) this.setState({ favorites: storage }) this.forceUpdate(); window.dirty_favorites = false; } } loadFavorites = (init)=>{ var favorites = localStorage.getItem("favorites") if(favorites !== null && localStorage.getItem("_v2_favorites") === null){ favorites = null; localStorage.setItem("_v2_favorites", "true") } if(favorites === null){ favorites = [ { name: "My Favorites", key: 0, children: [], open: true } ] } else{ favorites = JSON.parse(favorites); } if(init){ this.state = { "favorites": favorites }; } else{ this.setState = ({ "favorites": favorites }); } localStorage.setItem("dirty_favorites", "false") this.saveFavorites(favorites); } saveFavorites = (favorites)=>{ if(favorites === undefined){ localStorage.setItem("favorites", JSON.stringify(this.state.favorites)); } else{ localStorage.setItem("favorites", JSON.stringify(favorites)); } } handleToggle(parent_name){ for(var i=0; i<this.state.favorites.length; i++){ if(this.state.favorites[i].name === parent_name){ this.state.favorites[i].open = !this.state.favorites[i].open; this.setState(this.state.favorites); this.saveFavorites(); } } } handleOpenEditFavorite = (selectedFavorite, selectedParent) => () => { this.setState({ selectedFavorite: selectedFavorite, selectedParent: selectedParent, showEditDialog: true }); } handleCloseEditFavorite = favorites => { this.setState({ favorites: favorites, showEditDialog: false }) this.saveFavorites(favorites); } handleOpenAddCollection = () => { this.setState({ showAddCollectionDialog: true }) } handleCloseAddCollection = favorites => { this.setState({ showAddCollectionDialog: false, favorites: favorites }) this.saveFavorites(favorites); } handleOpenRemoveCollection = () => { this.setState({ showRemoveCollectionDialog: true }) } handleCloseRemoveCollection = favorites => { this.setState({ showRemoveCollectionDialog: false, favorites: favorites }) this.saveFavorites(favorites); } handleDelete = (child, parent) => () => { var favs = this.state.favorites for(var i=0; i<parent.children.length; i++){ if(parent.children[i].id === child.id){ parent.children.splice(i, 1) break; } } this.setState({ favorites: favs }) this.saveFavorites(favs); } handleQueuePlaylist = (collection_name) => () => { var collection = null; for(var i=0; i<this.state.favorites.length; i++){ if(this.state.favorites[i].name === collection_name){ collection = this.state.favorites[i]; break; } } if(collection === null){ return; } for(var i=0; i<collection.children.length; i++){ ws_client.send({ type: "command", key: "add.queue", details: collection.children[i] }, true); } } detectSmallScreen = () => { return this.props.width === "sm" || this.props.width === "xs" } render(){ const { classes, theme } = this.props; return ( <Card className={classes.card}> <CardContent className={classes.content}> <Typography variant="headline" component="h2"> Favorites </Typography> <List className={classes.flex} component="nav"> {this.state.favorites.map((parent,idx)=>{ return ( <div className={classes.flex}> <ListItem spacing={5} key={parent.key} > <ListItemText primary={parent.name} /> {this.state.playlistMode && <Button onClick={this.handleQueuePlaylist(parent.name)}> <PlaylistPlay /> </Button> } <Button onClick={()=>this.handleToggle(parent.name)}> {parent.open ? <ExpandLess /> : <ExpandMore />} </Button> </ListItem> <Collapse in={parent.open} timeout="auto" unmountOnExit> <List> { parent.children.length === 0 && <ListItem> <Typography component="p"> No saved favorites! </Typography> </ListItem> } {parent.children.map(child=>{ return ( <div> <ListItem> { !this.detectSmallScreen() && <img src={child.thumbnail.url} className={classes.thumbnail}/> } <ListItemText primary={child.title} /> { !this.detectSmallScreen() && <RequestButton song={child} /> } { !this.detectSmallScreen() && <Button onClick={this.handleOpenEditFavorite(child, parent)}> <Edit /> </Button> } { !this.detectSmallScreen() && <AlertDialog title="Confirm Delete" message="Are you sure you wish to delete this from your favorites?" onOk={this.handleDelete(child, parent)} control={ <Button> <Cancel /> </Button> } /> } </ListItem> { this.detectSmallScreen() && <RequestButton song={child} /> } { this.detectSmallScreen() && <Button onClick={this.handleOpenEditFavorite(child, parent)}> <Edit /> </Button> } { this.detectSmallScreen() && <div style={{"display": "inline-block"}}> <AlertDialog title="Confirm Delete" message="Are you sure you wish to delete this from your favorites?" onOk={this.handleDelete(child, parent)} control={ <Button> <Cancel /> </Button> } /> </div> } </div> ) })} </List> </Collapse> </div> ) })} </List> <EditFavoriteDialog favorites={this.state.favorites} favorite={this.state.selectedFavorite} parent={this.state.selectedParent} open={this.state.showEditDialog} onClose={this.handleCloseEditFavorite} /> <AddFavoritesCollectionDialog favorites={this.state.favorites} open={this.state.showAddCollectionDialog} onClose={this.handleCloseAddCollection}/> <RemoveFavoritesCollectionDialog favorites={this.state.favorites} open={this.state.showRemoveCollectionDialog} onClose={this.handleCloseRemoveCollection}/> <CardActions> <Button onClick={this.handleOpenAddCollection}> <AddCircle className={classNames(classes.leftIcon, classes.iconSmall)}/> Add Collection </Button> <Button onClick={this.handleOpenRemoveCollection}> <RemoveCircle className={classNames(classes.leftIcon, classes.iconSmall)}/> Remove Collection </Button> </CardActions> </CardContent> </Card> ) } } Favorites.propTypes = { classes: PropTypes.object.isRequired, theme: PropTypes.object.isRequired, }; export default withWidth()(withStyles(styles)(Favorites));
// Build configuration, defining source and destination // directories and patterns // // srcDir is the source directory var srcDir = './src', destDir = './carpool_app/static', bowerDir = './bower_components'; // src holds the values of source folders var src = { root: srcDir, vendorRoot: bowerDir, css: srcDir + '/css/**/*.scss', js: srcDir + '/**/*.js', img: srcDir + '/img/**/*', fonts: srcDir + '/fonts/**/*', html: srcDir + '/**/*.html', ejs: [srcDir + '/**/*.ejs', '!' + srcDir + '/**/_*.ejs'], tests: './test/**/*' }; // dest holds the values of desination folders var dest = { root: destDir, css: destDir + '/css', js: destDir + '/js', img: destDir + '/img', fonts: destDir + '/fonts', html: destDir }; // Export our src and dest configurations so they can // be used in our gulp tasks module.exports = { src: src, dest: dest };
function DialogShow(text, time, done){ if ($("#dialog").length > 0) $("#dialog").remove(); var id = $.mobile.activePage.attr("id"); if (!id) id = "content"; $("#" + id).append("<div data-role='popup' id='dialog' data-transition='fade' data-position-to='window'><p>" + text + "</p></div>"); var dialog = $("#dialog"); dialog.popup({ history: false }); dialog.css({"padding": "2em", "opacity": "0.85"}); dialog.popup("open").on({ popupafteropen: function (){ if (!time) time = 2000; setTimeout(function (){ dialog.popup('close') if (done) done(); }, time); } }); } var menuShow = false function ToggleMenu(){ if (menuShow){ $("#menu").hide(); menuShow = false; }else{ $("#menu").show(); menuShow = true; } } function Send(url, json, callback) { var request = $.ajax({ type: 'POST', url: url, data: JSON.stringify(json), contentType: 'application/json', dataType: 'json', timeout: 30000, async: false }); request.done(function (data) { if (!callback && data) { if (!data.Message) DialogShow("Ok"); else DialogShow(data.Message); } if (callback) callback(data); }); request.fail(function (data) { var msg = "" if (data && data.responseText) msg = data.responseText; DialogShow("Произошла ошибка, повторите еще раз позже"+msg); }); }
var vue2; (function (vue2) { var infiniteGrid2 = (function () { function infiniteGrid2() { this.divSize = 1; this.lines = []; } infiniteGrid2.prototype.setDivSize = function (size) { this.divSize = size; }; infiniteGrid2.prototype.setBounds = function (bounds) { this.lines = []; var xMin = bounds.min[0]; var yMin = bounds.min[1]; var xMax = bounds.max[0]; var yMax = bounds.max[1]; var xMin2 = xMin - (xMin % 0.001); var yMin2 = yMin - (yMin % 0.001); for (var x = xMin2; x < xMax; x += 0.001) { this.lines.push([x, yMin]); this.lines.push([x, yMax]); } for (var y = yMin2; y < yMax; y += 0.001) { this.lines.push([xMin, y]); this.lines.push([xMax, y]); } }; return infiniteGrid2; })(); vue2.infiniteGrid2 = infiniteGrid2; })(vue2 || (vue2 = {})); function setView2Data(element) { var elt = $(element).parent()[0]; while (elt != undefined && elt != null) { var view2 = $(elt).data('view2'); if (view2 != undefined) { $(element).data('view2', view2); return view2; } elt = $(elt).parent()[0]; } alert("view2 not found in DOM"); return undefined; } ko.bindingHandlers.vue2View = { init: function (element, valueAccessor, allBindingsAccessor, viewModel) { var observable = valueAccessor(); var view2 = new vue2.view2(); $(element).data('view2', view2); view2.setWindowSize($(element).width(), $(element).height()); var interactions = new vue2.view2Interactions(); interactions.setView2(view2); $(element).mousewheel(function (e, delta) { var eoffsetX = (e.offsetX || e.clientX - $(e.target).offset().left + window.pageXOffset), eoffsetY = (e.offsetY || e.clientY - $(e.target).offset().top + window.pageYOffset); interactions.zoomRelative(delta, [eoffsetX, eoffsetY]); }); $(element).mousedown($.proxy(interactions.onMousedown, interactions)); $(element).mouseup($.proxy(interactions.onMouseup, interactions)); $(element).mousemove($.proxy(interactions.onMousemove, interactions)); var callback = function () { }; view2.pushBoundChanged(element, callback); ko.bindingHandlers.vue2View.update(element, valueAccessor, allBindingsAccessor, viewModel, undefined); }, update: function (element, valueAccessor, allBindingsAccessor, viewModel) { console.log("View2 set bounds to view model"); var value = ko.utils.unwrapObservable(valueAccessor()); var view2 = $(element).data('view2'); setTimeout(function () { view2.setBounds(value); }, 1); } }; ko.bindingHandlers.vue2Grid = { init: function (element, valueAccessor, allBindingsAccessor, viewModel) { var view2 = setView2Data(element); var value = ko.utils.unwrapObservable(valueAccessor()); var grid = new vue2.infiniteGrid2(); grid.setDivSize(value.divSize); var doUpdate = function () { var view2 = $(element).data('view2'); grid.setBounds(view2.bounds); var path = element; var segments = path.pathSegList; segments.clear(); var dest = [0, 0]; var i, len = grid.lines.length; for (i = 0; i < len; i += 2) { view2.vecToWindow(grid.lines[i], dest); segments.appendItem(path.createSVGPathSegMovetoAbs(dest[0], dest[1])); view2.vecToWindow(grid.lines[i + 1], dest); segments.appendItem(path.createSVGPathSegLinetoAbs(dest[0], dest[1])); } }; doUpdate(); view2.pushBoundChanged(element, doUpdate); }, update: function (element, valueAccessor, allBindingsAccessor, viewModel) { } }; ko.bindingHandlers.vue2Center = { init: function (element, valueAccessor, allBindingsAccessor, viewModel) { var view2 = setView2Data(element); var options = allBindingsAccessor().vue2Options || {}; var constraint = allBindingsAccessor().vue2Constraint; if (options.draggable == true) { var dragStartLeft = 0; var dragStartTop = 0; var dragStart2 = [0, 0]; $(element).draggable({ start: function (event, ui) { var observable = valueAccessor(); dragStart2[0] = observable()[0]; dragStart2[1] = observable()[1]; dragStartLeft = ui.position.left; dragStartTop = ui.position.top; }, drag: function (event, ui) { var options = allBindingsAccessor().vue2Options || {}; var observable = valueAccessor(); if (options.axis != undefined) { var axis = [options.axis.left, options.axis.top]; var delta = [ ui.position.left - dragStartLeft, ui.position.top - dragStartTop ]; var dot = delta[0] * axis[0] + delta[1] * axis[1]; dot /= (axis[0] * axis[0] + axis[1] * axis[1]); ui.position.left = dragStartLeft + dot * axis[0]; ui.position.top = dragStartTop + dot * axis[1]; } var left = ui.position.left + $(element).width() / 2; var top = ui.position.top + $(element).height() / 2; if (options.windowOffset && options.windowOffset.left) { left -= options.windowOffset.left; } if (options.windowOffset && options.windowOffset.top) { top -= options.windowOffset.top; } var windowPos = [left, top]; var worldPos = [0, 0]; view2.vecToWorld(windowPos, worldPos); if (constraint) { var prox = $.proxy(constraint, viewModel); prox(ui, { start: dragStart2, position: worldPos }); view2.vecToWindow(worldPos, windowPos); left = windowPos[0] - $(element).width() / 2; top = windowPos[1] - $(element).height() / 2; if (options.windowOffset && options.windowOffset.left) { left += options.windowOffset.left; } if (options.windowOffset && options.windowOffset.top) { top += options.windowOffset.top; } ui.position.left = left; ui.position.top = top; } observable(worldPos); }, stop: function (event, ui) { } }); } var callback = function () { ko.bindingHandlers.vue2Center.update(element, valueAccessor, allBindingsAccessor, viewModel, null); }; view2.pushBoundChanged(element, callback); ko.utils.domNodeDisposal.addDisposeCallback(element, function () { view2.removeBoundChanged(element); }); }, update: function (element, valueAccessor, allBindingsAccessor, viewModel) { var value = ko.utils.unwrapObservable(valueAccessor()); var options = allBindingsAccessor().vue2Options || {}; var view2 = $(element).data('view2'); if (view2 != undefined) { var dest = [0, 0]; view2.vecToWindow(value, dest); var newTop = dest[1] - $(element).height() / 2; var newLeft = dest[0] - $(element).width() / 2; if (options.windowOffset && options.windowOffset.top) { newTop += options.windowOffset.top; } if (options.windowOffset && options.windowOffset.left) { newLeft += options.windowOffset.left; } $(element).css({ top: newTop, left: newLeft }); } } }; ko.bindingHandlers.vue2Bounds = { init: function (element, valueAccessor, allBindingsAccessor, viewModel) { var view2 = setView2Data(element); var callback = function () { ko.bindingHandlers.vue2Bounds.update(element, valueAccessor, allBindingsAccessor, viewModel, null); }; view2.pushBoundChanged(element, callback); ko.utils.domNodeDisposal.addDisposeCallback(element, function () { view2.removeBoundChanged(element); }); }, update: function (element, valueAccessor, allBindingsAccessor, viewModel) { var view2 = $(element).data('view2'); if (view2 != undefined) { var rect = ko.utils.unwrapObservable(valueAccessor()); var bottomLeft = [0, 0]; var topRight = [0, 0]; view2.vecToWindow(rect.min, bottomLeft); view2.vecToWindow(rect.max, topRight); $(element).css({ top: topRight[1], left: bottomLeft[0], width: topRight[0] - bottomLeft[0], height: bottomLeft[1] - topRight[1] }); } } }; ko.bindingHandlers.vue2Points = { init: function (element, valueAccessor, allBindingsAccessor, viewModel) { var view2 = setView2Data(element); var callback = function () { ko.bindingHandlers.vue2Points.update(element, valueAccessor, allBindingsAccessor, viewModel, null); }; view2.pushBoundChanged(element, callback); ko.utils.domNodeDisposal.addDisposeCallback(element, function () { view2.removeBoundChanged(element); }); }, update: function (element, valueAccessor, allBindingsAccessor, viewModel) { var view2 = $(element).data('view2'); var path = element; var segments = path.pathSegList; segments.clear(); var value0 = ko.utils.unwrapObservable(valueAccessor()); var value = value0; if (value.length <= 1) { return; } var dest = [0, 0]; view2.vecToWindow(value[0], dest); segments.appendItem(path.createSVGPathSegMovetoAbs(dest[0], dest[1])); var i, len = value.length; for (i = 1; i < len; ++i) { view2.vecToWindow(value[i], dest); segments.appendItem(path.createSVGPathSegLinetoAbs(dest[0], dest[1])); } } }; var vue2; (function (vue2) { var rectangle2 = (function () { function rectangle2() { this.min = [0, 0]; this.max = [0, 0]; } Object.defineProperty(rectangle2.prototype, "width", { get: function () { return this.max[0] - this.min[0]; }, enumerable: true, configurable: true }); Object.defineProperty(rectangle2.prototype, "height", { get: function () { return this.max[1] - this.min[1]; }, enumerable: true, configurable: true }); rectangle2.prototype.set4 = function (minx, miny, maxx, maxy) { this.min[0] = minx; this.min[1] = miny; this.max[0] = maxx; this.max[1] = maxy; }; rectangle2.prototype.copy = function (dest) { dest.min[0] = this.min[0]; dest.min[1] = this.min[1]; dest.max[0] = this.max[0]; dest.max[1] = this.max[1]; }; return rectangle2; })(); vue2.rectangle2 = rectangle2; })(vue2 || (vue2 = {})); var vue2; (function (vue2) { var view2 = (function () { function view2() { this.width = 700; this.height = 700; this.bounds = new vue2.rectangle2(); this.boundsChanged = []; this.windowVectorToWorld = function (v, dest) { var minX = this.bounds.min[0]; var minY = this.bounds.min[1]; var maxX = this.bounds.max[0]; var maxY = this.bounds.max[1]; dest[0] = v[0] / this.width * (maxX - minX); dest[1] = -v[1] / this.height * (maxY - minY); }; this.bounds.set4(-1, -1, 2, 2); this.__uniqueId = view2.__uniqueIdCounter++; } view2.prototype.vecToWindow = function (w, dest) { var minX = this.bounds.min[0]; var minY = this.bounds.min[1]; var maxX = this.bounds.max[0]; var maxY = this.bounds.max[1]; var rx = (w[0] - minX) / (maxX - minX); var ry = (w[1] - minY) / (maxY - minY); var cx = rx * this.width; var cy = this.height * (1 - ry); dest[0] = cx; dest[1] = cy; }; view2.prototype.vecToWorld = function (c, dest) { var minX = this.bounds.min[0]; var minY = this.bounds.min[1]; var maxX = this.bounds.max[0]; var maxY = this.bounds.max[1]; var rx = c[0] / this.width; var ry = 1 - c[1] / this.height; var wx = (1 - rx) * minX + rx * maxX; var wy = (1 - ry) * minY + ry * maxY; dest[0] = wx; dest[1] = wy; }; view2.prototype.setWindowSize = function (width, height) { this.width = width; this.height = height; }; view2.prototype.setBounds = function (bounds) { bounds.copy(this.bounds); this.boundsChanged.forEach(function (f) { return f.callback(); }); }; view2.prototype.setBounds4 = function (minx, miny, maxx, maxy) { this.bounds.set4(minx, miny, maxx, maxy); this.boundsChanged.forEach(function (f) { return f.callback(); }); }; view2.prototype.translateBounds = function (delta) { this.bounds.min[0] += delta[0]; this.bounds.min[1] += delta[1]; this.bounds.max[0] += delta[0]; this.bounds.max[1] += delta[1]; }; view2.prototype.pushBoundChanged = function (tag, callback) { this.boundsChanged.push(new callbackWithTag(tag, callback)); }; view2.prototype.removeBoundChanged = function (tag) { var len = this.boundsChanged.length; for (var i = 0; i < len; ++i) { if (this.boundsChanged[i].tag == tag) { this.boundsChanged.splice(i, 1); return; } } console.error("removeBoundChanged not found"); }; view2.__uniqueIdCounter = 1; return view2; })(); vue2.view2 = view2; var callbackWithTag = (function () { function callbackWithTag(tag, callback) { this.tag = tag; this.callback = callback; } return callbackWithTag; })(); vue2.callbackWithTag = callbackWithTag; })(vue2 || (vue2 = {})); var vue2; (function (vue2) { var view2Interactions = (function () { function view2Interactions() { this.isMouseDown = false; this.mouseStart = [0, 0]; this.boundsStart = new vue2.rectangle2(); } view2Interactions.prototype.setView2 = function (view2) { this.view2 = view2; }; view2Interactions.prototype.zoomRelative = function (delta, mouseXY) { var cx = mouseXY[0]; var cy = mouseXY[1]; var coeff = delta > 0 ? 0.9 : 1.1; var minX = this.view2.bounds.min[0]; var minY = this.view2.bounds.min[1]; var maxX = this.view2.bounds.max[0]; var maxY = this.view2.bounds.max[1]; var w = [0, 0]; this.view2.vecToWorld(mouseXY, w); var k = coeff * (maxX - minX); var newMinX = -1 * (k * cx / this.view2.width - w[0]); var newMaxX = k + newMinX; k = coeff * (maxY - minY); var newMinY = k * (cy / this.view2.height - 1) + w[1]; var newMaxY = k + newMinY; this.view2.setBounds4(newMinX, newMinY, newMaxX, newMaxY); }; view2Interactions.prototype.onMousedown = function (event) { if (event.which != 2) { return; } this.isMouseDown = true; this.mouseStart = this.getMouse(); this.view2.bounds.copy(this.boundsStart); }; view2Interactions.prototype.onMouseup = function (event) { if (event.which != 2) { return; } this.isMouseDown = false; }; view2Interactions.prototype.onMousemove = function (event) { if (!this.isMouseDown) { return; } var mouse = this.getMouse(); var windowDelta = [ mouse[0] - this.mouseStart[0], mouse[1] - this.mouseStart[1] ]; var viewDelta = [0, 0]; this.view2.windowVectorToWorld(windowDelta, viewDelta); this.view2.setBounds4(this.boundsStart.min[0] - viewDelta[0], this.boundsStart.min[1] - viewDelta[1], this.boundsStart.max[0] - viewDelta[0], this.boundsStart.max[1] - viewDelta[1]); }; view2Interactions.prototype.getMouse = function () { var eoffsetX = (event.offsetX || event.clientX), eoffsetY = (event.offsetY || event.clientY); return [eoffsetX, eoffsetY]; }; return view2Interactions; })(); vue2.view2Interactions = view2Interactions; })(vue2 || (vue2 = {})); //# sourceMappingURL=vue2.js.map
var Hints = {}; Hints.matchPatterns = function(forward) { var pattern = new RegExp('^' + (forward ? settings.nextmatchpattern : settings.previousmatchpattern) + '$', 'gi'); var nodeIterator = document.createNodeIterator(document.body, 4, null, false); var node; while (node = nodeIterator.nextNode()) { var localName = node.localName; if (/script|style|noscript/.test(localName)) { continue; } var nodeText = node.data.trim(); if (pattern.test(nodeText)) { var parentNode = node.parentNode; if (/a|button/.test(parentNode.localName) || parentNode.getAttribute('jsaction') || parentNode.getAttribute('onclick')) { var computedStyle = getComputedStyle(parentNode); if (computedStyle.opacity !== '0' && computedStyle.visibility === 'visible' && computedStyle.display !== 'none') { node.parentNode.click(); break; } } } } }; Hints.hideHints = function(reset, multi, useKeyDelay) { if (reset && document.getElementById('cVim-link-container') !== null) { document.getElementById('cVim-link-container').parentNode.removeChild(document.getElementById('cVim-link-container')); } else if (document.getElementById('cVim-link-container') !== null) { if (!multi) { HUD.hide(); } main = document.getElementById('cVim-link-container'); if (settings.linkanimations) { main.addEventListener('transitionend', function() { var m = document.getElementById('cVim-link-container'); if (m !== null) { m.parentNode.removeChild(m); } }); main.style.opacity = '0'; } else { document.getElementById('cVim-link-container').parentNode.removeChild(document.getElementById('cVim-link-container')); } } this.linkPreview = false; this.numericMatch = void 0; this.active = reset; this.currentString = ''; this.linkArr = []; this.linkHints = []; this.permutations = []; if (useKeyDelay && !this.active && settings.numerichints && settings.typelinkhints) { Hints.keyDelay = true; window.setTimeout(function() { Hints.keyDelay = false; }, settings.typelinkhintsdelay); } }; Hints.changeFocus = function() { this.linkArr.forEach(function(item) { item[0].style.zIndex = 1 - +item[0].style.zIndex; }); }; Hints.removeContainer = function() { var hintContainer = document.getElementById('cVim-link-container'); if (hintContainer !== null) { hintContainer.parentNode.removeChild(hintContainer); } }; Hints.dispatchAction = function(link) { if (!link) { return false; } this.lastClicked = link; var node = link.localName; if (settings.numerichints && settings.typelinkhints) { Hints.keyDelay = true; window.setTimeout(function() { Hints.keyDelay = false; }, settings.typelinkhintsdelay); } switch (this.type) { case 'yank': case 'multiyank': var text = link.href || link.value || link.getAttribute('placeholder'); if (text) { Clipboard.copy(text, this.multi); Status.setMessage(text, 2); } break; case 'image': case 'multiimage': var url = googleReverseImage(link.src, null); if (url) { chrome.runtime.sendMessage({action: 'openLinkTab', active: false, url: url, noconvert: true}); } break; case 'hover': if (Hints.lastHover) { Hints.lastHover.unhover(); if (Hints.lastHover === link) { Hints.lastHover = null; break; } } link.hover(); Hints.lastHover = link; break; case 'unhover': link.unhover(); break; case 'window': chrome.runtime.sendMessage({action: 'openLinkWindow', focused: false, url: link.href, noconvert: true}); break; default: if (node === 'textarea' || (node === 'input' && /^(text|password|email|search)$/i.test(link.type)) || link.getAttribute('contenteditable') === 'true') { setTimeout(function() { link.focus(); if (link.getAttribute('readonly')) { link.select(); } }.bind(this), 0); break; } if (node === 'input' || /button|select/i.test(node) || /^(button|checkbox|menu)$/.test(link.getAttribute('role')) || link.getAttribute('jsaction') || link.getAttribute('onclick') || link.getAttribute('role') === 'checkbox') { window.setTimeout(function() { link.simulateClick(); }, 0); break; } if (link.getAttribute('target') !== '_top' && (/tabbed/.test(this.type) || this.type === 'multi')) { chrome.runtime.sendMessage({action: 'openLinkTab', active: this.type === 'tabbedActive', url: link.href, noconvert: true}); } else { if (link.getAttribute('href')) { link.click(); } else { link.simulateClick(); } } break; } if (this.multi) { this.removeContainer(); window.setTimeout(function() { if (!document.activeElement.isInput()) { this.create(this.type, true); } }.bind(this), 0); } else { this.hideHints(false, false, true); } }; Hints.handleHintFeedback = function() { var linksFound = 0, index, link, i, span; if (!settings.numerichints) { for (i = 0; i < this.permutations.length; i++) { link = this.linkArr[i][0]; if (this.permutations[i].indexOf(this.currentString) === 0) { if (link.children.length) { link.replaceChild(link.firstChild.firstChild, link.firstChild); link.normalize(); } if (settings.dimhintcharacters) { span = document.createElement('span'); span.setAttribute('cVim', true); span.className = 'cVim-link-hint_match'; link.firstChild.splitText(this.currentString.length); span.appendChild(link.firstChild.cloneNode(true)); link.replaceChild(span, link.firstChild); } else if (link.textContent.length !== 1) { link.firstChild.deleteData(null, 1); } index = i.toString(); linksFound++; } else if (link.parentNode) { link.style.opacity = '0'; } } } else { var containsNumber, validMatch, stringNum, string; Hints.numericMatch = null; this.currentString = this.currentString.toLowerCase(); string = this.currentString; containsNumber = /\d+$/.test(string); if (containsNumber) { stringNum = this.currentString.match(/[0-9]+$/)[0]; } if ((!string) || (!settings.typelinkhints && /\D/.test(string.slice(-1)))) { return this.hideHints(false); } for (i = 0, l = this.linkArr.length; i < l; ++i) { link = this.linkArr[i][0]; if (link.style.opacity === '0') { continue; } validMatch = false; if (settings.typelinkhints) { if (containsNumber && link.textContent.indexOf(stringNum) === 0) { validMatch = true; } else if (!containsNumber && this.linkArr[i][2].toLowerCase().indexOf(string.replace(/.*\d/g, '')) !== -1) { validMatch = true; } } else if (link.textContent.indexOf(string) === 0) { validMatch = true; } if (validMatch) { if (link.children.length) { link.replaceChild(link.firstChild.firstChild, link.firstChild); link.normalize(); } if (settings.typelinkhints && !containsNumber) { var c = 0; for (var j = 0; j < this.linkArr.length; ++j) { if (this.linkArr[j][0].style.opacity !== '0') { this.linkArr[j][0].textContent = (c + 1).toString() + (this.linkArr[j][3] ? ': ' + this.linkArr[j][3] : ''); c++; } } } if (!Hints.numericMatch || link.textContent === string) { Hints.numericMatch = this.linkArr[i][1]; } if (containsNumber) { if (settings.dimhintcharacters) { span = document.createElement('span'); span.setAttribute('cVim', true); span.className = 'cVim-link-hint_match'; link.firstChild.splitText(stringNum.length); span.appendChild(link.firstChild.cloneNode(true)); link.replaceChild(span, link.firstChild); } else if (link.textContent.length !== 1) { link.firstChild.deleteData(null, 1); } } index = i.toString(); linksFound++; } else if (link.parentNode) { link.style.opacity = '0'; } } } if (linksFound === 0) { this.hideHints(false, false, true); } if (linksFound === 1) { this.dispatchAction(this.linkArr[index][1]); this.hideHints(false); } }; Hints.handleHint = function(key) { if (this.linkPreview) { this.dispatchAction(this.linkArr[this.currentIndex][1]); } if (settings.numerichints || settings.hintcharacters.split('').indexOf(key.toLowerCase()) !== -1) { this.currentString += key.toLowerCase(); this.handleHintFeedback(this.currentString); } else { this.hideHints(false, false, true); } }; Hints.evaluateLink = function(link, linkIndex) { var isAreaNode = false, imgParent, linkElement, linkStyle, mapCoordinates; if (link.localName === 'area' && link.parentNode && link.parentNode.localName === 'map') { imgParent = document.querySelector('img[usemap="#' + link.parentNode.name + '"'); if (!imgParent) { return; } linkLocation = getVisibleBoundingRect(imgParent); isAreaNode = true; } else { linkLocation = getVisibleBoundingRect(link); } if (!linkLocation) { return; } linkElement = this.linkElementBase.cloneNode(false); linkStyle = linkElement.style; linkStyle.zIndex = linkIndex; if (isAreaNode) { mapCoordinates = link.getAttribute('coords').split(','); if (mapCoordinates.length < 2) { return; } linkStyle.top = linkLocation.top * this.documentZoom + document.body.scrollTop + parseInt(mapCoordinates[1]) + 'px'; linkStyle.left = linkLocation.left * this.documentZoom + document.body.scrollLeft + parseInt(mapCoordinates[0]) + 'px'; } else { if (linkLocation.top < 0) { linkStyle.top = document.body.scrollTop+ 'px'; } else { linkStyle.top = linkLocation.top * this.documentZoom + document.body.scrollTop + 'px'; } if (linkLocation.left < 0) { linkStyle.left = document.body.scrollLeft + 'px'; } else { if (l.offsetLeft > linkLocation.left) { linkStyle.left = link.offsetLeft * this.documentZoom + 'px'; } else { linkStyle.left = linkLocation.left * this.documentZoom + document.body.scrollLeft + 'px'; } } } if (settings && settings.numerichints) { if (!settings.typelinkhints) { this.linkArr.push([linkLocation.bottom * linkLocation.left, linkElement, link]); } else { var textValue = ''; var alt = ''; if (link.firstElementChild && link.firstElementChild.alt) { textValue = link.firstElementChild.alt; alt = textValue; } else { textValue = link.textContent || link.value || link.alt || ''; } this.linkArr.push([linkLocation.left + linkLocation.top, linkElement, link, textValue, alt]); } } else { this.linkArr.push([linkElement, link]); } }; Hints.siteFilters = { 'reddit.com': function(node) { if (node.localName === 'a' && !node.getAttribute('href')) { return false; } if (node.getAttribute('onclick') && node.getAttribute('onclick').indexOf('click_thing') === 0) { return false; } return true; } }; Hints.getLinks = function() { var node, nodeIterator, name, role, applicableFiltersLength, filterCatch, i = 0, applicableFilters = []; nodeIterator = document.createNodeIterator(document.body, 1, { acceptNode: function(node) { name = node.localName.toLowerCase(); if (Hints.type) { if (Hints.type.indexOf('yank') !== -1) { return name === 'a' || name === 'textarea' || name === 'input'; } else if (Hints.type.indexOf('image') !== -1) { return name === 'img'; } } if (name === 'a' || name === 'button' || name === 'select' || name === 'textarea' || name === 'input' || name === 'area') { return NodeFilter.FILTER_ACCEPT; } if (node.getAttribute('onclick') || node.getAttribute('tabindex') || node.getAttribute('aria-haspopup') || node.getAttribute('data-cmd') || node.getAttribute('jsaction')) { return NodeFilter.FILTER_ACCEPT; } if (role = node.getAttribute('role')) { if (role === 'button' || role === 'checkbox' || role.indexOf('menu') === 0) { return NodeFilter.FILTER_ACCEPT; } } return NodeFilter.FILTER_REJECT; } }); for (var key in this.siteFilters) { if (window.location.origin.indexOf(key) !== -1) { applicableFilters.push(this.siteFilters[key]); } } applicableFiltersLength = applicableFilters.length; while (node = nodeIterator.nextNode()) { filterCatch = false; for (var j = 0; j < applicableFiltersLength; j++) { if (!applicableFilters[j](node)) { filterCatch = true; break; } } if (!filterCatch) { this.evaluateLink(node, i++); } } }; Hints.generateHintString = function(n, x) { var len = settings.hintcharacters.length, l = [], r; for (var i = 0; n >= 0 && i < x; i++) { r = n % len; l.push(settings.hintcharacters[r]); n -= r; n /= Math.floor(len); } return l.reverse().join(''); }; Hints.create = function(type, multi) { if (!Command.domElementsLoaded) { return false; } var links, main, frag, i, l; this.type = type; this.hideHints(true, multi); if (document.body && document.body.style) { Hints.documentZoom = +document.body.style.zoom || 1; } else { Hints.documentZoom = 1; } Hints.linkElementBase = document.createElement('div'); Hints.linkElementBase.cVim = true; Hints.linkElementBase.className = 'cVim-link-hint'; links = this.getLinks(); if (type && type.indexOf('multi') !== -1) { this.multi = true; } else { this.multi = false; } if (this.linkArr.length === 0) { return this.hideHints(); } main = document.createElement('div'); if (settings && settings.linkanimations) { main.style.opacity = '0'; } main.cVim = true; frag = document.createDocumentFragment(); main.id = 'cVim-link-container'; main.top = document.body.scrollTop + 'px'; main.left = document.body.scrollLeft + 'px'; try { document.lastChild.appendChild(main); } catch(e) { document.body.appendChild(main); } if (!multi && settings && settings.hud) { HUD.display('Follow link ' + (function() { switch (type) { case 'yank': return '(yank)'; case 'multiyank': return '(multi-yank)'; case 'image': return '(reverse image)'; case 'tabbed': case 'tabbedActive': return '(tabbed)'; case 'window': return '(window)'; case 'hover': return '(hover)'; case 'unhover': return '(unhover)'; case 'multi': return '(multi)'; default: return ''; } })()); } if (!settings.numerichints) { var lim = Math.ceil(Math.log(this.linkArr.length) / Math.log(settings.hintcharacters.length)) || 1; var rlim = Math.floor((Math.pow(settings.hintcharacters.length, lim) - this.linkArr.length) / settings.hintcharacters.length); for (i = 0; i < rlim; ++i) { this.linkArr[i][0].textContent = this.generateHintString(i, lim - 1); this.permutations.push(this.generateHintString(i, lim - 1)); } for (i = rlim * settings.hintcharacters.length, e = i + this.linkArr.length - rlim; i < e; ++i) { this.permutations.push(this.generateHintString(i, lim)); } for (i = this.linkArr.length - 1; i >= 0; --i) { this.linkArr[i][0].textContent = this.permutations[i]; frag.appendChild(this.linkArr[i][0]); } } else { this.linkArr = this.linkArr.sort(function(a, b) { return a[0] - b[0]; }).map(function(e) { return e.slice(1); }); for (i = 0, l = this.linkArr.length; i < l; ++i) { this.linkArr[i][0].textContent = (i + 1).toString() + (this.linkArr[i][3] ? ': ' + this.linkArr[i][3] : ''); frag.appendChild(this.linkArr[i][0]); } } main.appendChild(frag); main.style.opacity = '1'; };
import React, { Component } from 'react'; export default class SearchForm extends Component { constructor(props) { super(props); } render() { let _this = this; return ( <div className="r searchForm rel"> <form onSubmit={this.props.onSearch}> <button className="searchBtn"> <svg viewBox="0 0 100 100"> <use xlinkHref="#icon-search"> </use> </svg> </button> <input type="text" className="abs" required value={_this.props.keyword} onChange={this.props.onInputChange} placeholder="在此输入搜索关键字"/> </form> </div> ) } }
"use strict"; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; }; exports.check = check; var util = _interopRequireWildcard(require("../../../util")); var t = _interopRequireWildcard(require("../../../types")); function check(node) { return t.isFunction(node) && hasDefaults(node); } var hasDefaults = function hasDefaults(node) { for (var i = 0; i < node.params.length; i++) { if (!t.isIdentifier(node.params[i])) return true; } return false; }; var iifeVisitor = { enter: function enter(node, parent, scope, state) { if (!this.isReferencedIdentifier()) return; if (!state.scope.hasOwnBinding(node.name)) return; if (state.scope.bindingIdentifierEquals(node.name, node)) return; state.iife = true; this.stop(); } }; exports.Function = function (node, parent, scope, file) { if (!hasDefaults(node)) return; t.ensureBlock(node); var body = []; var argsIdentifier = t.identifier("arguments"); argsIdentifier._ignoreAliasFunctions = true; var lastNonDefaultParam = 0; var state = { iife: false, scope: scope }; var pushDefNode = function pushDefNode(left, right, i) { var defNode = util.template("default-parameter", { VARIABLE_NAME: left, DEFAULT_VALUE: right, ARGUMENT_KEY: t.literal(i), ARGUMENTS: argsIdentifier }, true); file.checkNode(defNode); defNode._blockHoist = node.params.length - i; body.push(defNode); }; for (var i = 0; i < node.params.length; i++) { var param = node.params[i]; if (!t.isAssignmentPattern(param)) { if (!t.isRestElement(param)) { lastNonDefaultParam = i + 1; } if (!t.isIdentifier(param)) { scope.traverse(param, iifeVisitor, state); } if (file.transformers["es6.blockScopingTDZ"].canRun() && t.isIdentifier(param)) { pushDefNode(param, t.identifier("undefined"), i); } continue; } var left = param.left; var right = param.right; var placeholder = scope.generateUidIdentifier("x"); placeholder._isDefaultPlaceholder = true; node.params[i] = placeholder; if (!state.iife) { if (t.isIdentifier(right) && scope.hasOwnBinding(right.name)) { state.iife = true; } else { scope.traverse(right, iifeVisitor, state); } } pushDefNode(left, right, i); } // we need to cut off all trailing default parameters node.params = node.params.slice(0, lastNonDefaultParam); if (state.iife) { var container = t.functionExpression(null, [], node.body, node.generator); container._aliasFunction = true; body.push(t.returnStatement(t.callExpression(container, []))); node.body = t.blockStatement(body); } else { node.body.body = body.concat(node.body.body); } }; exports.__esModule = true;
// All code points in the `Duployan` script as per Unicode v8.0.0: [ 0x1BC00, 0x1BC01, 0x1BC02, 0x1BC03, 0x1BC04, 0x1BC05, 0x1BC06, 0x1BC07, 0x1BC08, 0x1BC09, 0x1BC0A, 0x1BC0B, 0x1BC0C, 0x1BC0D, 0x1BC0E, 0x1BC0F, 0x1BC10, 0x1BC11, 0x1BC12, 0x1BC13, 0x1BC14, 0x1BC15, 0x1BC16, 0x1BC17, 0x1BC18, 0x1BC19, 0x1BC1A, 0x1BC1B, 0x1BC1C, 0x1BC1D, 0x1BC1E, 0x1BC1F, 0x1BC20, 0x1BC21, 0x1BC22, 0x1BC23, 0x1BC24, 0x1BC25, 0x1BC26, 0x1BC27, 0x1BC28, 0x1BC29, 0x1BC2A, 0x1BC2B, 0x1BC2C, 0x1BC2D, 0x1BC2E, 0x1BC2F, 0x1BC30, 0x1BC31, 0x1BC32, 0x1BC33, 0x1BC34, 0x1BC35, 0x1BC36, 0x1BC37, 0x1BC38, 0x1BC39, 0x1BC3A, 0x1BC3B, 0x1BC3C, 0x1BC3D, 0x1BC3E, 0x1BC3F, 0x1BC40, 0x1BC41, 0x1BC42, 0x1BC43, 0x1BC44, 0x1BC45, 0x1BC46, 0x1BC47, 0x1BC48, 0x1BC49, 0x1BC4A, 0x1BC4B, 0x1BC4C, 0x1BC4D, 0x1BC4E, 0x1BC4F, 0x1BC50, 0x1BC51, 0x1BC52, 0x1BC53, 0x1BC54, 0x1BC55, 0x1BC56, 0x1BC57, 0x1BC58, 0x1BC59, 0x1BC5A, 0x1BC5B, 0x1BC5C, 0x1BC5D, 0x1BC5E, 0x1BC5F, 0x1BC60, 0x1BC61, 0x1BC62, 0x1BC63, 0x1BC64, 0x1BC65, 0x1BC66, 0x1BC67, 0x1BC68, 0x1BC69, 0x1BC6A, 0x1BC70, 0x1BC71, 0x1BC72, 0x1BC73, 0x1BC74, 0x1BC75, 0x1BC76, 0x1BC77, 0x1BC78, 0x1BC79, 0x1BC7A, 0x1BC7B, 0x1BC7C, 0x1BC80, 0x1BC81, 0x1BC82, 0x1BC83, 0x1BC84, 0x1BC85, 0x1BC86, 0x1BC87, 0x1BC88, 0x1BC90, 0x1BC91, 0x1BC92, 0x1BC93, 0x1BC94, 0x1BC95, 0x1BC96, 0x1BC97, 0x1BC98, 0x1BC99, 0x1BC9C, 0x1BC9D, 0x1BC9E, 0x1BC9F ];
var mathModule = require('./math-module') describe('math module', function () { describe('add', function () { it('should correctly add positive numbers', function () { var result = mathModule.add(3, 2) expect(result).to.equal(5) }) it('should correctly add negative numbers', function () { var result = mathModule.add(-3, -5) expect(result).to.equal(-8) }) }) })
'use strict'; var config = require('../config'), log = require('../logger'); module.exports = function (eventargs) { if (config.meta.env !== 'production') { // logs the middleware name that is about to be registered console.log('Middleware registered: %s', eventargs.name); } else { var logData = { middleware: eventargs.name }; log.info(logData, 'Middleware registered'); } };
// 演示数据 db.checkitem.insert({ "name":"检查DB当前登录用户信息", "target_ip":"server", "target_ip2":"", "options":{ }, "cmd": { "category":"mssql", "res_type":"multi_rows", "command":"select login_name,host_name, host_process_id,login_time from sys.dm_exec_sessions where host_name!=''", "args":[ "server=192.168.230.113\SD;user id=readonly;password=readonly;" ] }, "checkways":[ { "way":"shouldBeGreaterThan", "params":[0], "level":"warn", "options":[] } ] }); db.checkitem.insert({ "name":"检查Server运行目录文件", "target_ip":"server", "target_ip2":"", "options":{ }, "cmd": { "category":"cmd", "res_type":"string", "command":"dir", "args":[ ".", "/B" ] }, "checkways":[ { "way":"ShouldContain", "params":[".exe"], "level":"warn", "options":[] } ] });
/* http://www.JSON.org/json2.js 2009-04-16 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the object holding the key. For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. */ /*jslint evil: true */ /*global JSON */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. if (!this.JSON) { JSON = {}; } (function () { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/. test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } }()); /*! * jQuery JavaScript Library v1.4.2 * http://jquery.com/ * * Copyright 2010, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2010, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Sat Feb 13 22:33:48 2010 -0500 */ (function( window, undefined ) { // Define a local copy of jQuery var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context ); }, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // Use the correct document accordingly with window argument (sandbox) document = window.document, // A central reference to the root jQuery(document) rootjQuery, // A simple way to check for HTML strings or ID strings // (both of which we optimize for) quickExpr = /^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/, // Is it a simple selector isSimple = /^.[^:#\[\.,]*$/, // Check if a string has a non-whitespace character in it rnotwhite = /\S/, // Used for trimming whitespace rtrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, // Keep a UserAgent string for use with jQuery.browser userAgent = navigator.userAgent, // For matching the engine and version of the browser browserMatch, // Has the ready events already been bound? readyBound = false, // The functions to execute on DOM ready readyList = [], // The ready event handler DOMContentLoaded, // Save a reference to some core methods toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, push = Array.prototype.push, slice = Array.prototype.slice, indexOf = Array.prototype.indexOf; jQuery.fn = jQuery.prototype = { init: function( selector, context ) { var match, elem, ret, doc; // Handle $(""), $(null), or $(undefined) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // The body element only exists once, optimize finding it if ( selector === "body" && !context ) { this.context = document; this[0] = document.body; this.selector = "body"; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? match = quickExpr.exec( selector ); // Verify a match, and that no context was specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { doc = (context ? context.ownerDocument || context : document); // If a single string is passed in and it's a single tag // just do a createElement and skip the rest ret = rsingleTag.exec( selector ); if ( ret ) { if ( jQuery.isPlainObject( context ) ) { selector = [ document.createElement( ret[1] ) ]; jQuery.fn.attr.call( selector, context, true ); } else { selector = [ doc.createElement( ret[1] ) ]; } } else { ret = buildFragment( [ match[1] ], [ doc ] ); selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes; } return jQuery.merge( this, selector ); // HANDLE: $("#id") } else { elem = document.getElementById( match[2] ); if ( elem ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $("TAG") } else if ( !context && /^\w+$/.test( selector ) ) { this.selector = selector; this.context = document; selector = document.getElementsByTagName( selector ); return jQuery.merge( this, selector ); // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return (context || rootjQuery).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return jQuery( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if (selector.selector !== undefined) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.4.2", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return slice.call( this, 0 ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this.slice(num)[ 0 ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = jQuery(); if ( jQuery.isArray( elems ) ) { push.apply( ret, elems ); } else { jQuery.merge( ret, elems ); } // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + (this.selector ? " " : "") + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Attach the listeners jQuery.bindReady(); // If the DOM is already ready if ( jQuery.isReady ) { // Execute the function immediately fn.call( document, jQuery ); // Otherwise, remember the function for later } else if ( readyList ) { // Add the function to the wait list readyList.push( fn ); } return this; }, eq: function( i ) { return i === -1 ? this.slice( i ) : this.slice( i, +i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ), "slice", slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || jQuery(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { // copy reference to target object var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging object literal values or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || jQuery.isArray(copy) ) ) { var clone = src && ( jQuery.isPlainObject(src) || jQuery.isArray(src) ) ? src : jQuery.isArray(copy) ? [] : {}; // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { window.$ = _$; if ( deep ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // Handle when the DOM is ready ready: function() { // Make sure that the DOM is not already loaded if ( !jQuery.isReady ) { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 13 ); } // Remember that the DOM is ready jQuery.isReady = true; // If there are functions bound, to execute if ( readyList ) { // Execute all of them var fn, i = 0; while ( (fn = readyList[ i++ ]) ) { fn.call( document, jQuery ); } // Reset the list of functions readyList = null; } // Trigger any bound ready events if ( jQuery.fn.triggerHandler ) { jQuery( document ).triggerHandler( "ready" ); } } }, bindReady: function() { if ( readyBound ) { return; } readyBound = true; // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { return jQuery.ready(); } // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else if ( document.attachEvent ) { // ensure firing before onload, // maybe late but safe also for iframes document.attachEvent("onreadystatechange", DOMContentLoaded); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var toplevel = false; try { toplevel = window.frameElement == null; } catch(e) {} if ( document.documentElement.doScroll && toplevel ) { doScrollCheck(); } } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return toString.call(obj) === "[object Function]"; }, isArray: function( obj ) { return toString.call(obj) === "[object Array]"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || toString.call(obj) !== "[object Object]" || obj.nodeType || obj.setInterval ) { return false; } // Not own constructor property must be Object if ( obj.constructor && !hasOwnProperty.call(obj, "constructor") && !hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || hasOwnProperty.call( obj, key ); }, isEmptyObject: function( obj ) { for ( var name in obj ) { return false; } return true; }, error: function( msg ) { throw msg; }, parseJSON: function( data ) { if ( typeof data !== "string" || !data ) { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@") .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]") .replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) { // Try to use the native JSON parser first return window.JSON && window.JSON.parse ? window.JSON.parse( data ) : (new Function("return " + data))(); } else { jQuery.error( "Invalid JSON: " + data ); } }, noop: function() {}, // Evalulates a script in a global context globalEval: function( data ) { if ( data && rnotwhite.test(data) ) { // Inspired by code by Andrea Giammarchi // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html var head = document.getElementsByTagName("head")[0] || document.documentElement, script = document.createElement("script"); script.type = "text/javascript"; if ( jQuery.support.scriptEval ) { script.appendChild( document.createTextNode( data ) ); } else { script.text = data; } // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709). head.insertBefore( script, head.firstChild ); head.removeChild( script ); } }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); }, // args is for internal usage only each: function( object, callback, args ) { var name, i = 0, length = object.length, isObj = length === undefined || jQuery.isFunction(object); if ( args ) { if ( isObj ) { for ( name in object ) { if ( callback.apply( object[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( object[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in object ) { if ( callback.call( object[ name ], name, object[ name ] ) === false ) { break; } } } else { for ( var value = object[0]; i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {} } } return object; }, trim: function( text ) { return (text || "").replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( array, results ) { var ret = results || []; if ( array != null ) { // The window, strings (and functions) also have 'length' // The extra typeof function check is to prevent crashes // in Safari 2 (See: #3039) if ( array.length == null || typeof array === "string" || jQuery.isFunction(array) || (typeof array !== "function" && array.setInterval) ) { push.call( ret, array ); } else { jQuery.merge( ret, array ); } } return ret; }, inArray: function( elem, array ) { if ( array.indexOf ) { return array.indexOf( elem ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === elem ) { return i; } } return -1; }, merge: function( first, second ) { var i = first.length, j = 0; if ( typeof second.length === "number" ) { for ( var l = second.length; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var ret = []; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, length = elems.length; i < length; i++ ) { if ( !inv !== !callback( elems[ i ], i ) ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var ret = [], value; // Go through the array, translating each of the items to their // new value (or values). for ( var i = 0, length = elems.length; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, proxy: function( fn, proxy, thisObject ) { if ( arguments.length === 2 ) { if ( typeof proxy === "string" ) { thisObject = fn; fn = thisObject[ proxy ]; proxy = undefined; } else if ( proxy && !jQuery.isFunction( proxy ) ) { thisObject = proxy; proxy = undefined; } } if ( !proxy && fn ) { proxy = function() { return fn.apply( thisObject || this, arguments ); }; } // Set the guid of unique handler to the same of original handler, so it can be removed if ( fn ) { proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; } // So proxy can be declared as an argument return proxy; }, // Use of jQuery.browser is frowned upon. // More details: http://docs.jquery.com/Utilities/jQuery.browser uaMatch: function( ua ) { ua = ua.toLowerCase(); var match = /(webkit)[ \/]([\w.]+)/.exec( ua ) || /(opera)(?:.*version)?[ \/]([\w.]+)/.exec( ua ) || /(msie) ([\w.]+)/.exec( ua ) || !/compatible/.test( ua ) && /(mozilla)(?:.*? rv:([\w.]+))?/.exec( ua ) || []; return { browser: match[1] || "", version: match[2] || "0" }; }, browser: {} }); browserMatch = jQuery.uaMatch( userAgent ); if ( browserMatch.browser ) { jQuery.browser[ browserMatch.browser ] = true; jQuery.browser.version = browserMatch.version; } // Deprecated, use jQuery.browser.webkit instead if ( jQuery.browser.webkit ) { jQuery.browser.safari = true; } if ( indexOf ) { jQuery.inArray = function( elem, array ) { return indexOf.call( array, elem ); }; } // All jQuery objects should point back to these rootjQuery = jQuery(document); // Cleanup functions for the document ready method if ( document.addEventListener ) { DOMContentLoaded = function() { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); }; } else if ( document.attachEvent ) { DOMContentLoaded = function() { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }; } // The DOM ready check for Internet Explorer function doScrollCheck() { if ( jQuery.isReady ) { return; } try { // If IE is used, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); } catch( error ) { setTimeout( doScrollCheck, 1 ); return; } // and execute any waiting functions jQuery.ready(); } function evalScript( i, elem ) { if ( elem.src ) { jQuery.ajax({ url: elem.src, async: false, dataType: "script" }); } else { jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } // Mutifunctional method to get and set values to a collection // The value/s can be optionally by executed if its a function function access( elems, key, value, exec, fn, pass ) { var length = elems.length; // Setting many attributes if ( typeof key === "object" ) { for ( var k in key ) { access( elems, k, key[k], exec, fn, value ); } return elems; } // Setting one attribute if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = !pass && exec && jQuery.isFunction(value); for ( var i = 0; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } return elems; } // Getting an attribute return length ? fn( elems[0], key ) : undefined; } function now() { return (new Date).getTime(); } (function() { jQuery.support = {}; var root = document.documentElement, script = document.createElement("script"), div = document.createElement("div"), id = "script" + now(); div.style.display = "none"; div.innerHTML = " <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; var all = div.getElementsByTagName("*"), a = div.getElementsByTagName("a")[0]; // Can't get basic test support if ( !all || !all.length || !a ) { return; } jQuery.support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: div.firstChild.nodeType === 3, // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText insted) style: /red/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: a.getAttribute("href") === "/a", // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.55$/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: div.getElementsByTagName("input")[0].value === "on", // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: document.createElement("select").appendChild( document.createElement("option") ).selected, parentNode: div.removeChild( div.appendChild( document.createElement("div") ) ).parentNode === null, // Will be defined later deleteExpando: true, checkClone: false, scriptEval: false, noCloneEvent: true, boxModel: null }; script.type = "text/javascript"; try { script.appendChild( document.createTextNode( "window." + id + "=1;" ) ); } catch(e) {} root.insertBefore( script, root.firstChild ); // Make sure that the execution of code works by injecting a script // tag with appendChild/createTextNode // (IE doesn't support this, fails, and uses .text instead) if ( window[ id ] ) { jQuery.support.scriptEval = true; delete window[ id ]; } // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete script.test; } catch(e) { jQuery.support.deleteExpando = false; } root.removeChild( script ); if ( div.attachEvent && div.fireEvent ) { div.attachEvent("onclick", function click() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) jQuery.support.noCloneEvent = false; div.detachEvent("onclick", click); }); div.cloneNode(true).fireEvent("onclick"); } div = document.createElement("div"); div.innerHTML = "<input type='radio' name='radiotest' checked='checked'/>"; var fragment = document.createDocumentFragment(); fragment.appendChild( div.firstChild ); // WebKit doesn't clone checked state correctly in fragments jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked; // Figure out if the W3C box model works as expected // document.body must exist before we can do this jQuery(function() { var div = document.createElement("div"); div.style.width = div.style.paddingLeft = "1px"; document.body.appendChild( div ); jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2; document.body.removeChild( div ).style.display = 'none'; div = null; }); // Technique from Juriy Zaytsev // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ var eventSupported = function( eventName ) { var el = document.createElement("div"); eventName = "on" + eventName; var isSupported = (eventName in el); if ( !isSupported ) { el.setAttribute(eventName, "return;"); isSupported = typeof el[eventName] === "function"; } el = null; return isSupported; }; jQuery.support.submitBubbles = eventSupported("submit"); jQuery.support.changeBubbles = eventSupported("change"); // release memory in IE root = script = div = all = a = null; })(); jQuery.props = { "for": "htmlFor", "class": "className", readonly: "readOnly", maxlength: "maxLength", cellspacing: "cellSpacing", rowspan: "rowSpan", colspan: "colSpan", tabindex: "tabIndex", usemap: "useMap", frameborder: "frameBorder" }; var expando = "jQuery" + now(), uuid = 0, windowData = {}; jQuery.extend({ cache: {}, expando:expando, // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, "object": true, "applet": true }, data: function( elem, name, data ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { return; } elem = elem == window ? windowData : elem; var id = elem[ expando ], cache = jQuery.cache, thisCache; if ( !id && typeof name === "string" && data === undefined ) { return null; } // Compute a unique ID for the element if ( !id ) { id = ++uuid; } // Avoid generating a new cache unless none exists and we // want to manipulate it. if ( typeof name === "object" ) { elem[ expando ] = id; thisCache = cache[ id ] = jQuery.extend(true, {}, name); } else if ( !cache[ id ] ) { elem[ expando ] = id; cache[ id ] = {}; } thisCache = cache[ id ]; // Prevent overriding the named cache with undefined values if ( data !== undefined ) { thisCache[ name ] = data; } return typeof name === "string" ? thisCache[ name ] : thisCache; }, removeData: function( elem, name ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { return; } elem = elem == window ? windowData : elem; var id = elem[ expando ], cache = jQuery.cache, thisCache = cache[ id ]; // If we want to remove a specific section of the element's data if ( name ) { if ( thisCache ) { // Remove the section of cache data delete thisCache[ name ]; // If we've removed all the data, remove the element's cache if ( jQuery.isEmptyObject(thisCache) ) { jQuery.removeData( elem ); } } // Otherwise, we want to remove all of the element's data } else { if ( jQuery.support.deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } // Completely remove the data cache delete cache[ id ]; } } }); jQuery.fn.extend({ data: function( key, value ) { if ( typeof key === "undefined" && this.length ) { return jQuery.data( this[0] ); } else if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } var parts = key.split("."); parts[1] = parts[1] ? "." + parts[1] : ""; if ( value === undefined ) { var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); if ( data === undefined && this.length ) { data = jQuery.data( this[0], key ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } else { return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function() { jQuery.data( this, key, value ); }); } }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { if ( !elem ) { return; } type = (type || "fx") + "queue"; var q = jQuery.data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( !data ) { return q || []; } if ( !q || jQuery.isArray(data) ) { q = jQuery.data( elem, type, jQuery.makeArray(data) ); } else { q.push( data ); } return q; }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), fn = queue.shift(); // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift("inprogress"); } fn.call(elem, function() { jQuery.dequeue(elem, type); }); } } }); jQuery.fn.extend({ queue: function( type, data ) { if ( typeof type !== "string" ) { data = type; type = "fx"; } if ( data === undefined ) { return jQuery.queue( this[0], type ); } return this.each(function( i, elem ) { var queue = jQuery.queue( this, type, data ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; type = type || "fx"; return this.queue( type, function() { var elem = this; setTimeout(function() { jQuery.dequeue( elem, type ); }, time ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); } }); var rclass = /[\n\t]/g, rspace = /\s+/, rreturn = /\r/g, rspecialurl = /href|src|style/, rtype = /(button|input)/i, rfocusable = /(button|input|object|select|textarea)/i, rclickable = /^(a|area)$/i, rradiocheck = /radio|checkbox/; jQuery.fn.extend({ attr: function( name, value ) { return access( this, name, value, true, jQuery.attr ); }, removeAttr: function( name, fn ) { return this.each(function(){ jQuery.attr( this, name, "" ); if ( this.nodeType === 1 ) { this.removeAttribute( name ); } }); }, addClass: function( value ) { if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); self.addClass( value.call(this, i, self.attr("class")) ); }); } if ( value && typeof value === "string" ) { var classNames = (value || "").split( rspace ); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 ) { if ( !elem.className ) { elem.className = value; } else { var className = " " + elem.className + " ", setClass = elem.className; for ( var c = 0, cl = classNames.length; c < cl; c++ ) { if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) { setClass += " " + classNames[c]; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); self.removeClass( value.call(this, i, self.attr("class")) ); }); } if ( (value && typeof value === "string") || value === undefined ) { var classNames = (value || "").split(rspace); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { var className = (" " + elem.className + " ").replace(rclass, " "); for ( var c = 0, cl = classNames.length; c < cl; c++ ) { className = className.replace(" " + classNames[c] + " ", " "); } elem.className = jQuery.trim( className ); } else { elem.className = ""; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this); self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery(this), state = stateVal, classNames = value.split( rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space seperated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery.data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery.data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " "; for ( var i = 0, l = this.length; i < l; i++ ) { if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { return true; } } return false; }, val: function( value ) { if ( value === undefined ) { var elem = this[0]; if ( elem ) { if ( jQuery.nodeName( elem, "option" ) ) { return (elem.attributes.value || {}).specified ? elem.value : elem.text; } // We need to handle select boxes special if ( jQuery.nodeName( elem, "select" ) ) { var index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one"; // Nothing was selected if ( index < 0 ) { return null; } // Loop through all the selected options for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { var option = options[ i ]; if ( option.selected ) { // Get the specifc value for the option value = jQuery(option).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; } // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) { return elem.getAttribute("value") === null ? "on" : elem.value; } // Everything else, we just grab the value return (elem.value || "").replace(rreturn, ""); } return undefined; } var isFunction = jQuery.isFunction(value); return this.each(function(i) { var self = jQuery(this), val = value; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call(this, i, self.val()); } // Typecast each time if the value is a Function and the appended // value is therefore different each time. if ( typeof val === "number" ) { val += ""; } if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) { this.checked = jQuery.inArray( self.val(), val ) >= 0; } else if ( jQuery.nodeName( this, "select" ) ) { var values = jQuery.makeArray(val); jQuery( "option", this ).each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { this.selectedIndex = -1; } } else { this.value = val; } }); } }); jQuery.extend({ attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, attr: function( elem, name, value, pass ) { // don't set attributes on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { return undefined; } if ( pass && name in jQuery.attrFn ) { return jQuery(elem)[name](value); } var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ), // Whether we are setting (or getting) set = value !== undefined; // Try to normalize/fix the name name = notxml && jQuery.props[ name ] || name; // Only do all the following if this is a node (faster for style) if ( elem.nodeType === 1 ) { // These attributes require special treatment var special = rspecialurl.test( name ); // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( name === "selected" && !jQuery.support.optSelected ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } // If applicable, access the attribute via the DOM 0 way if ( name in elem && notxml && !special ) { if ( set ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } elem[ name ] = value; } // browsers index elements by id/name on forms, give priority to attributes. if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) { return elem.getAttributeNode( name ).nodeValue; } // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ if ( name === "tabIndex" ) { var attributeNode = elem.getAttributeNode( "tabIndex" ); return attributeNode && attributeNode.specified ? attributeNode.value : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } return elem[ name ]; } if ( !jQuery.support.style && notxml && name === "style" ) { if ( set ) { elem.style.cssText = "" + value; } return elem.style.cssText; } if ( set ) { // convert the value to a string (all browsers do this but IE) see #1070 elem.setAttribute( name, "" + value ); } var attr = !jQuery.support.hrefNormalized && notxml && special ? // Some attributes require a special call on IE elem.getAttribute( name, 2 ) : elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return attr === null ? undefined : attr; } // elem is actually elem.style ... set the style // Using attr for specific style information is now deprecated. Use style instead. return jQuery.style( elem, name, value ); } }); var rnamespaces = /\.(.*)$/, fcleanup = function( nm ) { return nm.replace(/[^\w\s\.\|`]/g, function( ch ) { return "\\" + ch; }); }; /* * A number of helper functions used for managing events. * Many of the ideas behind this code originated from * Dean Edwards' addEvent library. */ jQuery.event = { // Bind an event to an element // Original by Dean Edwards add: function( elem, types, handler, data ) { if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // For whatever reason, IE has trouble passing the window object // around, causing it to be cloned in the process if ( elem.setInterval && ( elem !== window && !elem.frameElement ) ) { elem = window; } var handleObjIn, handleObj; if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; } // Make sure that the function being executed has a unique ID if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure var elemData = jQuery.data( elem ); // If no elemData is found then we must be trying to bind to one of the // banned noData elements if ( !elemData ) { return; } var events = elemData.events = elemData.events || {}, eventHandle = elemData.handle, eventHandle; if ( !eventHandle ) { elemData.handle = eventHandle = function() { // Handle the second event of a trigger and when // an event is called after a page has unloaded return typeof jQuery !== "undefined" && !jQuery.event.triggered ? jQuery.event.handle.apply( eventHandle.elem, arguments ) : undefined; }; } // Add elem as a property of the handle function // This is to prevent a memory leak with non-native events in IE. eventHandle.elem = elem; // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = types.split(" "); var type, i = 0, namespaces; while ( (type = types[ i++ ]) ) { handleObj = handleObjIn ? jQuery.extend({}, handleObjIn) : { handler: handler, data: data }; // Namespaced event handlers if ( type.indexOf(".") > -1 ) { namespaces = type.split("."); type = namespaces.shift(); handleObj.namespace = namespaces.slice(0).sort().join("."); } else { namespaces = []; handleObj.namespace = ""; } handleObj.type = type; handleObj.guid = handler.guid; // Get the current list of functions bound to this event var handlers = events[ type ], special = jQuery.event.special[ type ] || {}; // Init the event handler queue if ( !handlers ) { handlers = events[ type ] = []; // Check for a special event handler // Only use addEventListener/attachEvent if the special // events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add the function to the element's handler list handlers.push( handleObj ); // Keep track of which events have been used, for global triggering jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, pos ) { // don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } var ret, type, fn, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType, elemData = jQuery.data( elem ), events = elemData && elemData.events; if ( !elemData || !events ) { return; } // types is actually an event object here if ( types && types.type ) { handler = types.handler; types = types.type; } // Unbind all events for the element if ( !types || typeof types === "string" && types.charAt(0) === "." ) { types = types || ""; for ( type in events ) { jQuery.event.remove( elem, type + types ); } return; } // Handle multiple events separated by a space // jQuery(...).unbind("mouseover mouseout", fn); types = types.split(" "); while ( (type = types[ i++ ]) ) { origType = type; handleObj = null; all = type.indexOf(".") < 0; namespaces = []; if ( !all ) { // Namespaced event handlers namespaces = type.split("."); type = namespaces.shift(); namespace = new RegExp("(^|\\.)" + jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)") } eventType = events[ type ]; if ( !eventType ) { continue; } if ( !handler ) { for ( var j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( all || namespace.test( handleObj.namespace ) ) { jQuery.event.remove( elem, origType, handleObj.handler, j ); eventType.splice( j--, 1 ); } } continue; } special = jQuery.event.special[ type ] || {}; for ( var j = pos || 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( handler.guid === handleObj.guid ) { // remove the given handler for the given type if ( all || namespace.test( handleObj.namespace ) ) { if ( pos == null ) { eventType.splice( j--, 1 ); } if ( special.remove ) { special.remove.call( elem, handleObj ); } } if ( pos != null ) { break; } } } // remove generic event handler if no more handlers exist if ( eventType.length === 0 || pos != null && eventType.length === 1 ) { if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { removeEvent( elem, type, elemData.handle ); } ret = null; delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { var handle = elemData.handle; if ( handle ) { handle.elem = null; } delete elemData.events; delete elemData.handle; if ( jQuery.isEmptyObject( elemData ) ) { jQuery.removeData( elem ); } } }, // bubbling is internal trigger: function( event, data, elem /*, bubbling */ ) { // Event object or event type var type = event.type || event, bubbling = arguments[3]; if ( !bubbling ) { event = typeof event === "object" ? // jQuery.Event object event[expando] ? event : // Object literal jQuery.extend( jQuery.Event(type), event ) : // Just the event type (string) jQuery.Event(type); if ( type.indexOf("!") >= 0 ) { event.type = type = type.slice(0, -1); event.exclusive = true; } // Handle a global trigger if ( !elem ) { // Don't bubble custom events when global (to avoid too much overhead) event.stopPropagation(); // Only trigger if we've ever bound an event for it if ( jQuery.event.global[ type ] ) { jQuery.each( jQuery.cache, function() { if ( this.events && this.events[type] ) { jQuery.event.trigger( event, data, this.handle.elem ); } }); } } // Handle triggering a single element // don't do events on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { return undefined; } // Clean up in case it is reused event.result = undefined; event.target = elem; // Clone the incoming data, if any data = jQuery.makeArray( data ); data.unshift( event ); } event.currentTarget = elem; // Trigger the event, it is assumed that "handle" is a function var handle = jQuery.data( elem, "handle" ); if ( handle ) { handle.apply( elem, data ); } var parent = elem.parentNode || elem.ownerDocument; // Trigger an inline bound script try { if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) { if ( elem[ "on" + type ] && elem[ "on" + type ].apply( elem, data ) === false ) { event.result = false; } } // prevent IE from throwing an error for some elements with some event types, see #3533 } catch (e) {} if ( !event.isPropagationStopped() && parent ) { jQuery.event.trigger( event, data, parent, true ); } else if ( !event.isDefaultPrevented() ) { var target = event.target, old, isClick = jQuery.nodeName(target, "a") && type === "click", special = jQuery.event.special[ type ] || {}; if ( (!special._default || special._default.call( elem, event ) === false) && !isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) { try { if ( target[ type ] ) { // Make sure that we don't accidentally re-trigger the onFOO events old = target[ "on" + type ]; if ( old ) { target[ "on" + type ] = null; } jQuery.event.triggered = true; target[ type ](); } // prevent IE from throwing an error for some elements with some event types, see #3533 } catch (e) {} if ( old ) { target[ "on" + type ] = old; } jQuery.event.triggered = false; } } }, handle: function( event ) { var all, handlers, namespaces, namespace, events; event = arguments[0] = jQuery.event.fix( event || window.event ); event.currentTarget = this; // Namespaced event handlers all = event.type.indexOf(".") < 0 && !event.exclusive; if ( !all ) { namespaces = event.type.split("."); event.type = namespaces.shift(); namespace = new RegExp("(^|\\.)" + namespaces.slice(0).sort().join("\\.(?:.*\\.)?") + "(\\.|$)"); } var events = jQuery.data(this, "events"), handlers = events[ event.type ]; if ( events && handlers ) { // Clone the handlers to prevent manipulation handlers = handlers.slice(0); for ( var j = 0, l = handlers.length; j < l; j++ ) { var handleObj = handlers[ j ]; // Filter the functions by class if ( all || namespace.test( handleObj.namespace ) ) { // Pass in a reference to the handler function itself // So that we can later remove it event.handler = handleObj.handler; event.data = handleObj.data; event.handleObj = handleObj; var ret = handleObj.handler.apply( this, arguments ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } if ( event.isImmediatePropagationStopped() ) { break; } } } } return event.result; }, props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), fix: function( event ) { if ( event[ expando ] ) { return event; } // store a copy of the original event object // and "clone" to set read-only properties var originalEvent = event; event = jQuery.Event( originalEvent ); for ( var i = this.props.length, prop; i; ) { prop = this.props[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary if ( !event.target ) { event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either } // check if target is a textnode (safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Add relatedTarget, if necessary if ( !event.relatedTarget && event.fromElement ) { event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; } // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && event.clientX != null ) { var doc = document.documentElement, body = document.body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Add which for key events if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) ) { event.which = event.charCode || event.keyCode; } // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) if ( !event.metaKey && event.ctrlKey ) { event.metaKey = event.ctrlKey; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && event.button !== undefined ) { event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); } return event; }, // Deprecated, use jQuery.guid instead guid: 1E8, // Deprecated, use jQuery.proxy instead proxy: jQuery.proxy, special: { ready: { // Make sure the ready event is setup setup: jQuery.bindReady, teardown: jQuery.noop }, live: { add: function( handleObj ) { jQuery.event.add( this, handleObj.origType, jQuery.extend({}, handleObj, {handler: liveHandler}) ); }, remove: function( handleObj ) { var remove = true, type = handleObj.origType.replace(rnamespaces, ""); jQuery.each( jQuery.data(this, "events").live || [], function() { if ( type === this.origType.replace(rnamespaces, "") ) { remove = false; return false; } }); if ( remove ) { jQuery.event.remove( this, handleObj.origType, liveHandler ); } } }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( this.setInterval ) { this.onbeforeunload = eventHandle; } return false; }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } } }; var removeEvent = document.removeEventListener ? function( elem, type, handle ) { elem.removeEventListener( type, handle, false ); } : function( elem, type, handle ) { elem.detachEvent( "on" + type, handle ); }; jQuery.Event = function( src ) { // Allow instantiation without the 'new' keyword if ( !this.preventDefault ) { return new jQuery.Event( src ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Event type } else { this.type = src; } // timeStamp is buggy for some events on Firefox(#3843) // So we won't rely on the native value this.timeStamp = now(); // Mark it as fixed this[ expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); } // otherwise set the returnValue property of the original event to false (IE) e.returnValue = false; }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Checks if an event happened on an element within another element // Used in jQuery.event.special.mouseenter and mouseleave handlers var withinElement = function( event ) { // Check if mouse(over|out) are still within the same parent element var parent = event.relatedTarget; // Firefox sometimes assigns relatedTarget a XUL element // which we cannot access the parentNode property of try { // Traverse up the tree while ( parent && parent !== this ) { parent = parent.parentNode; } if ( parent !== this ) { // set the correct event type event.type = event.data; // handle event if we actually just moused on to a non sub-element jQuery.event.handle.apply( this, arguments ); } // assuming we've left the element since we most likely mousedover a xul element } catch(e) { } }, // In case of event delegation, we only need to rename the event.type, // liveHandler will take care of the rest. delegate = function( event ) { event.type = event.data; jQuery.event.handle.apply( this, arguments ); }; // Create mouseenter and mouseleave events jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { setup: function( data ) { jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig ); }, teardown: function( data ) { jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement ); } }; }); // submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function( data, namespaces ) { if ( this.nodeName.toLowerCase() !== "form" ) { jQuery.event.add(this, "click.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { return trigger( "submit", this, arguments ); } }); jQuery.event.add(this, "keypress.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { return trigger( "submit", this, arguments ); } }); } else { return false; } }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialSubmit" ); } }; } // change delegation, happens here so we have bind. if ( !jQuery.support.changeBubbles ) { var formElems = /textarea|input|select/i, changeFilters, getVal = function( elem ) { var type = elem.type, val = elem.value; if ( type === "radio" || type === "checkbox" ) { val = elem.checked; } else if ( type === "select-multiple" ) { val = elem.selectedIndex > -1 ? jQuery.map( elem.options, function( elem ) { return elem.selected; }).join("-") : ""; } else if ( elem.nodeName.toLowerCase() === "select" ) { val = elem.selectedIndex; } return val; }, testChange = function testChange( e ) { var elem = e.target, data, val; if ( !formElems.test( elem.nodeName ) || elem.readOnly ) { return; } data = jQuery.data( elem, "_change_data" ); val = getVal(elem); // the current data will be also retrieved by beforeactivate if ( e.type !== "focusout" || elem.type !== "radio" ) { jQuery.data( elem, "_change_data", val ); } if ( data === undefined || val === data ) { return; } if ( data != null || val ) { e.type = "change"; return jQuery.event.trigger( e, arguments[1], elem ); } }; jQuery.event.special.change = { filters: { focusout: testChange, click: function( e ) { var elem = e.target, type = elem.type; if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) { return testChange.call( this, e ); } }, // Change has to be called before submit // Keydown will be called before keypress, which is used in submit-event delegation keydown: function( e ) { var elem = e.target, type = elem.type; if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") || (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || type === "select-multiple" ) { return testChange.call( this, e ); } }, // Beforeactivate happens also before the previous element is blurred // with this event you can't trigger a change event, but you can store // information/focus[in] is not needed anymore beforeactivate: function( e ) { var elem = e.target; jQuery.data( elem, "_change_data", getVal(elem) ); } }, setup: function( data, namespaces ) { if ( this.type === "file" ) { return false; } for ( var type in changeFilters ) { jQuery.event.add( this, type + ".specialChange", changeFilters[type] ); } return formElems.test( this.nodeName ); }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialChange" ); return formElems.test( this.nodeName ); } }; changeFilters = jQuery.event.special.change.filters; } function trigger( type, elem, args ) { args[0].type = type; return jQuery.event.handle.apply( elem, args ); } // Create "bubbling" focus and blur events if ( document.addEventListener ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { jQuery.event.special[ fix ] = { setup: function() { this.addEventListener( orig, handler, true ); }, teardown: function() { this.removeEventListener( orig, handler, true ); } }; function handler( e ) { e = jQuery.event.fix( e ); e.type = fix; return jQuery.event.handle.call( this, e ); } }); } jQuery.each(["bind", "one"], function( i, name ) { jQuery.fn[ name ] = function( type, data, fn ) { // Handle object literals if ( typeof type === "object" ) { for ( var key in type ) { this[ name ](key, data, type[key], fn); } return this; } if ( jQuery.isFunction( data ) ) { fn = data; data = undefined; } var handler = name === "one" ? jQuery.proxy( fn, function( event ) { jQuery( this ).unbind( event, handler ); return fn.apply( this, arguments ); }) : fn; if ( type === "unload" && name !== "one" ) { this.one( type, data, fn ); } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.add( this[i], type, handler, data ); } } return this; }; }); jQuery.fn.extend({ unbind: function( type, fn ) { // Handle object literals if ( typeof type === "object" && !type.preventDefault ) { for ( var key in type ) { this.unbind(key, type[key]); } } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.remove( this[i], type, fn ); } } return this; }, delegate: function( selector, types, data, fn ) { return this.live( types, data, fn, selector ); }, undelegate: function( selector, types, fn ) { if ( arguments.length === 0 ) { return this.unbind( "live" ); } else { return this.die( types, null, fn, selector ); } }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { var event = jQuery.Event( type ); event.preventDefault(); event.stopPropagation(); jQuery.event.trigger( event, data, this[0] ); return event.result; } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, i = 1; // link all the functions, so any of them can unbind this click handler while ( i < args.length ) { jQuery.proxy( fn, args[ i++ ] ); } return this.click( jQuery.proxy( fn, function( event ) { // Figure out which function to execute var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; })); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); var liveMap = { focus: "focusin", blur: "focusout", mouseenter: "mouseover", mouseleave: "mouseout" }; jQuery.each(["live", "die"], function( i, name ) { jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) { var type, i = 0, match, namespaces, preType, selector = origSelector || this.selector, context = origSelector ? this : jQuery( this.context ); if ( jQuery.isFunction( data ) ) { fn = data; data = undefined; } types = (types || "").split(" "); while ( (type = types[ i++ ]) != null ) { match = rnamespaces.exec( type ); namespaces = ""; if ( match ) { namespaces = match[0]; type = type.replace( rnamespaces, "" ); } if ( type === "hover" ) { types.push( "mouseenter" + namespaces, "mouseleave" + namespaces ); continue; } preType = type; if ( type === "focus" || type === "blur" ) { types.push( liveMap[ type ] + namespaces ); type = type + namespaces; } else { type = (liveMap[ type ] || type) + namespaces; } if ( name === "live" ) { // bind live handler context.each(function(){ jQuery.event.add( this, liveConvert( type, selector ), { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } ); }); } else { // unbind live handler context.unbind( liveConvert( type, selector ), fn ); } } return this; } }); function liveHandler( event ) { var stop, elems = [], selectors = [], args = arguments, related, match, handleObj, elem, j, i, l, data, events = jQuery.data( this, "events" ); // Make sure we avoid non-left-click bubbling in Firefox (#3861) if ( event.liveFired === this || !events || !events.live || event.button && event.type === "click" ) { return; } event.liveFired = this; var live = events.live.slice(0); for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) { selectors.push( handleObj.selector ); } else { live.splice( j--, 1 ); } } match = jQuery( event.target ).closest( selectors, event.currentTarget ); for ( i = 0, l = match.length; i < l; i++ ) { for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( match[i].selector === handleObj.selector ) { elem = match[i].elem; related = null; // Those two events require additional checking if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) { related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0]; } if ( !related || related !== elem ) { elems.push({ elem: elem, handleObj: handleObj }); } } } } for ( i = 0, l = elems.length; i < l; i++ ) { match = elems[i]; event.currentTarget = match.elem; event.data = match.handleObj.data; event.handleObj = match.handleObj; if ( match.handleObj.origHandler.apply( match.elem, args ) === false ) { stop = false; break; } } return stop; } function liveConvert( type, selector ) { return "live." + (type && type !== "*" ? type + "." : "") + selector.replace(/\./g, "`").replace(/ /g, "&"); } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( fn ) { return fn ? this.bind( name, fn ) : this.trigger( name ); }; if ( jQuery.attrFn ) { jQuery.attrFn[ name ] = true; } }); // Prevent memory leaks in IE // Window isn't included so as not to unbind existing unload events // More info: // - http://isaacschlueter.com/2006/10/msie-memory-leaks/ if ( window.attachEvent && !window.addEventListener ) { window.attachEvent("onunload", function() { for ( var id in jQuery.cache ) { if ( jQuery.cache[ id ].handle ) { // Try/Catch is to handle iframes being unloaded, see #4280 try { jQuery.event.remove( jQuery.cache[ id ].handle.elem ); } catch(e) {} } } }); } /*! * Sizzle CSS Selector Engine - v1.0 * Copyright 2009, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true; // Here we check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function(){ baseHasDuplicate = false; return 0; }); var Sizzle = function(selector, context, results, seed) { results = results || []; var origContext = context = context || document; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var parts = [], m, set, checkSet, extra, prune = true, contextXML = isXML(context), soFar = selector; // Reset the position of the chunker regexp (start from head) while ( (chunker.exec(""), m = chunker.exec(soFar)) !== null ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) { selector += parts.shift(); } set = posProcess( selector, set ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { var ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { var ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray(set); } else { prune = false; } while ( parts.length ) { var cur = parts.pop(), pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { Sizzle.error( cur || selector ); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( var i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( var i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { Sizzle( extra, origContext, results, seed ); Sizzle.uniqueSort( results ); } return results; }; Sizzle.uniqueSort = function(results){ if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort(sortOrder); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[i-1] ) { results.splice(i--, 1); } } } } return results; }; Sizzle.matches = function(expr, set){ return Sizzle(expr, null, null, set); }; Sizzle.find = function(expr, context, isXML){ var set, match; if ( !expr ) { return []; } for ( var i = 0, l = Expr.order.length; i < l; i++ ) { var type = Expr.order[i], match; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { var left = match[1]; match.splice(1,1); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace(/\\/g, ""); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = context.getElementsByTagName("*"); } return {set: set, expr: expr}; }; Sizzle.filter = function(expr, set, inplace, not){ var old = expr, result = [], curLoop = set, match, anyFound, isXMLFilter = set && set[0] && isXML(set[0]); while ( expr && set.length ) { for ( var type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { var filter = Expr.filter[ type ], found, item, left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( var i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); var pass = not ^ !!found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr === old ) { if ( anyFound == null ) { Sizzle.error( expr ); } else { break; } } old = expr; } return curLoop; }; Sizzle.error = function( msg ) { throw "Syntax error, unrecognized expression: " + msg; }; var Expr = Sizzle.selectors = { order: [ "ID", "NAME", "TAG" ], match: { ID: /#((?:[\w\u00c0-\uFFFF-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function(elem){ return elem.getAttribute("href"); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !/\W/.test(part), isPartStrNotTag = isPartStr && !isTag; if ( isTag ) { part = part.toLowerCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function(checkSet, part){ var isPartStr = typeof part === "string"; if ( isPartStr && !/\W/.test(part) ) { part = part.toLowerCase(); for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { Sizzle.filter( part, checkSet, true ); } } }, "": function(checkSet, part, isXML){ var doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !/\W/.test(part) ) { var nodeCheck = part = part.toLowerCase(); checkFn = dirNodeCheck; } checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML); }, "~": function(checkSet, part, isXML){ var doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !/\W/.test(part) ) { var nodeCheck = part = part.toLowerCase(); checkFn = dirNodeCheck; } checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML); } }, find: { ID: function(match, context, isXML){ if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? [m] : []; } }, NAME: function(match, context){ if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName(match[1]); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, TAG: function(match, context){ return context.getElementsByTagName(match[1]); } }, preFilter: { CLASS: function(match, curLoop, inplace, result, not, isXML){ match = " " + match[1].replace(/\\/g, "") + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function(match){ return match[1].replace(/\\/g, ""); }, TAG: function(match, curLoop){ return match[1].toLowerCase(); }, CHILD: function(match){ if ( match[1] === "nth" ) { // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec( match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function(match, curLoop, inplace, result, not, isXML){ var name = match[1].replace(/\\/g, ""); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function(match, curLoop, inplace, result, not){ if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = Sizzle(match[3], null, null, curLoop); } else { var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function(match){ match.unshift( true ); return match; } }, filters: { enabled: function(elem){ return elem.disabled === false && elem.type !== "hidden"; }, disabled: function(elem){ return elem.disabled === true; }, checked: function(elem){ return elem.checked === true; }, selected: function(elem){ // Accessing this property makes selected-by-default // options in Safari work properly elem.parentNode.selectedIndex; return elem.selected === true; }, parent: function(elem){ return !!elem.firstChild; }, empty: function(elem){ return !elem.firstChild; }, has: function(elem, i, match){ return !!Sizzle( match[3], elem ).length; }, header: function(elem){ return /h\d/i.test( elem.nodeName ); }, text: function(elem){ return "text" === elem.type; }, radio: function(elem){ return "radio" === elem.type; }, checkbox: function(elem){ return "checkbox" === elem.type; }, file: function(elem){ return "file" === elem.type; }, password: function(elem){ return "password" === elem.type; }, submit: function(elem){ return "submit" === elem.type; }, image: function(elem){ return "image" === elem.type; }, reset: function(elem){ return "reset" === elem.type; }, button: function(elem){ return "button" === elem.type || elem.nodeName.toLowerCase() === "button"; }, input: function(elem){ return /input|select|textarea|button/i.test(elem.nodeName); } }, setFilters: { first: function(elem, i){ return i === 0; }, last: function(elem, i, match, array){ return i === array.length - 1; }, even: function(elem, i){ return i % 2 === 0; }, odd: function(elem, i){ return i % 2 === 1; }, lt: function(elem, i, match){ return i < match[3] - 0; }, gt: function(elem, i, match){ return i > match[3] - 0; }, nth: function(elem, i, match){ return match[3] - 0 === i; }, eq: function(elem, i, match){ return match[3] - 0 === i; } }, filter: { PSEUDO: function(elem, match, i, array){ var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var i = 0, l = not.length; i < l; i++ ) { if ( not[i] === elem ) { return false; } } return true; } else { Sizzle.error( "Syntax error, unrecognized expression: " + name ); } }, CHILD: function(elem, match){ var type = match[1], node = elem; switch (type) { case 'only': case 'first': while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; case 'last': while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case 'nth': var first = match[2], last = match[3]; if ( first === 1 && last === 0 ) { return true; } var doneName = match[0], parent = elem.parentNode; if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { var count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent.sizcache = doneName; } var diff = elem.nodeIndex - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } } }, ID: function(elem, match){ return elem.nodeType === 1 && elem.getAttribute("id") === match; }, TAG: function(elem, match){ return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; }, CLASS: function(elem, match){ return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function(elem, match){ var name = match[1], result = Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value !== check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function(elem, match, i, array){ var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, function(all, num){ return "\\" + (num - 0 + 1); })); } var makeArray = function(array, results) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. // Also verifies that the returned array holds DOM nodes // (which is not the case in the Blackberry browser) try { Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; // Provide a fallback method if it does not work } catch(e){ makeArray = function(array, results) { var ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var i = 0, l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( var i = 0; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { if ( a == b ) { hasDuplicate = true; } return a.compareDocumentPosition ? -1 : 1; } var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1; if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } else if ( "sourceIndex" in document.documentElement ) { sortOrder = function( a, b ) { if ( !a.sourceIndex || !b.sourceIndex ) { if ( a == b ) { hasDuplicate = true; } return a.sourceIndex ? -1 : 1; } var ret = a.sourceIndex - b.sourceIndex; if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } else if ( document.createRange ) { sortOrder = function( a, b ) { if ( !a.ownerDocument || !b.ownerDocument ) { if ( a == b ) { hasDuplicate = true; } return a.ownerDocument ? -1 : 1; } var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange(); aRange.setStart(a, 0); aRange.setEnd(a, 0); bRange.setStart(b, 0); bRange.setEnd(b, 0); var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange); if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } // Utility function for retreiving the text value of an array of DOM nodes function getText( elems ) { var ret = "", elem; for ( var i = 0; elems[i]; i++ ) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if ( elem.nodeType === 3 || elem.nodeType === 4 ) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if ( elem.nodeType !== 8 ) { ret += getText( elem.childNodes ); } } return ret; } // Check to see if the browser returns elements by name when // querying by getElementById (and provide a workaround) (function(){ // We're going to inject a fake input element with a specified name var form = document.createElement("div"), id = "script" + (new Date).getTime(); form.innerHTML = "<a name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly var root = document.documentElement; root.insertBefore( form, root.firstChild ); // The workaround has to do additional checks after a getElementById // Which slows things down for other browsers (hence the branching) if ( document.getElementById( id ) ) { Expr.find.ID = function(match, context, isXML){ if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }; Expr.filter.ID = function(elem, match){ var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }; } root.removeChild( form ); root = form = null; // release memory in IE })(); (function(){ // Check to see if the browser returns only elements // when doing getElementsByTagName("*") // Create a fake element var div = document.createElement("div"); div.appendChild( document.createComment("") ); // Make sure no comments are found if ( div.getElementsByTagName("*").length > 0 ) { Expr.find.TAG = function(match, context){ var results = context.getElementsByTagName(match[1]); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; }; } // Check to see if an attribute returns normalized href attributes div.innerHTML = "<a href='#'></a>"; if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && div.firstChild.getAttribute("href") !== "#" ) { Expr.attrHandle.href = function(elem){ return elem.getAttribute("href", 2); }; } div = null; // release memory in IE })(); if ( document.querySelectorAll ) { (function(){ var oldSizzle = Sizzle, div = document.createElement("div"); div.innerHTML = "<p class='TEST'></p>"; // Safari can't handle uppercase or unicode characters when // in quirks mode. if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { return; } Sizzle = function(query, context, extra, seed){ context = context || document; // Only use querySelectorAll on non-XML documents // (ID selectors don't work in non-HTML documents) if ( !seed && context.nodeType === 9 && !isXML(context) ) { try { return makeArray( context.querySelectorAll(query), extra ); } catch(e){} } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } div = null; // release memory in IE })(); } (function(){ var div = document.createElement("div"); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; // Opera can't find a second classname (in 9.6) // Also, make sure that getElementsByClassName actually exists if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { return; } // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; if ( div.getElementsByClassName("e").length === 1 ) { return; } Expr.order.splice(1, 0, "CLASS"); Expr.find.CLASS = function(match, context, isXML) { if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { return context.getElementsByClassName(match[1]); } }; div = null; // release memory in IE })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { elem = elem[dir]; var match = false; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem.sizcache = doneName; elem.sizset = i; } if ( elem.nodeName.toLowerCase() === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { elem = elem[dir]; var match = false; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem.sizcache = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } var contains = document.compareDocumentPosition ? function(a, b){ return !!(a.compareDocumentPosition(b) & 16); } : function(a, b){ return a !== b && (a.contains ? a.contains(b) : true); }; var isXML = function(elem){ // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; var posProcess = function(selector, context){ var tmpSet = [], later = "", match, root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.filters; jQuery.unique = Sizzle.uniqueSort; jQuery.text = getText; jQuery.isXMLDoc = isXML; jQuery.contains = contains; return; window.Sizzle = Sizzle; })(); var runtil = /Until$/, rparentsprev = /^(?:parents|prevUntil|prevAll)/, // Note: This RegExp should be improved, or likely pulled from Sizzle rmultiselector = /,/, slice = Array.prototype.slice; // Implement the identical functionality for filter and not var winnow = function( elements, qualifier, keep ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { return !!qualifier.call( elem, i, elem ) === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return (elem === qualifier) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return (jQuery.inArray( elem, qualifier ) >= 0) === keep; }); }; jQuery.fn.extend({ find: function( selector ) { var ret = this.pushStack( "", "find", selector ), length = 0; for ( var i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( var n = length; n < ret.length; n++ ) { for ( var r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var targets = jQuery( target ); return this.filter(function() { for ( var i = 0, l = targets.length; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && jQuery.filter( selector, this ).length > 0; }, closest: function( selectors, context ) { if ( jQuery.isArray( selectors ) ) { var ret = [], cur = this[0], match, matches = {}, selector; if ( cur && selectors.length ) { for ( var i = 0, l = selectors.length; i < l; i++ ) { selector = selectors[i]; if ( !matches[selector] ) { matches[selector] = jQuery.expr.match.POS.test( selector ) ? jQuery( selector, context || this.context ) : selector; } } while ( cur && cur.ownerDocument && cur !== context ) { for ( selector in matches ) { match = matches[selector]; if ( match.jquery ? match.index(cur) > -1 : jQuery(cur).is(match) ) { ret.push({ selector: selector, elem: cur }); delete matches[selector]; } } cur = cur.parentNode; } } return ret; } var pos = jQuery.expr.match.POS.test( selectors ) ? jQuery( selectors, context || this.context ) : null; return this.map(function( i, cur ) { while ( cur && cur.ownerDocument && cur !== context ) { if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selectors) ) { return cur; } cur = cur.parentNode; } return null; }); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { if ( !elem || typeof elem === "string" ) { return jQuery.inArray( this[0], // If it receives a string, the selector is used // If it receives nothing, the siblings are used elem ? jQuery( elem ) : this.parent().children() ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context || this.context ) : jQuery.makeArray( selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, andSelf: function() { return this.add( this.prevObject ); } }); // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return jQuery.nth( elem, 2, "nextSibling" ); }, prev: function( elem ) { return jQuery.nth( elem, 2, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( elem.parentNode.firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.makeArray( elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 ? jQuery.unique( ret ) : ret; if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, slice.call(arguments).join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[dir]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, nth: function( cur, result, dir, elem ) { result = result || 1; var num = 0; for ( ; cur; cur = cur[dir] ) { if ( cur.nodeType === 1 && ++num === result ) { break; } } return cur; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /(<([\w:]+)[^>]*?)\/>/g, rselfClosing = /^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnocache = /<script|<object|<embed|<option|<style/i, rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, // checked="checked" or checked (html5) fcloseTag = function( all, front, tag ) { return rselfClosing.test( tag ) ? all : front + "></" + tag + ">"; }, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }; wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE can't serialize <link> and <script> tags normally if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "div<div>", "</div>" ]; } jQuery.fn.extend({ text: function( text ) { if ( jQuery.isFunction(text) ) { return this.each(function(i) { var self = jQuery(this); self.text( text.call(this, i, self.text()) ); }); } if ( typeof text !== "object" && text !== undefined ) { return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); } return jQuery.text( this ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append(this); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { return this.each(function() { jQuery( this ).wrapAll( html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } else if ( arguments.length ) { var set = jQuery(arguments[0]); set.push.apply( set, this.toArray() ); return this.pushStack( set, "before", arguments ); } }, after: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } else if ( arguments.length ) { var set = this.pushStack( this, "after", arguments ); set.push.apply( set, jQuery(arguments[0]).toArray() ); return set; } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( events ) { // Do the clone var ret = this.map(function() { if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) { // IE copies events bound via attachEvent when // using cloneNode. Calling detachEvent on the // clone will also remove the events from the orignal // In order to get around this, we use innerHTML. // Unfortunately, this means some modifications to // attributes in IE that are actually only stored // as properties will not be copied (such as the // the name attribute on an input). var html = this.outerHTML, ownerDocument = this.ownerDocument; if ( !html ) { var div = ownerDocument.createElement("div"); div.appendChild( this.cloneNode(true) ); html = div.innerHTML; } return jQuery.clean([html.replace(rinlinejQuery, "") // Handle the case in IE 8 where action=/test/> self-closes a tag .replace(/=([^="'>\s]+\/)>/g, '="$1">') .replace(rleadingWhitespace, "")], ownerDocument)[0]; } else { return this.cloneNode(true); } }); // Copy the events from the original to the clone if ( events === true ) { cloneCopyEvent( this, ret ); cloneCopyEvent( this.find("*"), ret.find("*") ); } // Return the cloned set return ret; }, html: function( value ) { if ( value === undefined ) { return this[0] && this[0].nodeType === 1 ? this[0].innerHTML.replace(rinlinejQuery, "") : null; // See if we can take a shortcut and just use innerHTML } else if ( typeof value === "string" && !rnocache.test( value ) && (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) && !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) { value = value.replace(rxhtmlTag, fcloseTag); try { for ( var i = 0, l = this.length; i < l; i++ ) { // Remove element nodes and prevent memory leaks if ( this[i].nodeType === 1 ) { jQuery.cleanData( this[i].getElementsByTagName("*") ); this[i].innerHTML = value; } } // If using innerHTML throws an exception, use the fallback method } catch(e) { this.empty().append( value ); } } else if ( jQuery.isFunction( value ) ) { this.each(function(i){ var self = jQuery(this), old = self.html(); self.empty().append(function(){ return value.call( this, i, old ); }); }); } else { this.empty().append( value ); } return this; }, replaceWith: function( value ) { if ( this[0] && this[0].parentNode ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery(value).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery(this).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } else { return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ); } }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { var results, first, value = args[0], scripts = [], fragment, parent; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback, true ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call(this, i, table ? self.html() : undefined); self.domManip( args, table, callback ); }); } if ( this[0] ) { parent = value && value.parentNode; // If we're in a fragment, just use that instead of building a new one if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) { results = { fragment: parent }; } else { results = buildFragment( args, this, scripts ); } fragment = results.fragment; if ( fragment.childNodes.length === 1 ) { first = fragment = fragment.firstChild; } else { first = fragment.firstChild; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); for ( var i = 0, l = this.length; i < l; i++ ) { callback.call( table ? root(this[i], first) : this[i], i > 0 || results.cacheable || this.length > 1 ? fragment.cloneNode(true) : fragment ); } } if ( scripts.length ) { jQuery.each( scripts, evalScript ); } } return this; function root( elem, cur ) { return jQuery.nodeName(elem, "table") ? (elem.getElementsByTagName("tbody")[0] || elem.appendChild(elem.ownerDocument.createElement("tbody"))) : elem; } } }); function cloneCopyEvent(orig, ret) { var i = 0; ret.each(function() { if ( this.nodeName !== (orig[i] && orig[i].nodeName) ) { return; } var oldData = jQuery.data( orig[i++] ), curData = jQuery.data( this, oldData ), events = oldData && oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( var type in events ) { for ( var handler in events[ type ] ) { jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data ); } } } }); } function buildFragment( args, nodes, scripts ) { var fragment, cacheable, cacheresults, doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document); // Only cache "small" (1/2 KB) strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) { cacheable = true; cacheresults = jQuery.fragments[ args[0] ]; if ( cacheresults ) { if ( cacheresults !== 1 ) { fragment = cacheresults; } } } if ( !fragment ) { fragment = doc.createDocumentFragment(); jQuery.clean( args, doc, fragment, scripts ); } if ( cacheable ) { jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1; } return { fragment: fragment, cacheable: cacheable }; } jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var ret = [], insert = jQuery( selector ), parent = this.length === 1 && this[0].parentNode; if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = (i > 0 ? this.clone(true) : this).get(); jQuery.fn[ original ].apply( jQuery(insert[i]), elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); jQuery.extend({ clean: function( elems, context, fragment, scripts ) { context = context || document; // !context.createElement fails in IE with an error but returns typeof 'object' if ( typeof context.createElement === "undefined" ) { context = context.ownerDocument || context[0] && context[0].ownerDocument || document; } var ret = []; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" && !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else if ( typeof elem === "string" ) { // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, fcloseTag); // Trim whitespace, otherwise indexOf won't work as expected var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(), wrap = wrapMap[ tag ] || wrapMap._default, depth = wrap[0], div = context.createElement("div"); // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> var hasBody = rtbody.test(elem), tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( var j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } } if ( fragment ) { for ( var i = 0; ret[i]; i++ ) { if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) { scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] ); } else { if ( ret[i].nodeType === 1 ) { ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) ); } fragment.appendChild( ret[i] ); } } } return ret; }, cleanData: function( elems ) { var data, id, cache = jQuery.cache, special = jQuery.event.special, deleteExpando = jQuery.support.deleteExpando; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { id = elem[ jQuery.expando ]; if ( id ) { data = cache[ id ]; if ( data.events ) { for ( var type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); } else { removeEvent( elem, type, data.handle ); } } } if ( deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } delete cache[ id ]; } } } }); // exclude the following css properties to add px var rexclude = /z-?index|font-?weight|opacity|zoom|line-?height/i, ralpha = /alpha\([^)]*\)/, ropacity = /opacity=([^)]*)/, rfloat = /float/i, rdashAlpha = /-([a-z])/ig, rupper = /([A-Z])/g, rnumpx = /^-?\d+(?:px)?$/i, rnum = /^-?\d/, cssShow = { position: "absolute", visibility: "hidden", display:"block" }, cssWidth = [ "Left", "Right" ], cssHeight = [ "Top", "Bottom" ], // cache check for defaultView.getComputedStyle getComputedStyle = document.defaultView && document.defaultView.getComputedStyle, // normalize float css property styleFloat = jQuery.support.cssFloat ? "cssFloat" : "styleFloat", fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn.css = function( name, value ) { return access( this, name, value, true, function( elem, name, value ) { if ( value === undefined ) { return jQuery.curCSS( elem, name ); } if ( typeof value === "number" && !rexclude.test(name) ) { value += "px"; } jQuery.style( elem, name, value ); }); }; jQuery.extend({ style: function( elem, name, value ) { // don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { return undefined; } // ignore negative width and height values #1599 if ( (name === "width" || name === "height") && parseFloat(value) < 0 ) { value = undefined; } var style = elem.style || elem, set = value !== undefined; // IE uses filters for opacity if ( !jQuery.support.opacity && name === "opacity" ) { if ( set ) { // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // Set the alpha filter to set the opacity var opacity = parseInt( value, 10 ) + "" === "NaN" ? "" : "alpha(opacity=" + value * 100 + ")"; var filter = style.filter || jQuery.curCSS( elem, "filter" ) || ""; style.filter = ralpha.test(filter) ? filter.replace(ralpha, opacity) : opacity; } return style.filter && style.filter.indexOf("opacity=") >= 0 ? (parseFloat( ropacity.exec(style.filter)[1] ) / 100) + "": ""; } // Make sure we're using the right name for getting the float value if ( rfloat.test( name ) ) { name = styleFloat; } name = name.replace(rdashAlpha, fcamelCase); if ( set ) { style[ name ] = value; } return style[ name ]; }, css: function( elem, name, force, extra ) { if ( name === "width" || name === "height" ) { var val, props = cssShow, which = name === "width" ? cssWidth : cssHeight; function getWH() { val = name === "width" ? elem.offsetWidth : elem.offsetHeight; if ( extra === "border" ) { return; } jQuery.each( which, function() { if ( !extra ) { val -= parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0; } if ( extra === "margin" ) { val += parseFloat(jQuery.curCSS( elem, "margin" + this, true)) || 0; } else { val -= parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0; } }); } if ( elem.offsetWidth !== 0 ) { getWH(); } else { jQuery.swap( elem, props, getWH ); } return Math.max(0, Math.round(val)); } return jQuery.curCSS( elem, name, force ); }, curCSS: function( elem, name, force ) { var ret, style = elem.style, filter; // IE uses filters for opacity if ( !jQuery.support.opacity && name === "opacity" && elem.currentStyle ) { ret = ropacity.test(elem.currentStyle.filter || "") ? (parseFloat(RegExp.$1) / 100) + "" : ""; return ret === "" ? "1" : ret; } // Make sure we're using the right name for getting the float value if ( rfloat.test( name ) ) { name = styleFloat; } if ( !force && style && style[ name ] ) { ret = style[ name ]; } else if ( getComputedStyle ) { // Only "float" is needed here if ( rfloat.test( name ) ) { name = "float"; } name = name.replace( rupper, "-$1" ).toLowerCase(); var defaultView = elem.ownerDocument.defaultView; if ( !defaultView ) { return null; } var computedStyle = defaultView.getComputedStyle( elem, null ); if ( computedStyle ) { ret = computedStyle.getPropertyValue( name ); } // We should always get a number back from opacity if ( name === "opacity" && ret === "" ) { ret = "1"; } } else if ( elem.currentStyle ) { var camelCase = name.replace(rdashAlpha, fcamelCase); ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ]; // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels if ( !rnumpx.test( ret ) && rnum.test( ret ) ) { // Remember the original values var left = style.left, rsLeft = elem.runtimeStyle.left; // Put in the new values to get a computed value out elem.runtimeStyle.left = elem.currentStyle.left; style.left = camelCase === "fontSize" ? "1em" : (ret || 0); ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; elem.runtimeStyle.left = rsLeft; } } return ret; }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var old = {}; // Remember the old values, and insert the new ones for ( var name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } callback.call( elem ); // Revert the old values for ( var name in options ) { elem.style[ name ] = old[ name ]; } } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight, skip = elem.nodeName.toLowerCase() === "tr"; return width === 0 && height === 0 && !skip ? true : width > 0 && height > 0 && !skip ? false : jQuery.curCSS(elem, "display") === "none"; }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } var jsc = now(), rscript = /<script(.|\s)*?\/script>/gi, rselectTextarea = /select|textarea/i, rinput = /color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i, jsre = /=\?(&|$)/, rquery = /\?/, rts = /(\?|&)_=.*?(&|$)/, rurl = /^(\w+:)?\/\/([^\/?#]+)/, r20 = /%20/g, // Keep a copy of the old load method _load = jQuery.fn.load; jQuery.fn.extend({ load: function( url, params, callback ) { if ( typeof url !== "string" ) { return _load.call( this, url ); // Don't do a request if no elements are being requested } else if ( !this.length ) { return this; } var off = url.indexOf(" "); if ( off >= 0 ) { var selector = url.slice(off, url.length); url = url.slice(0, off); } // Default to a GET request var type = "GET"; // If the second parameter was provided if ( params ) { // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = null; // Otherwise, build a param string } else if ( typeof params === "object" ) { params = jQuery.param( params, jQuery.ajaxSettings.traditional ); type = "POST"; } } var self = this; // Request the remote document jQuery.ajax({ url: url, type: type, dataType: "html", data: params, complete: function( res, status ) { // If successful, inject the HTML into all the matched elements if ( status === "success" || status === "notmodified" ) { // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div />") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append(res.responseText.replace(rscript, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result res.responseText ); } if ( callback ) { self.each( callback, [res.responseText, status, res] ); } } }); return this; }, serialize: function() { return jQuery.param(this.serializeArray()); }, serializeArray: function() { return this.map(function() { return this.elements ? jQuery.makeArray(this.elements) : this; }) .filter(function() { return this.name && !this.disabled && (this.checked || rselectTextarea.test(this.nodeName) || rinput.test(this.type)); }) .map(function( i, elem ) { var val = jQuery(this).val(); return val == null ? null : jQuery.isArray(val) ? jQuery.map( val, function( val, i ) { return { name: elem.name, value: val }; }) : { name: elem.name, value: val }; }).get(); } }); // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function( i, o ) { jQuery.fn[o] = function( f ) { return this.bind(o, f); }; }); jQuery.extend({ get: function( url, data, callback, type ) { // shift arguments if data argument was omited if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = null; } return jQuery.ajax({ type: "GET", url: url, data: data, success: callback, dataType: type }); }, getScript: function( url, callback ) { return jQuery.get(url, null, callback, "script"); }, getJSON: function( url, data, callback ) { return jQuery.get(url, data, callback, "json"); }, post: function( url, data, callback, type ) { // shift arguments if data argument was omited if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = {}; } return jQuery.ajax({ type: "POST", url: url, data: data, success: callback, dataType: type }); }, ajaxSetup: function( settings ) { jQuery.extend( jQuery.ajaxSettings, settings ); }, ajaxSettings: { url: location.href, global: true, type: "GET", contentType: "application/x-www-form-urlencoded", processData: true, async: true, /* timeout: 0, data: null, username: null, password: null, traditional: false, */ // Create the request object; Microsoft failed to properly // implement the XMLHttpRequest in IE7 (can't request local files), // so we use the ActiveXObject when it is available // This function can be overriden by calling jQuery.ajaxSetup xhr: window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) ? function() { return new window.XMLHttpRequest(); } : function() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} }, accepts: { xml: "application/xml, text/xml", html: "text/html", script: "text/javascript, application/javascript", json: "application/json, text/javascript", text: "text/plain", _default: "*/*" } }, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajax: function( origSettings ) { var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings); var jsonp, status, data, callbackContext = origSettings && origSettings.context || s, type = s.type.toUpperCase(); // convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Handle JSONP Parameter Callbacks if ( s.dataType === "jsonp" ) { if ( type === "GET" ) { if ( !jsre.test( s.url ) ) { s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?"; } } else if ( !s.data || !jsre.test(s.data) ) { s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?"; } s.dataType = "json"; } // Build temporary JSONP function if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) { jsonp = s.jsonpCallback || ("jsonp" + jsc++); // Replace the =? sequence both in the query string and the data if ( s.data ) { s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1"); } s.url = s.url.replace(jsre, "=" + jsonp + "$1"); // We need to make sure // that a JSONP style response is executed properly s.dataType = "script"; // Handle JSONP-style loading window[ jsonp ] = window[ jsonp ] || function( tmp ) { data = tmp; success(); complete(); // Garbage collect window[ jsonp ] = undefined; try { delete window[ jsonp ]; } catch(e) {} if ( head ) { head.removeChild( script ); } }; } if ( s.dataType === "script" && s.cache === null ) { s.cache = false; } if ( s.cache === false && type === "GET" ) { var ts = now(); // try replacing _= if it is there var ret = s.url.replace(rts, "$1_=" + ts + "$2"); // if nothing was replaced, add timestamp to the end s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : ""); } // If data is available, append data to url for get requests if ( s.data && type === "GET" ) { s.url += (rquery.test(s.url) ? "&" : "?") + s.data; } // Watch for a new set of requests if ( s.global && ! jQuery.active++ ) { jQuery.event.trigger( "ajaxStart" ); } // Matches an absolute URL, and saves the domain var parts = rurl.exec( s.url ), remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host); // If we're requesting a remote document // and trying to load JSON or Script with a GET if ( s.dataType === "script" && type === "GET" && remote ) { var head = document.getElementsByTagName("head")[0] || document.documentElement; var script = document.createElement("script"); script.src = s.url; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } // Handle Script loading if ( !jsonp ) { var done = false; // Attach handlers for all browsers script.onload = script.onreadystatechange = function() { if ( !done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) { done = true; success(); complete(); // Handle memory leak in IE script.onload = script.onreadystatechange = null; if ( head && script.parentNode ) { head.removeChild( script ); } } }; } // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); // We handle everything using the script element injection return undefined; } var requestDone = false; // Create the request object var xhr = s.xhr(); if ( !xhr ) { return; } // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open(type, s.url, s.async, s.username, s.password); } else { xhr.open(type, s.url, s.async); } // Need an extra try/catch for cross domain requests in Firefox 3 try { // Set the correct header, if data is being sent if ( s.data || origSettings && origSettings.contentType ) { xhr.setRequestHeader("Content-Type", s.contentType); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[s.url] ) { xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]); } if ( jQuery.etag[s.url] ) { xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]); } } // Set header so the called script knows that it's an XMLHttpRequest // Only send the header if it's not a remote XHR if ( !remote ) { xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); } // Set the Accepts header for the server, depending on the dataType xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ? s.accepts[ s.dataType ] + ", */*" : s.accepts._default ); } catch(e) {} // Allow custom headers/mimetypes and early abort if ( s.beforeSend && s.beforeSend.call(callbackContext, xhr, s) === false ) { // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) { jQuery.event.trigger( "ajaxStop" ); } // close opended socket xhr.abort(); return false; } if ( s.global ) { trigger("ajaxSend", [xhr, s]); } // Wait for a response to come back var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) { // The request was aborted if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) { // Opera doesn't call onreadystatechange before this point // so we simulate the call if ( !requestDone ) { complete(); } requestDone = true; if ( xhr ) { xhr.onreadystatechange = jQuery.noop; } // The transfer is complete and the data is available, or the request timed out } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) { requestDone = true; xhr.onreadystatechange = jQuery.noop; status = isTimeout === "timeout" ? "timeout" : !jQuery.httpSuccess( xhr ) ? "error" : s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? "notmodified" : "success"; var errMsg; if ( status === "success" ) { // Watch for, and catch, XML document parse errors try { // process the data (runs the xml through httpData regardless of callback) data = jQuery.httpData( xhr, s.dataType, s ); } catch(err) { status = "parsererror"; errMsg = err; } } // Make sure that the request was successful or notmodified if ( status === "success" || status === "notmodified" ) { // JSONP handles its own success callback if ( !jsonp ) { success(); } } else { jQuery.handleError(s, xhr, status, errMsg); } // Fire the complete handlers complete(); if ( isTimeout === "timeout" ) { xhr.abort(); } // Stop memory leaks if ( s.async ) { xhr = null; } } }; // Override the abort handler, if we can (IE doesn't allow it, but that's OK) // Opera doesn't fire onreadystatechange at all on abort try { var oldAbort = xhr.abort; xhr.abort = function() { if ( xhr ) { oldAbort.call( xhr ); } onreadystatechange( "abort" ); }; } catch(e) { } // Timeout checker if ( s.async && s.timeout > 0 ) { setTimeout(function() { // Check to see if the request is still happening if ( xhr && !requestDone ) { onreadystatechange( "timeout" ); } }, s.timeout); } // Send the data try { xhr.send( type === "POST" || type === "PUT" || type === "DELETE" ? s.data : null ); } catch(e) { jQuery.handleError(s, xhr, null, e); // Fire the complete handlers complete(); } // firefox 1.5 doesn't fire statechange for sync requests if ( !s.async ) { onreadystatechange(); } function success() { // If a local callback was specified, fire it and pass it the data if ( s.success ) { s.success.call( callbackContext, data, status, xhr ); } // Fire the global callback if ( s.global ) { trigger( "ajaxSuccess", [xhr, s] ); } } function complete() { // Process result if ( s.complete ) { s.complete.call( callbackContext, xhr, status); } // The request was completed if ( s.global ) { trigger( "ajaxComplete", [xhr, s] ); } // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) { jQuery.event.trigger( "ajaxStop" ); } } function trigger(type, args) { (s.context ? jQuery(s.context) : jQuery.event).trigger(type, args); } // return XMLHttpRequest to allow aborting the request etc. return xhr; }, handleError: function( s, xhr, status, e ) { // If a local callback was specified, fire it if ( s.error ) { s.error.call( s.context || s, xhr, status, e ); } // Fire the global callback if ( s.global ) { (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] ); } }, // Counter for holding the number of active queries active: 0, // Determines if an XMLHttpRequest was successful or not httpSuccess: function( xhr ) { try { // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450 return !xhr.status && location.protocol === "file:" || // Opera returns 0 when status is 304 ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status === 304 || xhr.status === 1223 || xhr.status === 0; } catch(e) {} return false; }, // Determines if an XMLHttpRequest returns NotModified httpNotModified: function( xhr, url ) { var lastModified = xhr.getResponseHeader("Last-Modified"), etag = xhr.getResponseHeader("Etag"); if ( lastModified ) { jQuery.lastModified[url] = lastModified; } if ( etag ) { jQuery.etag[url] = etag; } // Opera returns 0 when status is 304 return xhr.status === 304 || xhr.status === 0; }, httpData: function( xhr, type, s ) { var ct = xhr.getResponseHeader("content-type") || "", xml = type === "xml" || !type && ct.indexOf("xml") >= 0, data = xml ? xhr.responseXML : xhr.responseText; if ( xml && data.documentElement.nodeName === "parsererror" ) { jQuery.error( "parsererror" ); } // Allow a pre-filtering function to sanitize the response // s is checked to keep backwards compatibility if ( s && s.dataFilter ) { data = s.dataFilter( data, type ); } // The filter can actually parse the response if ( typeof data === "string" ) { // Get the JavaScript object, if JSON is used. if ( type === "json" || !type && ct.indexOf("json") >= 0 ) { data = jQuery.parseJSON( data ); // If the type is "script", eval it in global context } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) { jQuery.globalEval( data ); } } return data; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a, traditional ) { var s = []; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray(a) || a.jquery ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( var prefix in a ) { buildParams( prefix, a[prefix] ); } } // Return the resulting serialization return s.join("&").replace(r20, "+"); function buildParams( prefix, obj ) { if ( jQuery.isArray(obj) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || /\[\]$/.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v ); } }); } else if ( !traditional && obj != null && typeof obj === "object" ) { // Serialize object item. jQuery.each( obj, function( k, v ) { buildParams( prefix + "[" + k + "]", v ); }); } else { // Serialize scalar item. add( prefix, obj ); } } function add( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction(value) ? value() : value; s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value); } } }); var elemdisplay = {}, rfxtypes = /toggle|show|hide/, rfxnum = /^([+-]=)?([\d+-.]+)(.*)$/, timerId, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ]; jQuery.fn.extend({ show: function( speed, callback ) { if ( speed || speed === 0) { return this.animate( genFx("show", 3), speed, callback); } else { for ( var i = 0, l = this.length; i < l; i++ ) { var old = jQuery.data(this[i], "olddisplay"); this[i].style.display = old || ""; if ( jQuery.css(this[i], "display") === "none" ) { var nodeName = this[i].nodeName, display; if ( elemdisplay[ nodeName ] ) { display = elemdisplay[ nodeName ]; } else { var elem = jQuery("<" + nodeName + " />").appendTo("body"); display = elem.css("display"); if ( display === "none" ) { display = "block"; } elem.remove(); elemdisplay[ nodeName ] = display; } jQuery.data(this[i], "olddisplay", display); } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( var j = 0, k = this.length; j < k; j++ ) { this[j].style.display = jQuery.data(this[j], "olddisplay") || ""; } return this; } }, hide: function( speed, callback ) { if ( speed || speed === 0 ) { return this.animate( genFx("hide", 3), speed, callback); } else { for ( var i = 0, l = this.length; i < l; i++ ) { var old = jQuery.data(this[i], "olddisplay"); if ( !old && old !== "none" ) { jQuery.data(this[i], "olddisplay", jQuery.css(this[i], "display")); } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( var j = 0, k = this.length; j < k; j++ ) { this[j].style.display = "none"; } return this; } }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2 ) { var bool = typeof fn === "boolean"; if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) { this._toggle.apply( this, arguments ); } else if ( fn == null || bool ) { this.each(function() { var state = bool ? fn : jQuery(this).is(":hidden"); jQuery(this)[ state ? "show" : "hide" ](); }); } else { this.animate(genFx("toggle", 3), fn, fn2); } return this; }, fadeTo: function( speed, to, callback ) { return this.filter(":hidden").css("opacity", 0).show().end() .animate({opacity: to}, speed, callback); }, animate: function( prop, speed, easing, callback ) { var optall = jQuery.speed(speed, easing, callback); if ( jQuery.isEmptyObject( prop ) ) { return this.each( optall.complete ); } return this[ optall.queue === false ? "each" : "queue" ](function() { var opt = jQuery.extend({}, optall), p, hidden = this.nodeType === 1 && jQuery(this).is(":hidden"), self = this; for ( p in prop ) { var name = p.replace(rdashAlpha, fcamelCase); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; p = name; } if ( prop[p] === "hide" && hidden || prop[p] === "show" && !hidden ) { return opt.complete.call(this); } if ( ( p === "height" || p === "width" ) && this.style ) { // Store display property opt.display = jQuery.css(this, "display"); // Make sure that nothing sneaks out opt.overflow = this.style.overflow; } if ( jQuery.isArray( prop[p] ) ) { // Create (if needed) and add to specialEasing (opt.specialEasing = opt.specialEasing || {})[p] = prop[p][1]; prop[p] = prop[p][0]; } } if ( opt.overflow != null ) { this.style.overflow = "hidden"; } opt.curAnim = jQuery.extend({}, prop); jQuery.each( prop, function( name, val ) { var e = new jQuery.fx( self, opt, name ); if ( rfxtypes.test(val) ) { e[ val === "toggle" ? hidden ? "show" : "hide" : val ]( prop ); } else { var parts = rfxnum.exec(val), start = e.cur(true) || 0; if ( parts ) { var end = parseFloat( parts[2] ), unit = parts[3] || "px"; // We need to compute starting value if ( unit !== "px" ) { self.style[ name ] = (end || 1) + unit; start = ((end || 1) / e.cur(true)) * start; self.style[ name ] = start + unit; } // If a +=/-= token was provided, we're doing a relative animation if ( parts[1] ) { end = ((parts[1] === "-=" ? -1 : 1) * end) + start; } e.custom( start, end, unit ); } else { e.custom( start, val, "" ); } } }); // For JS strict compliance return true; }); }, stop: function( clearQueue, gotoEnd ) { var timers = jQuery.timers; if ( clearQueue ) { this.queue([]); } this.each(function() { // go in reverse order so anything added to the queue during the loop is ignored for ( var i = timers.length - 1; i >= 0; i-- ) { if ( timers[i].elem === this ) { if (gotoEnd) { // force the next step to be the last timers[i](true); } timers.splice(i, 1); } } }); // start the next in the queue if the last step wasn't forced if ( !gotoEnd ) { this.dequeue(); } return this; } }); // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show", 1), slideUp: genFx("hide", 1), slideToggle: genFx("toggle", 1), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, callback ) { return this.animate( props, speed, callback ); }; }); jQuery.extend({ speed: function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? speed : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction(easing) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : jQuery.fx.speeds[opt.duration] || jQuery.fx.speeds._default; // Queueing opt.old = opt.complete; opt.complete = function() { if ( opt.queue !== false ) { jQuery(this).dequeue(); } if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } }; return opt; }, easing: { linear: function( p, n, firstNum, diff ) { return firstNum + diff * p; }, swing: function( p, n, firstNum, diff ) { return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum; } }, timers: [], fx: function( elem, options, prop ) { this.options = options; this.elem = elem; this.prop = prop; if ( !options.orig ) { options.orig = {}; } } }); jQuery.fx.prototype = { // Simple function for setting a style value update: function() { if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this ); // Set display property to block for height/width animations if ( ( this.prop === "height" || this.prop === "width" ) && this.elem.style ) { this.elem.style.display = "block"; } }, // Get the current size cur: function( force ) { if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) { return this.elem[ this.prop ]; } var r = parseFloat(jQuery.css(this.elem, this.prop, force)); return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0; }, // Start an animation from one number to another custom: function( from, to, unit ) { this.startTime = now(); this.start = from; this.end = to; this.unit = unit || this.unit || "px"; this.now = this.start; this.pos = this.state = 0; var self = this; function t( gotoEnd ) { return self.step(gotoEnd); } t.elem = this.elem; if ( t() && jQuery.timers.push(t) && !timerId ) { timerId = setInterval(jQuery.fx.tick, 13); } }, // Simple 'show' function show: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.show = true; // Begin the animation // Make sure that we start at a small width/height to avoid any // flash of content this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur()); // Start by showing the element jQuery( this.elem ).show(); }, // Simple 'hide' function hide: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.hide = true; // Begin the animation this.custom(this.cur(), 0); }, // Each step of an animation step: function( gotoEnd ) { var t = now(), done = true; if ( gotoEnd || t >= this.options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); this.options.curAnim[ this.prop ] = true; for ( var i in this.options.curAnim ) { if ( this.options.curAnim[i] !== true ) { done = false; } } if ( done ) { if ( this.options.display != null ) { // Reset the overflow this.elem.style.overflow = this.options.overflow; // Reset the display var old = jQuery.data(this.elem, "olddisplay"); this.elem.style.display = old ? old : this.options.display; if ( jQuery.css(this.elem, "display") === "none" ) { this.elem.style.display = "block"; } } // Hide the element if the "hide" operation was done if ( this.options.hide ) { jQuery(this.elem).hide(); } // Reset the properties, if the item has been hidden or shown if ( this.options.hide || this.options.show ) { for ( var p in this.options.curAnim ) { jQuery.style(this.elem, p, this.options.orig[p]); } } // Execute the complete function this.options.complete.call( this.elem ); } return false; } else { var n = t - this.startTime; this.state = n / this.options.duration; // Perform the easing function, defaults to swing var specialEasing = this.options.specialEasing && this.options.specialEasing[this.prop]; var defaultEasing = this.options.easing || (jQuery.easing.swing ? "swing" : "linear"); this.pos = jQuery.easing[specialEasing || defaultEasing](this.state, n, 0, 1, this.options.duration); this.now = this.start + ((this.end - this.start) * this.pos); // Perform the next step of the animation this.update(); } return true; } }; jQuery.extend( jQuery.fx, { tick: function() { var timers = jQuery.timers; for ( var i = 0; i < timers.length; i++ ) { if ( !timers[i]() ) { timers.splice(i--, 1); } } if ( !timers.length ) { jQuery.fx.stop(); } }, stop: function() { clearInterval( timerId ); timerId = null; }, speeds: { slow: 600, fast: 200, // Default speed _default: 400 }, step: { opacity: function( fx ) { jQuery.style(fx.elem, "opacity", fx.now); }, _default: function( fx ) { if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) { fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit; } else { fx.elem[ fx.prop ] = fx.now; } } } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } function genFx( type, num ) { var obj = {}; jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() { obj[ this ] = type; }); return obj; } if ( "getBoundingClientRect" in document.documentElement ) { jQuery.fn.offset = function( options ) { var elem = this[0]; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } var box = elem.getBoundingClientRect(), doc = elem.ownerDocument, body = doc.body, docElem = doc.documentElement, clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, top = box.top + (self.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop ) - clientTop, left = box.left + (self.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft) - clientLeft; return { top: top, left: left }; }; } else { jQuery.fn.offset = function( options ) { var elem = this[0]; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } jQuery.offset.initialize(); var offsetParent = elem.offsetParent, prevOffsetParent = elem, doc = elem.ownerDocument, computedStyle, docElem = doc.documentElement, body = doc.body, defaultView = doc.defaultView, prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle, top = elem.offsetTop, left = elem.offsetLeft; while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) { if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { break; } computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle; top -= elem.scrollTop; left -= elem.scrollLeft; if ( elem === offsetParent ) { top += elem.offsetTop; left += elem.offsetLeft; if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(elem.nodeName)) ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevOffsetParent = offsetParent, offsetParent = elem.offsetParent; } if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevComputedStyle = computedStyle; } if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) { top += body.offsetTop; left += body.offsetLeft; } if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { top += Math.max( docElem.scrollTop, body.scrollTop ); left += Math.max( docElem.scrollLeft, body.scrollLeft ); } return { top: top, left: left }; }; } jQuery.offset = { initialize: function() { var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.curCSS(body, "marginTop", true) ) || 0, html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>"; jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } ); container.innerHTML = html; body.insertBefore( container, body.firstChild ); innerDiv = container.firstChild; checkDiv = innerDiv.firstChild; td = innerDiv.nextSibling.firstChild.firstChild; this.doesNotAddBorder = (checkDiv.offsetTop !== 5); this.doesAddBorderForTableAndCells = (td.offsetTop === 5); checkDiv.style.position = "fixed", checkDiv.style.top = "20px"; // safari subtracts parent border width here which is 5px this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15); checkDiv.style.position = checkDiv.style.top = ""; innerDiv.style.overflow = "hidden", innerDiv.style.position = "relative"; this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5); this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop); body.removeChild( container ); body = container = innerDiv = checkDiv = table = td = null; jQuery.offset.initialize = jQuery.noop; }, bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; jQuery.offset.initialize(); if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.curCSS(body, "marginTop", true) ) || 0; left += parseFloat( jQuery.curCSS(body, "marginLeft", true) ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { // set position first, in-case top/left are set even on static elem if ( /static/.test( jQuery.curCSS( elem, "position" ) ) ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curTop = parseInt( jQuery.curCSS( elem, "top", true ), 10 ) || 0, curLeft = parseInt( jQuery.curCSS( elem, "left", true ), 10 ) || 0; if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } var props = { top: (options.top - curOffset.top) + curTop, left: (options.left - curOffset.left) + curLeft }; if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[0] ) { return null; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = /^body|html$/i.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.curCSS(elem, "marginTop", true) ) || 0; offset.left -= parseFloat( jQuery.curCSS(elem, "marginLeft", true) ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.curCSS(offsetParent[0], "borderTopWidth", true) ) || 0; parentOffset.left += parseFloat( jQuery.curCSS(offsetParent[0], "borderLeftWidth", true) ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!/^body|html$/i.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( ["Left", "Top"], function( i, name ) { var method = "scroll" + name; jQuery.fn[ method ] = function(val) { var elem = this[0], win; if ( !elem ) { return null; } if ( val !== undefined ) { // Set the scroll offset return this.each(function() { win = getWindow( this ); if ( win ) { win.scrollTo( !i ? val : jQuery(win).scrollLeft(), i ? val : jQuery(win).scrollTop() ); } else { this[ method ] = val; } }); } else { win = getWindow( elem ); // Return the scroll offset return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] : jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ method ] : elem[ method ]; } }; }); function getWindow( elem ) { return ("scrollTo" in elem && elem.document) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each([ "Height", "Width" ], function( i, name ) { var type = name.toLowerCase(); // innerHeight and innerWidth jQuery.fn["inner" + name] = function() { return this[0] ? jQuery.css( this[0], type, false, "padding" ) : null; }; // outerHeight and outerWidth jQuery.fn["outer" + name] = function( margin ) { return this[0] ? jQuery.css( this[0], type, false, margin ? "margin" : "border" ) : null; }; jQuery.fn[ type ] = function( size ) { // Get window width or height var elem = this[0]; if ( !elem ) { return size == null ? null : this; } if ( jQuery.isFunction( size ) ) { return this.each(function( i ) { var self = jQuery( this ); self[ type ]( size.call( this, i, self[ type ]() ) ); }); } return ("scrollTo" in elem && elem.document) ? // does it walk and quack like a window? // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode elem.document.compatMode === "CSS1Compat" && elem.document.documentElement[ "client" + name ] || elem.document.body[ "client" + name ] : // Get document width or height (elem.nodeType === 9) ? // is it a document // Either scroll[Width/Height] or offset[Width/Height], whichever is greater Math.max( elem.documentElement["client" + name], elem.body["scroll" + name], elem.documentElement["scroll" + name], elem.body["offset" + name], elem.documentElement["offset" + name] ) : // Get or set width or height on the element size === undefined ? // Get width or height on the element jQuery.css( elem, type ) : // Set the width or height on the element (default to pixels if value is unitless) this.css( type, typeof size === "string" ? size : size + "px" ); }; }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; })(window); // name: sammy // version: 0.5.4 (function($) { var Sammy, PATH_REPLACER = "([^\/]+)", PATH_NAME_MATCHER = /:([\w\d]+)/g, QUERY_STRING_MATCHER = /\?([^#]*)$/, // mainly for making `arguments` an Array _makeArray = function(nonarray) { return Array.prototype.slice.call(nonarray); }, // borrowed from jQuery _isFunction = function( obj ) { return Object.prototype.toString.call(obj) === "[object Function]"; }, _isArray = function( obj ) { return Object.prototype.toString.call(obj) === "[object Array]"; }, _decode = decodeURIComponent, _routeWrapper = function(verb) { return function(path, callback) { return this.route.apply(this, [verb, path, callback]); }; }, loggers = []; // `Sammy` (also aliased as $.sammy) is not only the namespace for a // number of prototypes, its also a top level method that allows for easy // creation/management of `Sammy.Application` instances. There are a // number of different forms for `Sammy()` but each returns an instance // of `Sammy.Application`. When a new instance is created using // `Sammy` it is added to an Object called `Sammy.apps`. This // provides for an easy way to get at existing Sammy applications. Only one // instance is allowed per `element_selector` so when calling // `Sammy('selector')` multiple times, the first time will create // the application and the following times will extend the application // already added to that selector. // // ### Example // // // returns the app at #main or a new app // Sammy('#main') // // // equivilent to "new Sammy.Application", except appends to apps // Sammy(); // Sammy(function() { ... }); // // // extends the app at '#main' with function. // Sammy('#main', function() { ... }); // Sammy = function() { var args = _makeArray(arguments), app, selector; Sammy.apps = Sammy.apps || {}; if (args.length === 0 || args[0] && _isFunction(args[0])) { // Sammy() return Sammy.apply(Sammy, ['body'].concat(args)); } else if (typeof (selector = args.shift()) == 'string') { // Sammy('#main') app = Sammy.apps[selector] || new Sammy.Application(); app.element_selector = selector; if (args.length > 0) { $.each(args, function(i, plugin) { app.use(plugin); }); } // if the selector changes make sure the refrence in Sammy.apps changes if (app.element_selector != selector) { delete Sammy.apps[selector]; } Sammy.apps[app.element_selector] = app; return app; } }; Sammy.VERSION = '0.5.4'; // Add to the global logger pool. Takes a function that accepts an // unknown number of arguments and should print them or send them somewhere // The first argument is always a timestamp. Sammy.addLogger = function(logger) { loggers.push(logger); }; // Sends a log message to each logger listed in the global // loggers pool. Can take any number of arguments. // Also prefixes the arguments with a timestamp. Sammy.log = function() { var args = _makeArray(arguments); args.unshift("[" + Date() + "]"); $.each(loggers, function(i, logger) { logger.apply(Sammy, args); }); }; if (typeof window.console != 'undefined') { if (_isFunction(console.log.apply)) { Sammy.addLogger(function() { window.console.log.apply(console, arguments); }); } else { Sammy.addLogger(function() { window.console.log(arguments); }); } } else if (typeof console != 'undefined') { Sammy.addLogger(function() { console.log.apply(console, arguments); }); } $.extend(Sammy, { makeArray: _makeArray, isFunction: _isFunction, isArray: _isArray }) // Sammy.Object is the base for all other Sammy classes. It provides some useful // functionality, including cloning, iterating, etc. Sammy.Object = function(obj) { // constructor return $.extend(this, obj || {}); }; $.extend(Sammy.Object.prototype, { // Returns a copy of the object with Functions removed. toHash: function() { var json = {}; $.each(this, function(k,v) { if (!_isFunction(v)) { json[k] = v; } }); return json; }, // Renders a simple HTML version of this Objects attributes. // Does not render functions. // For example. Given this Sammy.Object: // // var s = new Sammy.Object({first_name: 'Sammy', last_name: 'Davis Jr.'}); // s.toHTML() //=> '<strong>first_name</strong> Sammy<br /><strong>last_name</strong> Davis Jr.<br />' // toHTML: function() { var display = ""; $.each(this, function(k, v) { if (!_isFunction(v)) { display += "<strong>" + k + "</strong> " + v + "<br />"; } }); return display; }, // Returns an array of keys for this object. If `attributes_only` // is true will not return keys that map to a `function()` keys: function(attributes_only) { var keys = []; for (var property in this) { if (!_isFunction(this[property]) || !attributes_only) { keys.push(property); } } return keys; }, // Checks if the object has a value at `key` and that the value is not empty has: function(key) { return this[key] && $.trim(this[key].toString()) != ''; }, // convenience method to join as many arguments as you want // by the first argument - useful for making paths join: function() { var args = _makeArray(arguments); var delimiter = args.shift(); return args.join(delimiter); }, // Shortcut to Sammy.log log: function() { Sammy.log.apply(Sammy, arguments); }, // Returns a string representation of this object. // if `include_functions` is true, it will also toString() the // methods of this object. By default only prints the attributes. toString: function(include_functions) { var s = []; $.each(this, function(k, v) { if (!_isFunction(v) || include_functions) { s.push('"' + k + '": ' + v.toString()); } }); return "Sammy.Object: {" + s.join(',') + "}"; } }); // The HashLocationProxy is the default location proxy for all Sammy applications. // A location proxy is a prototype that conforms to a simple interface. The purpose // of a location proxy is to notify the Sammy.Application its bound to when the location // or 'external state' changes. The HashLocationProxy considers the state to be // changed when the 'hash' (window.location.hash / '#') changes. It does this in two // different ways depending on what browser you are using. The newest browsers // (IE, Safari > 4, FF >= 3.6) support a 'onhashchange' DOM event, thats fired whenever // the location.hash changes. In this situation the HashLocationProxy just binds // to this event and delegates it to the application. In the case of older browsers // a poller is set up to track changes to the hash. Unlike Sammy 0.3 or earlier, // the HashLocationProxy allows the poller to be a global object, eliminating the // need for multiple pollers even when thier are multiple apps on the page. Sammy.HashLocationProxy = function(app, run_interval_every) { this.app = app; // set is native to false and start the poller immediately this.is_native = false; this._startPolling(run_interval_every); }; Sammy.HashLocationProxy.prototype = { // bind the proxy events to the current app. bind: function() { var proxy = this, app = this.app; $(window).bind('hashchange.' + this.app.eventNamespace(), function(e, non_native) { // if we receive a native hash change event, set the proxy accordingly // and stop polling if (proxy.is_native === false && !non_native) { Sammy.log('native hash change exists, using'); proxy.is_native = true; clearInterval(Sammy.HashLocationProxy._interval); } app.trigger('location-changed'); }); }, // unbind the proxy events from the current app unbind: function() { $(window).unbind('hashchange.' + this.app.eventNamespace()); }, // get the current location from the hash. getLocation: function() { // Bypass the `window.location.hash` attribute. If a question mark // appears in the hash IE6 will strip it and all of the following // characters from `window.location.hash`. var matches = window.location.toString().match(/^[^#]*(#.+)$/); return matches ? matches[1] : ''; }, // set the current location to `new_location` setLocation: function(new_location) { return (window.location = new_location); }, _startPolling: function(every) { // set up interval var proxy = this; if (!Sammy.HashLocationProxy._interval) { if (!every) { every = 10; } var hashCheck = function() { current_location = proxy.getLocation(); if (!Sammy.HashLocationProxy._last_location || current_location != Sammy.HashLocationProxy._last_location) { setTimeout(function() { $(window).trigger('hashchange', [true]); }, 1); } Sammy.HashLocationProxy._last_location = current_location; }; hashCheck(); Sammy.HashLocationProxy._interval = setInterval(hashCheck, every); $(window).bind('beforeunload', function() { clearInterval(Sammy.HashLocationProxy._interval); }); } } }; // The DataLocationProxy is an optional location proxy prototype. As opposed to // the `HashLocationProxy` it gets its location from a jQuery.data attribute // tied to the application's element. You can set the name of the attribute by // passing a string as the second argument to the constructor. The default attribute // name is 'sammy-location'. To read more about location proxies, check out the // documentation for `Sammy.HashLocationProxy` Sammy.DataLocationProxy = function(app, data_name) { this.app = app; this.data_name = data_name || 'sammy-location'; }; Sammy.DataLocationProxy.prototype = { bind: function() { var proxy = this; this.app.$element().bind('setData', function(e, key, value) { if (key == proxy.data_name) { // jQuery unfortunately fires the event before it sets the value // work around it, by setting the value ourselves proxy.app.$element().each(function() { $.data(this, proxy.data_name, value); }); proxy.app.trigger('location-changed'); } }); }, unbind: function() { this.app.$element().unbind('setData'); }, getLocation: function() { return this.app.$element().data(this.data_name); }, setLocation: function(new_location) { return this.app.$element().data(this.data_name, new_location); } }; // Sammy.Application is the Base prototype for defining 'applications'. // An 'application' is a collection of 'routes' and bound events that is // attached to an element when `run()` is called. // The only argument an 'app_function' is evaluated within the context of the application. Sammy.Application = function(app_function) { var app = this; this.routes = {}; this.listeners = new Sammy.Object({}); this.arounds = []; this.befores = []; // generate a unique namespace this.namespace = (new Date()).getTime() + '-' + parseInt(Math.random() * 1000, 10); this.context_prototype = function() { Sammy.EventContext.apply(this, arguments); }; this.context_prototype.prototype = new Sammy.EventContext(); if (_isFunction(app_function)) { app_function.apply(this, [this]); } // set the location proxy if not defined to the default (HashLocationProxy) if (!this.location_proxy) { this.location_proxy = new Sammy.HashLocationProxy(app, this.run_interval_every); } if (this.debug) { this.bindToAllEvents(function(e, data) { app.log(app.toString(), e.cleaned_type, data || {}); }); } }; Sammy.Application.prototype = $.extend({}, Sammy.Object.prototype, { // the four route verbs ROUTE_VERBS: ['get','post','put','delete'], // An array of the default events triggered by the // application during its lifecycle APP_EVENTS: ['run','unload','lookup-route','run-route','route-found','event-context-before','event-context-after','changed','error','check-form-submission','redirect'], _last_route: null, _running: false, // Defines what element the application is bound to. Provide a selector // (parseable by `jQuery()`) and this will be used by `$element()` element_selector: 'body', // When set to true, logs all of the default events using `log()` debug: false, // When set to true, and the error() handler is not overriden, will actually // raise JS errors in routes (500) and when routes can't be found (404) raise_errors: false, // The time in milliseconds that the URL is queried for changes run_interval_every: 50, // The location proxy for the current app. By default this is set to a new // `Sammy.HashLocationProxy` on initialization. However, you can set // the location_proxy inside you're app function to give youre app a custom // location mechanism location_proxy: null, // The default template engine to use when using `partial()` in an // `EventContext`. `template_engine` can either be a string that // corresponds to the name of a method/helper on EventContext or it can be a function // that takes two arguments, the content of the unrendered partial and an optional // JS object that contains interpolation data. Template engine is only called/refered // to if the extension of the partial is null or unknown. See `partial()` // for more information template_engine: null, // //=> Sammy.Application: body toString: function() { return 'Sammy.Application:' + this.element_selector; }, // returns a jQuery object of the Applications bound element. $element: function() { return $(this.element_selector); }, // `use()` is the entry point for including Sammy plugins. // The first argument to use should be a function() that is evaluated // in the context of the current application, just like the `app_function` // argument to the `Sammy.Application` constructor. // // Any additional arguments are passed to the app function sequentially. // // For much more detail about plugins, check out: // http://code.quirkey.com/sammy/doc/plugins.html // // ### Example // // var MyPlugin = function(app, prepend) { // // this.helpers({ // myhelper: function(text) { // alert(prepend + " " + text); // } // }); // // }; // // var app = $.sammy(function() { // // this.use(MyPlugin, 'This is my plugin'); // // this.get('#/', function() { // this.myhelper('and dont you forget it!'); // //=> Alerts: This is my plugin and dont you forget it! // }); // // }); // use: function() { // flatten the arguments var args = _makeArray(arguments); var plugin = args.shift(); try { args.unshift(this); plugin.apply(this, args); } catch(e) { if (typeof plugin == 'undefined') { this.error("Plugin Error: called use() but plugin is not defined", e); } else if (!_isFunction(plugin)) { this.error("Plugin Error: called use() but '" + plugin.toString() + "' is not a function", e); } else { this.error("Plugin Error", e); } } return this; }, // `route()` is the main method for defining routes within an application. // For great detail on routes, check out: http://code.quirkey.com/sammy/doc/routes.html // // This method also has aliases for each of the different verbs (eg. `get()`, `post()`, etc.) // // ### Arguments // // * `verb` A String in the set of ROUTE_VERBS or 'any'. 'any' will add routes for each // of the ROUTE_VERBS. If only two arguments are passed, // the first argument is the path, the second is the callback and the verb // is assumed to be 'any'. // * `path` A Regexp or a String representing the path to match to invoke this verb. // * `callback` A Function that is called/evaluated whent the route is run see: `runRoute()`. // It is also possible to pass a string as the callback, which is looked up as the name // of a method on the application. // route: function(verb, path, callback) { var app = this, param_names = [], add_route; // if the method signature is just (path, callback) // assume the verb is 'any' if (!callback && _isFunction(path)) { path = verb; callback = path; verb = 'any'; } verb = verb.toLowerCase(); // ensure verb is lower case // if path is a string turn it into a regex if (path.constructor == String) { // Needs to be explicitly set because IE will maintain the index unless NULL is returned, // which means that with two consecutive routes that contain params, the second set of params will not be found and end up in splat instead of params // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/RegExp/lastIndex PATH_NAME_MATCHER.lastIndex = 0; // find the names while ((path_match = PATH_NAME_MATCHER.exec(path)) !== null) { param_names.push(path_match[1]); } // replace with the path replacement path = new RegExp("^" + path.replace(PATH_NAME_MATCHER, PATH_REPLACER) + "$"); } // lookup callback if (typeof callback == 'string') { callback = app[callback]; } add_route = function(with_verb) { var r = {verb: with_verb, path: path, callback: callback, param_names: param_names}; // add route to routes array app.routes[with_verb] = app.routes[with_verb] || []; // place routes in order of definition app.routes[with_verb].push(r); }; if (verb === 'any') { $.each(this.ROUTE_VERBS, function(i, v) { add_route(v); }); } else { add_route(verb); } // return the app return this; }, // Alias for route('get', ...) get: _routeWrapper('get'), // Alias for route('post', ...) post: _routeWrapper('post'), // Alias for route('put', ...) put: _routeWrapper('put'), // Alias for route('delete', ...) del: _routeWrapper('delete'), // Alias for route('any', ...) any: _routeWrapper('any'), // `mapRoutes` takes an array of arrays, each array being passed to route() // as arguments, this allows for mass definition of routes. Another benefit is // this makes it possible/easier to load routes via remote JSON. // // ### Example // // var app = $.sammy(function() { // // this.mapRoutes([ // ['get', '#/', function() { this.log('index'); }], // // strings in callbacks are looked up as methods on the app // ['post', '#/create', 'addUser'], // // No verb assumes 'any' as the verb // [/dowhatever/, function() { this.log(this.verb, this.path)}]; // ]); // }) // mapRoutes: function(route_array) { var app = this; $.each(route_array, function(i, route_args) { app.route.apply(app, route_args); }); return this; }, // A unique event namespace defined per application. // All events bound with `bind()` are automatically bound within this space. eventNamespace: function() { return ['sammy-app', this.namespace].join('-'); }, // Works just like `jQuery.fn.bind()` with a couple noteable differences. // // * It binds all events to the application element // * All events are bound within the `eventNamespace()` // * Events are not actually bound until the application is started with `run()` // * callbacks are evaluated within the context of a Sammy.EventContext // // See http://code.quirkey.com/sammy/docs/events.html for more info. // bind: function(name, data, callback) { var app = this; // build the callback // if the arity is 2, callback is the second argument if (typeof callback == 'undefined') { callback = data; } var listener_callback = function() { // pull off the context from the arguments to the callback var e, context, data; e = arguments[0]; data = arguments[1]; if (data && data.context) { context = data.context; delete data.context; } else { context = new app.context_prototype(app, 'bind', e.type, data, e.target); } e.cleaned_type = e.type.replace(app.eventNamespace(), ''); callback.apply(context, [e, data]); }; // it could be that the app element doesnt exist yet // so attach to the listeners array and then run() // will actually bind the event. if (!this.listeners[name]) { this.listeners[name] = []; } this.listeners[name].push(listener_callback); if (this.isRunning()) { // if the app is running // *actually* bind the event to the app element this._listen(name, listener_callback); } return this; }, // Triggers custom events defined with `bind()` // // ### Arguments // // * `name` The name of the event. Automatically prefixed with the `eventNamespace()` // * `data` An optional Object that can be passed to the bound callback. // * `context` An optional context/Object in which to execute the bound callback. // If no context is supplied a the context is a new `Sammy.EventContext` // trigger: function(name, data) { this.$element().trigger([name, this.eventNamespace()].join('.'), [data]); return this; }, // Reruns the current route refresh: function() { this.last_location = null; this.trigger('location-changed'); return this; }, // Takes a single callback that is pushed on to a stack. // Before any route is run, the callbacks are evaluated in order within // the current `Sammy.EventContext` // // If any of the callbacks explicitly return false, execution of any // further callbacks and the route itself is halted. // // You can also provide a set of options that will define when to run this // before based on the route it proceeds. // // ### Example // // var app = $.sammy(function() { // // // will run at #/route but not at #/ // this.before('#/route', function() { // //... // }); // // // will run at #/ but not at #/route // this.before({except: {path: '#/route'}}, function() { // this.log('not before #/route'); // }); // // this.get('#/', function() {}); // // this.get('#/route', function() {}); // // }); // // See `contextMatchesOptions()` for a full list of supported options // before: function(options, callback) { if (_isFunction(options)) { callback = options; options = {}; } this.befores.push([options, callback]); return this; }, // A shortcut for binding a callback to be run after a route is executed. // After callbacks have no guarunteed order. after: function(callback) { return this.bind('event-context-after', callback); }, // Adds an around filter to the application. around filters are functions // that take a single argument `callback` which is the entire route // execution path wrapped up in a closure. This means you can decide whether // or not to proceed with execution by not invoking `callback` or, // more usefuly wrapping callback inside the result of an asynchronous execution. // // ### Example // // The most common use case for around() is calling a _possibly_ async function // and executing the route within the functions callback: // // var app = $.sammy(function() { // // var current_user = false; // // function checkLoggedIn(callback) { // // /session returns a JSON representation of the logged in user // // or an empty object // if (!current_user) { // $.getJSON('/session', function(json) { // if (json.login) { // // show the user as logged in // current_user = json; // // execute the route path // callback(); // } else { // // show the user as not logged in // current_user = false; // // the context of aroundFilters is an EventContext // this.redirect('#/login'); // } // }); // } else { // // execute the route path // callback(); // } // }; // // this.around(checkLoggedIn); // // }); // around: function(callback) { this.arounds.push(callback); return this; }, // Returns a boolean of weather the current application is running. isRunning: function() { return this._running; }, // Helpers extends the EventContext prototype specific to this app. // This allows you to define app specific helper functions that can be used // whenever you're inside of an event context (templates, routes, bind). // // ### Example // // var app = $.sammy(function() { // // helpers({ // upcase: function(text) { // return text.toString().toUpperCase(); // } // }); // // get('#/', function() { with(this) { // // inside of this context I can use the helpers // $('#main').html(upcase($('#main').text()); // }}); // // }); // // // ### Arguments // // * `extensions` An object collection of functions to extend the context. // helpers: function(extensions) { $.extend(this.context_prototype.prototype, extensions); return this; }, // Helper extends the event context just like `helpers()` but does it // a single method at a time. This is especially useful for dynamically named // helpers // // ### Example // // // Trivial example that adds 3 helper methods to the context dynamically // var app = $.sammy(function(app) { // // $.each([1,2,3], function(i, num) { // app.helper('helper' + num, function() { // this.log("I'm helper number " + num); // }); // }); // // this.get('#/', function() { // this.helper2(); //=> I'm helper number 2 // }); // }); // // ### Arguments // // * `name` The name of the method // * `method` The function to be added to the prototype at `name` // helper: function(name, method) { this.context_prototype.prototype[name] = method; return this; }, // Actually starts the application's lifecycle. `run()` should be invoked // within a document.ready block to ensure the DOM exists before binding events, etc. // // ### Example // // var app = $.sammy(function() { ... }); // your application // $(function() { // document.ready // app.run(); // }); // // ### Arguments // // * `start_url` Optionally, a String can be passed which the App will redirect to // after the events/routes have been bound. run: function(start_url) { if (this.isRunning()) { return false; } var app = this; // actually bind all the listeners $.each(this.listeners.toHash(), function(name, callbacks) { $.each(callbacks, function(i, listener_callback) { app._listen(name, listener_callback); }); }); this.trigger('run', {start_url: start_url}); this._running = true; // set last location this.last_location = null; if (this.getLocation() == '' && typeof start_url != 'undefined') { this.setLocation(start_url); } // check url this._checkLocation(); this.location_proxy.bind(); this.bind('location-changed', function() { app._checkLocation(); }); // bind to submit to capture post/put/delete routes this.bind('submit', function(e) { var returned = app._checkFormSubmission($(e.target).closest('form')); return (returned === false) ? e.preventDefault() : false; }); // bind unload to body unload $(window).bind('beforeunload', function() { app.unload(); }); // trigger html changed return this.trigger('changed'); }, // The opposite of `run()`, un-binds all event listeners and intervals // `run()` Automaticaly binds a `onunload` event to run this when // the document is closed. unload: function() { if (!this.isRunning()) { return false; } var app = this; this.trigger('unload'); // clear interval this.location_proxy.unbind(); // unbind form submits this.$element().unbind('submit').removeClass(app.eventNamespace()); // unbind all events $.each(this.listeners.toHash() , function(name, listeners) { $.each(listeners, function(i, listener_callback) { app._unlisten(name, listener_callback); }); }); this._running = false; return this; }, // Will bind a single callback function to every event that is already // being listened to in the app. This includes all the `APP_EVENTS` // as well as any custom events defined with `bind()`. // // Used internally for debug logging. bindToAllEvents: function(callback) { var app = this; // bind to the APP_EVENTS first $.each(this.APP_EVENTS, function(i, e) { app.bind(e, callback); }); // next, bind to listener names (only if they dont exist in APP_EVENTS) $.each(this.listeners.keys(true), function(i, name) { if (app.APP_EVENTS.indexOf(name) == -1) { app.bind(name, callback); } }); return this; }, // Returns a copy of the given path with any query string after the hash // removed. routablePath: function(path) { return path.replace(QUERY_STRING_MATCHER, ''); }, // Given a verb and a String path, will return either a route object or false // if a matching route can be found within the current defined set. lookupRoute: function(verb, path) { var app = this, routed = false; this.trigger('lookup-route', {verb: verb, path: path}); if (typeof this.routes[verb] != 'undefined') { $.each(this.routes[verb], function(i, route) { if (app.routablePath(path).match(route.path)) { routed = route; return false; } }); } return routed; }, // First, invokes `lookupRoute()` and if a route is found, parses the // possible URL params and then invokes the route's callback within a new // `Sammy.EventContext`. If the route can not be found, it calls // `notFound()`. If `raise_errors` is set to `true` and // the `error()` has not been overriden, it will throw an actual JS // error. // // You probably will never have to call this directly. // // ### Arguments // // * `verb` A String for the verb. // * `path` A String path to lookup. // * `params` An Object of Params pulled from the URI or passed directly. // // ### Returns // // Either returns the value returned by the route callback or raises a 404 Not Found error. // runRoute: function(verb, path, params, target) { var app = this, route = this.lookupRoute(verb, path), context, wrapped_route, arounds, around, befores, before, callback_args, final_returned; this.log('runRoute', [verb, path].join(' ')); this.trigger('run-route', {verb: verb, path: path, params: params}); if (typeof params == 'undefined') { params = {}; } $.extend(params, this._parseQueryString(path)); if (route) { this.trigger('route-found', {route: route}); // pull out the params from the path if ((path_params = route.path.exec(this.routablePath(path))) !== null) { // first match is the full path path_params.shift(); // for each of the matches $.each(path_params, function(i, param) { // if theres a matching param name if (route.param_names[i]) { // set the name to the match params[route.param_names[i]] = _decode(param); } else { // initialize 'splat' if (!params.splat) { params.splat = []; } params.splat.push(_decode(param)); } }); } // set event context context = new this.context_prototype(this, verb, path, params, target); // ensure arrays arounds = this.arounds.slice(0); befores = this.befores.slice(0); // set the callback args to the context + contents of the splat callback_args = [context].concat(params.splat); // wrap the route up with the before filters wrapped_route = function() { var returned; while (befores.length > 0) { before = befores.shift(); // check the options if (app.contextMatchesOptions(context, before[0])) { returned = before[1].apply(context, [context]); if (returned === false) { return false; } } } app.last_route = route; context.trigger('event-context-before', {context: context}); returned = route.callback.apply(context, callback_args); context.trigger('event-context-after', {context: context}); return returned; }; $.each(arounds.reverse(), function(i, around) { var last_wrapped_route = wrapped_route; wrapped_route = function() { return around.apply(context, [last_wrapped_route]); }; }); try { final_returned = wrapped_route(); } catch(e) { this.error(['500 Error', verb, path].join(' '), e); } return final_returned; } else { return this.notFound(verb, path); } }, // Matches an object of options against an `EventContext` like object that // contains `path` and `verb` attributes. Internally Sammy uses this // for matching `before()` filters against specific options. You can set the // object to _only_ match certain paths or verbs, or match all paths or verbs _except_ // those that match the options. // // ### Example // // var app = $.sammy(), // context = {verb: 'get', path: '#/mypath'}; // // // match against a path string // app.contextMatchesOptions(context, '#/mypath'); //=> true // app.contextMatchesOptions(context, '#/otherpath'); //=> false // // equivilent to // app.contextMatchesOptions(context, {only: {path:'#/mypath'}}); //=> true // app.contextMatchesOptions(context, {only: {path:'#/otherpath'}}); //=> false // // match against a path regexp // app.contextMatchesOptions(context, /path/); //=> true // app.contextMatchesOptions(context, /^path/); //=> false // // match only a verb // app.contextMatchesOptions(context, {only: {verb:'get'}}); //=> true // app.contextMatchesOptions(context, {only: {verb:'post'}}); //=> false // // match all except a verb // app.contextMatchesOptions(context, {except: {verb:'post'}}); //=> true // app.contextMatchesOptions(context, {except: {verb:'get'}}); //=> false // // match all except a path // app.contextMatchesOptions(context, {except: {path:'#/otherpath'}}); //=> true // app.contextMatchesOptions(context, {except: {path:'#/mypath'}}); //=> false // contextMatchesOptions: function(context, match_options, positive) { // empty options always match var options = match_options; if (typeof options === 'undefined' || options == {}) { return true; } if (typeof positive === 'undefined') { positive = true; } // normalize options if (typeof options === 'string' || _isFunction(options.test)) { options = {path: options}; } if (options.only) { return this.contextMatchesOptions(context, options.only, true); } else if (options.except) { return this.contextMatchesOptions(context, options.except, false); } var path_matched = true, verb_matched = true; if (options.path) { // wierd regexp test if (_isFunction(options.path.test)) { path_matched = options.path.test(context.path); } else { path_matched = (options.path.toString() === context.path); } } if (options.verb) { verb_matched = options.verb === context.verb; } return positive ? (verb_matched && path_matched) : !(verb_matched && path_matched); }, // Delegates to the `location_proxy` to get the current location. // See `Sammy.HashLocationProxy` for more info on location proxies. getLocation: function() { return this.location_proxy.getLocation(); }, // Delegates to the `location_proxy` to set the current location. // See `Sammy.HashLocationProxy` for more info on location proxies. // // ### Arguments // // * `new_location` A new location string (e.g. '#/') // setLocation: function(new_location) { return this.location_proxy.setLocation(new_location); }, // Swaps the content of `$element()` with `content` // You can override this method to provide an alternate swap behavior // for `EventContext.partial()`. // // ### Example // // var app = $.sammy(function() { // // // implements a 'fade out'/'fade in' // this.swap = function(content) { // this.$element().hide('slow').html(content).show('slow'); // } // // get('#/', function() { // this.partial('index.html.erb') // will fade out and in // }); // // }); // swap: function(content) { return this.$element().html(content); }, // This thows a '404 Not Found' error by invoking `error()`. // Override this method or `error()` to provide custom // 404 behavior (i.e redirecting to / or showing a warning) notFound: function(verb, path) { var ret = this.error(['404 Not Found', verb, path].join(' ')); return (verb === 'get') ? ret : true; }, // The base error handler takes a string `message` and an `Error` // object. If `raise_errors` is set to `true` on the app level, // this will re-throw the error to the browser. Otherwise it will send the error // to `log()`. Override this method to provide custom error handling // e.g logging to a server side component or displaying some feedback to the // user. error: function(message, original_error) { if (!original_error) { original_error = new Error(); } original_error.message = [message, original_error.message].join(' '); this.trigger('error', {message: original_error.message, error: original_error}); if (this.raise_errors) { throw(original_error); } else { this.log(original_error.message, original_error); } }, _checkLocation: function() { var location, returned; // get current location location = this.getLocation(); // compare to see if hash has changed if (location != this.last_location) { // reset last location this.last_location = location; // lookup route for current hash returned = this.runRoute('get', location); } return returned; }, _checkFormSubmission: function(form) { var $form, path, verb, params, returned; this.trigger('check-form-submission', {form: form}); $form = $(form); path = $form.attr('action'); verb = $.trim($form.attr('method').toString().toLowerCase()); if (!verb || verb == '') { verb = 'get'; } this.log('_checkFormSubmission', $form, path, verb); if (verb === 'get') { this.setLocation(path + '?' + $form.serialize()); returned = false; } else { params = $.extend({}, this._parseFormParams($form)); returned = this.runRoute(verb, path, params, form.get(0)); }; return (typeof returned == 'undefined') ? false : returned; }, _parseFormParams: function($form) { var params = {}, form_fields = $form.serializeArray(), i; for (i = 0; i < form_fields.length; i++) { params = this._parseParamPair(params, form_fields[i].name, form_fields[i].value); } return params; }, _parseQueryString: function(path) { var params = {}, parts, pairs, pair, i; parts = path.match(QUERY_STRING_MATCHER); if (parts) { pairs = parts[1].split('&'); for (i = 0; i < pairs.length; i++) { pair = pairs[i].split('='); params = this._parseParamPair(params, _decode(pair[0]), _decode(pair[1])); } } return params; }, _parseParamPair: function(params, key, value) { if (params[key]) { if (_isArray(params[key])) { params[key].push(value); } else { params[key] = [params[key], value]; } } else { params[key] = value; } return params; }, _listen: function(name, callback) { return this.$element().bind([name, this.eventNamespace()].join('.'), callback); }, _unlisten: function(name, callback) { return this.$element().unbind([name, this.eventNamespace()].join('.'), callback); } }); // `Sammy.EventContext` objects are created every time a route is run or a // bound event is triggered. The callbacks for these events are evaluated within a `Sammy.EventContext` // This within these callbacks the special methods of `EventContext` are available. // // ### Example // // $.sammy(function() { with(this) { // // The context here is this Sammy.Application // get('#/:name', function() { with(this) { // // The context here is a new Sammy.EventContext // if (params['name'] == 'sammy') { // partial('name.html.erb', {name: 'Sammy'}); // } else { // redirect('#/somewhere-else') // } // }}); // }}); // // Initialize a new EventContext // // ### Arguments // // * `app` The `Sammy.Application` this event is called within. // * `verb` The verb invoked to run this context/route. // * `path` The string path invoked to run this context/route. // * `params` An Object of optional params to pass to the context. Is converted // to a `Sammy.Object`. // * `target` a DOM element that the event that holds this context originates // from. For post, put and del routes, this is the form element that triggered // the route. // Sammy.EventContext = function(app, verb, path, params, target) { this.app = app; this.verb = verb; this.path = path; this.params = new Sammy.Object(params); this.target = target; }; Sammy.EventContext.prototype = $.extend({}, Sammy.Object.prototype, { // A shortcut to the app's `$element()` $element: function() { return this.app.$element(); }, // Used for rendering remote templates or documents within the current application/DOM. // By default Sammy and `partial()` know nothing about how your templates // should be interpeted/rendered. This is easy to change, though. `partial()` looks // for a method in `EventContext` that matches the extension of the file you're // fetching (e.g. 'myfile.template' will look for a template() method, 'myfile.haml' => haml(), etc.) // If no matching render method is found it just takes the file contents as is. // // If you're templates have different (or no) extensions, and you want to render them all // through the same engine, you can set the default/fallback template engine on the app level // by setting `app.template_engine` to the name of the engine or a `function() {}` // // ### Caching // // If you use the `Sammy.Cache` plugin, remote requests will be automatically cached unless // you explicitly set `cache_partials` to `false` // // ### Example // // There are a couple different ways to use `partial()`: // // partial('doc.html'); // //=> Replaces $element() with the contents of doc.html // // use(Sammy.Template); // //=> includes the template() method // partial('doc.template', {name: 'Sammy'}); // //=> Replaces $element() with the contents of doc.template run through `template()` // // partial('doc.html', function(data) { // // data is the contents of the template. // $('.other-selector').html(data); // }); // // ### Iteration/Arrays // // If the data object passed to `partial()` is an Array, `partial()` // will itterate over each element in data calling the callback with the // results of interpolation and the index of the element in the array. // // use(Sammy.Template); // // item.template => "<li>I'm an item named <%= name %></li>" // partial('item.template', [{name: "Item 1"}, {name: "Item 2"}]) // //=> Replaces $element() with: // // <li>I'm an item named Item 1</li><li>I'm an item named Item 2</li> // partial('item.template', [{name: "Item 1"}, {name: "Item 2"}], function(rendered, i) { // rendered; //=> <li>I'm an item named Item 1</li> // for each element in the Array // i; // the 0 based index of the itteration // }); // partial: function(path, data, callback) { var file_data, wrapped_callback, engine, data_array, cache_key = 'partial:' + path, context = this; // engine setup if ((engine = path.match(/\.([^\.]+)$/))) { engine = engine[1]; } // set the engine to the default template engine if no match is found if ((!engine || !_isFunction(context[engine])) && this.app.template_engine) { engine = this.app.template_engine; } if (engine && !_isFunction(engine) && _isFunction(context[engine])) { engine = context[engine]; } if (!callback && _isFunction(data)) { // callback is in the data position callback = data; data = {}; } data_array = (_isArray(data) ? data : [data || {}]); wrapped_callback = function(response) { var new_content = response, all_content = ""; $.each(data_array, function(i, idata) { if (_isFunction(engine)) { new_content = engine.apply(context, [response, idata]); } // collect the content all_content += new_content; // if callback exists call it for each iteration if (callback) { // return the result of the callback // (you can bail the loop by returning false) return callback.apply(context, [new_content, i]); } }); if (!callback) { context.swap(all_content); } context.trigger('changed'); }; if (this.app.cache_partials && this.cache(cache_key)) { // try to load the template from the cache wrapped_callback.apply(context, [this.cache(cache_key)]); } else { // the template wasnt cached, we need to fetch it $.get(path, function(response) { if (context.app.cache_partials) { context.cache(cache_key, response); } wrapped_callback.apply(context, [response]); }); } }, // Changes the location of the current window. If `to` begins with // '#' it only changes the document's hash. If passed more than 1 argument // redirect will join them together with forward slashes. // // ### Example // // redirect('#/other/route'); // // equivilent to // redirect('#', 'other', 'route'); // redirect: function() { var to, args = _makeArray(arguments), current_location = this.app.getLocation(); if (args.length > 1) { args.unshift('/'); to = this.join.apply(this, args); } else { to = args[0]; } this.trigger('redirect', {to: to}); this.app.last_location = this.path; this.app.setLocation(to); if (current_location == to) { this.app.trigger('location-changed'); } }, // Triggers events on `app` within the current context. trigger: function(name, data) { if (typeof data == 'undefined') { data = {}; } if (!data.context) { data.context = this; } return this.app.trigger(name, data); }, // A shortcut to app's `eventNamespace()` eventNamespace: function() { return this.app.eventNamespace(); }, // A shortcut to app's `swap()` swap: function(contents) { return this.app.swap(contents); }, // Raises a possible `notFound()` error for the current path. notFound: function() { return this.app.notFound(this.verb, this.path); }, // //=> Sammy.EventContext: get #/ {} toString: function() { return "Sammy.EventContext: " + [this.verb, this.path, this.params].join(' '); } }); // An alias to Sammy $.sammy = window.Sammy = Sammy; })(jQuery); (function($) { if (!Mustache) { /* Shamless port of http://github.com/defunkt/mustache by Jan Lehnardt <jan@apache.org>, Alexander Lang <alex@upstream-berlin.com>, Sebastian Cohnen <sebastian.cohnen@googlemail.com> Thanks @defunkt for the awesome code. See http://github.com/defunkt/mustache for more info. */ var Mustache = function() { var Renderer = function() {}; Renderer.prototype = { otag: "{{", ctag: "}}", pragmas: {}, buffer: [], render: function(template, context, partials, in_recursion) { // fail fast if(template.indexOf(this.otag) == -1) { if(in_recursion) { return template; } else { this.send(template); } } if(!in_recursion) { this.buffer = []; } template = this.render_pragmas(template); var html = this.render_section(template, context, partials); if(in_recursion) { return this.render_tags(html, context, partials, in_recursion); } this.render_tags(html, context, partials, in_recursion); }, /* Sends parsed lines */ send: function(line) { if(line != "") { this.buffer.push(line); } }, /* Looks for %PRAGMAS */ render_pragmas: function(template) { // no pragmas if(template.indexOf(this.otag + "%") == -1) { return template; } var that = this; var regex = new RegExp(this.otag + "%([\\w_-]+) ?([\\w]+=[\\w]+)?" + this.ctag); return template.replace(regex, function(match, pragma, options) { that.pragmas[pragma] = {}; if(options) { var opts = options.split("="); that.pragmas[pragma][opts[0]] = opts[1]; } return ""; // ignore unknown pragmas silently }); }, /* Tries to find a partial in the global scope and render it */ render_partial: function(name, context, partials) { if(typeof(context[name]) != "object") { throw({message: "subcontext for '" + name + "' is not an object"}); } if(!partials || !partials[name]) { throw({message: "unknown_partial"}); } return this.render(partials[name], context[name], partials, true); }, /* Renders boolean and enumerable sections */ render_section: function(template, context, partials) { if(template.indexOf(this.otag + "#") == -1) { return template; } var that = this; // CSW - Added "+?" so it finds the tighest bound, not the widest var regex = new RegExp(this.otag + "\\#(.+)" + this.ctag + "\\s*([\\s\\S]+?)" + this.otag + "\\/\\1" + this.ctag + "\\s*", "mg"); // for each {{#foo}}{{/foo}} section do... return template.replace(regex, function(match, name, content) { var value = that.find(name, context); if(that.is_array(value)) { // Enumerable, Let's loop! return that.map(value, function(row) { return that.render(content, that.merge(context, that.create_context(row)), partials, true); }).join(""); } else if(value) { // boolean section return that.render(content, context, partials, true); } else { return ""; } }); }, /* Replace {{foo}} and friends with values from our view */ render_tags: function(template, context, partials, in_recursion) { // tit for tat var that = this; var new_regex = function() { return new RegExp(that.otag + "(=|!|>|\\{|%)?([^\/#]+?)\\1?" + that.ctag + "+", "g"); }; var regex = new_regex(); var lines = template.split("\n"); for (var i=0; i < lines.length; i++) { lines[i] = lines[i].replace(regex, function(match, operator, name) { switch(operator) { case "!": // ignore comments return match; case "=": // set new delimiters, rebuild the replace regexp that.set_delimiters(name); regex = new_regex(); return ""; case ">": // render partial return that.render_partial(name, context, partials); case "{": // the triple mustache is unescaped return that.find(name, context); default: // escape the value return that.escape(that.find(name, context)); } }, this); if(!in_recursion) { this.send(lines[i]); } } return lines.join("\n"); }, set_delimiters: function(delimiters) { var dels = delimiters.split(" "); this.otag = this.escape_regex(dels[0]); this.ctag = this.escape_regex(dels[1]); }, escape_regex: function(text) { // thank you Simon Willison if(!arguments.callee.sRE) { var specials = [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\' ]; arguments.callee.sRE = new RegExp( '(\\' + specials.join('|\\') + ')', 'g' ); } return text.replace(arguments.callee.sRE, '\\$1'); }, /* find `name` in current `context`. That is find me a value from the view object */ find: function(name, context) { name = this.trim(name); if(typeof context[name] === "function") { return context[name].apply(context); } if(context[name] !== undefined) { return context[name]; } // silently ignore unkown variables return ""; }, // Utility methods /* Does away with nasty characters */ escape: function(s) { return s.toString().replace(/[&"<>\\]/g, function(s) { switch(s) { case "&": return "&amp;"; case "\\": return "\\\\";; case '"': return '\"';; case "<": return "&lt;"; case ">": return "&gt;"; default: return s; } }); }, /* Merges all properties of object `b` into object `a`. `b.property` overwrites a.property` */ merge: function(a, b) { var _new = {}; for(var name in a) { if(a.hasOwnProperty(name)) { _new[name] = a[name]; } }; for(var name in b) { if(b.hasOwnProperty(name)) { _new[name] = b[name]; } }; return _new; }, // by @langalex, support for arrays of strings create_context: function(_context) { if(this.is_object(_context)) { return _context; } else if(this.pragmas["IMPLICIT-ITERATOR"]) { var iterator = this.pragmas["IMPLICIT-ITERATOR"].iterator || "."; var ctx = {}; ctx[iterator] = _context return ctx; } }, is_object: function(a) { return a && typeof a == "object" }, /* Thanks Doug Crockford JavaScript — The Good Parts lists an alternative that works better with frames. Frames can suck it, we use the simple version. */ is_array: function(a) { return (a && typeof a === "object" && a.constructor === Array); }, /* Gets rid of leading and trailing whitespace */ trim: function(s) { return s.replace(/^\s*|\s*$/g, ""); }, /* Why, why, why? Because IE. Cry, cry cry. */ map: function(array, fn) { if (typeof array.map == "function") { return array.map(fn) } else { var r = []; var l = array.length; for(i=0;i<l;i++) { r.push(fn(array[i])); } return r; } } }; return({ name: "mustache.js", version: "0.2.2", /* Turns a template and view into HTML */ to_html: function(template, view, partials, send_fun) { var renderer = new Renderer(); if(send_fun) { renderer.send = send_fun; } renderer.render(template, view, partials); return renderer.buffer.join("\n"); } }); }(); } // Ensure Mustache Sammy = Sammy || {}; // <tt>Sammy.Mustache</tt> provides a quick way of using mustache style templates in your app. // The plugin itself includes the awesome mustache.js lib created and maintained by Jan Lehnardt // at http://github.com/janl/mustache.js // // Mustache is a clever templating system that relys on double brackets {{}} for interpolation. // For full details on syntax check out the original Ruby implementation created by Chris Wanstrath at // http://github.com/defunkt/mustache // // By default using Sammy.Mustache in your app adds the <tt>mustache()</tt> method to the EventContext // prototype. However, just like <tt>Sammy.Template</tt> you can change the default name of the method // by passing a second argument (e.g. you could use the ms() as the method alias so that all the template // files could be in the form file.ms instead of file.mustache) // // ### Example #1 // // The template (mytemplate.ms): // // <h1>\{\{title\}\}<h1> // // Hey, {{name}}! Welcome to Mustache! // // The app: // // var $.app = $.sammy(function() { // // include the plugin and alias mustache() to ms() // this.use(Sammy.Mustache, 'ms'); // // this.get('#/hello/:name', function() { // // set local vars // this.title = 'Hello!' // this.name = this.params.name; // // render the template and pass it through mustache // this.partial('mytemplate.ms'); // }); // // }); // // If I go to #/hello/AQ in the browser, Sammy will render this to the <tt>body</tt>: // // <h1>Hello!</h1> // // Hey, AQ! Welcome to Mustache! // // // ### Example #2 - Mustache partials // // The template (mytemplate.ms) // // Hey, {{name}}! {{>hello_friend}} // // // The partial (mypartial.ms) // // Say hello to your friend {{friend}}! // // The app: // // var $.app = $.sammy(function() { // // include the plugin and alias mustache() to ms() // this.use(Sammy.Mustache, 'ms'); // // this.get('#/hello/:name/to/:friend', function() { // var context = this; // // // fetch mustache-partial first // $.get('mypartial.ms', function(response){ // context.partials = response; // // // set local vars // context.name = this.params.name; // context.hello_friend = {name: this.params.friend}; // // // render the template and pass it through mustache // context.partial('mytemplate.ms'); // }); // }); // // }); // // If I go to #/hello/AQ/to/dP in the browser, Sammy will render this to the <tt>body</tt>: // // Hey, AQ! Say hello to your friend dP! // // Note: You dont have to include the mustache.js file on top of the plugin as the plugin // includes the full source. // Sammy.Mustache = function(app, method_alias) { // *Helper* Uses Mustache.js to parse a template and interpolate and work with the passed data // // ### Arguments // // * `template` A String template. {{}} Tags are evaluated and interpolated by Mustache.js // * `data` An Object containing the replacement values for the template. // data is extended with the <tt>EventContext</tt> allowing you to call its methods within the template. // * `partials` An Object containing one or more partials (String templates // that are called from the main template). // var mustache = function(template, data, partials) { data = $.extend({}, this, data); partials = $.extend({}, data.partials, partials); return Mustache.to_html(template, data, partials); }; // set the default method name/extension if (!method_alias) method_alias = 'mustache'; app.helper(method_alias, mustache); }; })(jQuery); (function($) { // closure })(jQuery);
// generator: wizzi-lab-artifatcs/lib/js/module/gen/main.js, utc time: Fri, 18 Dec 2015 16:07:50 GMT /** WizziModelProduction script for generating WizziModelTypes and WizziModelFactories of this WizziFactoryPackage. */ var util = require('util'); var path = require('path'); var schema = require('wizzi-schema'); var packageName = 'wizzi-schema'; var wizziSchemaFolder = path.join(__dirname, 'lib', 'wizzi', 'schemas'); var wizziSchemaLabFolder = path.join(__dirname, 'lib', 'wizzi', 'schemas', 'lab'); var wizziModelFolder = path.join(__dirname, 'lib', 'wizzi', 'models'); function generate(name) { var schemaIttfDocumentPath = path.join(wizziSchemaFolder, name + '.wizzischema.ittf'); var modelPath = path.join(wizziModelFolder, name + '-model.g.js'); var factoryPath = path.join(wizziModelFolder, name + '-factory.g.js'); var labPath = path.join(wizziSchemaLabFolder, name + '-test.g.js'); var jsondocsPath = path.join(wizziModelFolder, name + '-schema.g.json'); var htmldocsPath = path.join(wizziModelFolder, name + '-schema.g.html'); schema.executeSchemaGenerationProcess(schemaIttfDocumentPath, modelPath, factoryPath, labPath, jsondocsPath, htmldocsPath, {}, function(err, result) { if (err) { throw new Error('Package: ' + packageName + '.WizziModelProduction error: ' + util.inspect(err, { depth: null })); } }); } // Expose the execute (WizziModelProductions) function var md = module.exports = {}; md.execute = function() { generate('wizzischema'); }; // CLI execution md.execute();
// Constructor function Color(r, g, b) { this.r = r; this.g = g; this.b = b; } // Instance methods Color.prototype.string = function() { return 'rgb('+this.r+','+this.g+','+this.b+')'; }; // Class methods // Export class module.exports = Color;
'use strict'; module.exports = function (obj, destName, altNames) { if (!obj || !destName || !altNames || !Array.isArray(altNames)) { return obj; } for (var i = 0, j = altNames.length; i < j; i++) { if (obj[destName]) { return obj; } if (obj[altNames[i]]) { obj[destName] = obj[altNames[i]]; } } return obj; };
"use strict"; const { data } = require("sdk/self"); const { Cc, Ci } = require("chrome"); function alert(title, msg, status) { let image; if (status === 0) image = data.url("success.png"); else image = data.url("warning.png"); let win = Cc['@mozilla.org/embedcomp/window-watcher;1']. getService(Ci.nsIWindowWatcher). openWindow(null, 'chrome://global/content/alerts/alert.xul', '_blank', 'chrome,titlebar=no,popup=yes,centerscreen', null); win.arguments = [image, title, msg, false, '']; } exports.alert = alert;
import Place from "../../modules/models/place.js" describe("A place", () => { const place = new Place("Belfast"); it("has a name", () => expect(place.name).toBe("Belfast")) it("has a latitude", () => expect(typeof place.lat).toBe("number")) it("has a longitute", () => expect(typeof place.lng).toBe("number")) })
function WalkontableScrollbar(instance, type) { var that = this; //reference to instance this.instance = instance; this.type = type; this.$table = $(this.instance.wtTable.TABLE); //create elements this.slider = document.createElement('DIV'); this.sliderStyle = this.slider.style; this.sliderStyle.position = 'absolute'; this.sliderStyle.top = '0'; this.sliderStyle.left = '0'; this.sliderStyle.display = 'none'; this.slider.className = 'dragdealer ' + type; this.handle = document.createElement('DIV'); this.handleStyle = this.handle.style; this.handle.className = 'handle'; this.slider.appendChild(this.handle); this.instance.wtTable.parent.appendChild(this.slider); var firstRun = true; this.dragTimeout = null; var dragDelta; var dragRender = function () { that.onScroll(dragDelta); }; this.dragdealer = new Dragdealer(this.slider, { vertical: (type === 'vertical'), horizontal: (type === 'horizontal'), slide: false, speed: 100, animationCallback: function (x, y) { if (firstRun) { firstRun = false; return; } that.skipRefresh = true; dragDelta = type === 'vertical' ? y : x; if (that.dragTimeout === null) { that.dragTimeout = setInterval(dragRender, 100); dragRender(); } }, callback: function (x, y) { that.skipRefresh = false; clearInterval(that.dragTimeout); that.dragTimeout = null; dragDelta = type === 'vertical' ? y : x; that.onScroll(dragDelta); } }); that.skipRefresh = false; } WalkontableScrollbar.prototype.onScroll = function (delta) { if (this.instance.drawn) { var keys = this.type === 'vertical' ? ['offsetRow', 'totalRows', 'countVisibleRows', 'top', 'height'] : ['offsetColumn', 'totalColumns', 'countVisibleColumns', 'left', 'width']; var total = this.instance.getSetting(keys[1]); var display = this.instance.wtTable[keys[2]](); if (total > display) { var newOffset = Math.round(parseInt(this.handleStyle[keys[3]], 10) * total / parseInt(this.slider.style[keys[4]], 10)); //offset = handlePos * totalRows / offsetRows if (delta === 1) { if (this.type === 'vertical') { this.instance.scrollVertical(Infinity).draw(); } else { this.instance.scrollHorizontal(Infinity).draw(); } } else if (newOffset !== this.instance.getSetting(keys[0])) { //is new offset different than old offset if (this.type === 'vertical') { this.instance.scrollVertical(newOffset - this.instance.getSetting(keys[0])).draw(); } else { this.instance.scrollHorizontal(newOffset - this.instance.getSetting(keys[0])).draw(); } } else { this.refresh(); } } } }; /** * Returns what part of the scroller should the handle take * @param viewportCount {Number} number of visible rows or columns * @param totalCount {Number} total number of rows or columns * @return {Number} 0..1 */ WalkontableScrollbar.prototype.getHandleSizeRatio = function (viewportCount, totalCount) { if (!totalCount || viewportCount > totalCount) { return 1; } return viewportCount / totalCount; }; WalkontableScrollbar.prototype.prepare = function () { if (this.skipRefresh) { return; } var ratio , scroll; if (this.type === 'vertical') { ratio = this.getHandleSizeRatio(this.instance.wtTable.countVisibleRows(), this.instance.getSetting('totalRows')); scroll = this.instance.getSetting('scrollV'); } else { ratio = this.getHandleSizeRatio(this.instance.wtTable.countVisibleColumns(), this.instance.getSetting('totalColumns')); scroll = this.instance.getSetting('scrollH'); } if (((ratio === 1 || isNaN(ratio)) && scroll === 'auto') || scroll === 'none') { //isNaN is needed because ratio equals NaN when totalRows/totalColumns equals 0 this.visible = false; } else { this.visible = true; } }; WalkontableScrollbar.prototype.refresh = function () { if (this.skipRefresh) { return; } else if (!this.visible) { this.sliderStyle.display = 'none'; return; } var ratio , sliderSize , handleSize , handlePosition , offsetCount , totalCount , visibleCount , tableOuterWidth = this.$table.outerWidth() , tableOuterHeight = this.$table.outerHeight() , tableWidth = this.instance.hasSetting('width') ? this.instance.getSetting('width') : tableOuterWidth , tableHeight = this.instance.hasSetting('height') ? this.instance.getSetting('height') : tableOuterHeight; if (!tableWidth) { //throw new Error("I could not compute table width. Is the <table> element attached to the DOM?"); return; } if (!tableHeight) { //throw new Error("I could not compute table height. Is the <table> element attached to the DOM?"); return; } if (this.instance.hasSetting('width') && this.instance.wtScroll.wtScrollbarV.visible) { tableWidth -= this.instance.getSetting('scrollbarWidth'); } if (tableWidth > tableOuterWidth + this.instance.getSetting('scrollbarWidth')) { tableWidth = tableOuterWidth; } if (this.instance.hasSetting('height') && this.instance.wtScroll.wtScrollbarH.visible) { tableHeight -= this.instance.getSetting('scrollbarHeight'); } if (tableHeight > tableOuterHeight + this.instance.getSetting('scrollbarHeight')) { tableHeight = tableOuterHeight; } if (this.type === 'vertical') { offsetCount = this.instance.getSetting('offsetRow'); totalCount = this.instance.getSetting('totalRows'); visibleCount = this.instance.wtTable.countVisibleRows(); if (this.instance.wtTable.isLastRowIncomplete()) { visibleCount--; } ratio = this.getHandleSizeRatio(visibleCount, totalCount); sliderSize = tableHeight - 2; //2 is sliders border-width this.sliderStyle.top = this.$table.position().top + 'px'; this.sliderStyle.left = tableWidth - 1 + 'px'; //1 is sliders border-width this.sliderStyle.height = sliderSize + 'px'; } else { //horizontal offsetCount = this.instance.getSetting('offsetColumn'); totalCount = this.instance.getSetting('totalColumns'); visibleCount = this.instance.wtTable.countVisibleColumns(); if (this.instance.wtTable.isLastColumnIncomplete()) { visibleCount--; } ratio = this.getHandleSizeRatio(visibleCount, totalCount); sliderSize = tableWidth - 2; //2 is sliders border-width this.sliderStyle.left = this.$table.position().left + 'px'; this.sliderStyle.top = tableHeight - 1 + 'px'; //1 is sliders border-width this.sliderStyle.width = sliderSize + 'px'; } handleSize = Math.round(sliderSize * ratio); if (handleSize < 10) { handleSize = 15; } handlePosition = Math.floor(sliderSize * (offsetCount / totalCount)); if (handleSize + handlePosition > sliderSize) { handlePosition = sliderSize - handleSize; } if (this.type === 'vertical') { this.handleStyle.height = handleSize + 'px'; this.handleStyle.top = handlePosition + 'px'; } else { //horizontal this.handleStyle.width = handleSize + 'px'; this.handleStyle.left = handlePosition + 'px'; } this.sliderStyle.display = 'block'; };
/* 每个需要插入的节点都作为一个标签,标签可以有自己的属性 每个组件可以定义自己包含的组件的子节点和属性 render(渲染):return里是要返回的节点 constructor(构造):设置state的初始值或者绑定事件 componentDidMount:在渲染后,组件挂载之后执行(组件变为了实际的节点) 在标签节点里可以写函数 */ //CSS require('normalize.css/normalize.css'); require('styles/App.scss'); import React from 'react'; import ReactDOM from 'react-dom' //获取图片相关数据 var imageDatas = require('../data/imageData.json'); //利用自执行函数,将图片名信息转化为图片URL路径信息 //参数:图片数据数组 //返回值:图片URL数组 (function getImageURL(imageDataArr) { for (var i = 0, j = imageDataArr.length; i < j; i++) { var singleImageData = imageDataArr[i]; //真实路径 singleImageData.imageURL = require('../images/' + singleImageData.filename); imageDataArr[i] = singleImageData; } return imageDataArr; })(imageDatas); /*获取区间内的一个随机值,用途图片随机定位*/ function getRangeRandom(low, high) { return Math.ceil(Math.random() * (high - low) + low); } /*获取0-30度之间的正负任意值*/ function get30DegRandom() { return (Math.random() > 0.5 ? '' : '-' + Math.ceil(Math.random() * 30)); } //单幅画的主组件 class ImgFigure extends React.Component { /*imgFigures的点击处理函数*/ handleClick = (e) => { //调用的是对应的props的inverse值,而不是函数inverse //因为this是在ImgFigure的 if (this.props.arrage.isCenter) { this.props.inverse(); } else { this.props.center(); } e.stopPropagation(); e.preventDefault(); } render() { //保存style属性的对象 var styleObj = {}; //如果props属性中指定了这张图片的位置,则使用 if (this.props.arrage.pos) { //自定义标签有属性 styleObj = this.props.arrage.pos; } //如果图片的旋转角度有值并且不为0,添加角度 if (this.props.arrage.rotate) { ['MozTransform', 'msTransform', 'WebkitTransform', 'transform'].forEach(function(value) { styleObj[value] = 'rotate(' + this.props.arrage.rotate + 'deg)'; }.bind(this)); } if (this.props.arrage.isCenter) { styleObj.zIndex = 11; } var imgFigureClassName = "img-figure"; //如果翻转,添加对应类名 imgFigureClassName += this.props.arrage.isInverse ? ' is-inverse' : ''; return ( //img-figure已经定义了绝对定位,利用style来赋值left和top <figure className={imgFigureClassName} style={styleObj} onClick={this.handleClick}> <img src={this.props.data.imageURL} alt={this.props.data.title}/> <figcaption> <h2 className="img-title">{this.props.data.title}</h2> <div className="img-back" onClick={this.handleClick}> <p> {this.props.data.desc} </p> </div> </figcaption> </figure> ) } } class ControllerUnit extends React.Component { handleClick = (e) => { //如果点击的是当前正在选中态的按钮,则翻转图片,否则将对应的图片居中 if (this.props.arrage.isCenter) { this.props.inverse(); } else { this.props.center(); } e.preventDefault(); e.stopPropagation(); } render() { var controllerUintClassName = "controller-unit"; //如果对应的是居中的图片,显示控制按钮的居中态 if (this.props.arrage.isCenter) { controllerUintClassName += " is-center"; if (this.props.arrage.isInverse) { controllerUintClassName += " is-inverse"; } } return ( <span className={controllerUintClassName} onClick={this.handleClick}></span> ); } } //站点基本骨架 class AppComponent extends React.Component { constructor(props) { super(props) //初始定位 //常量 this.Constant = { centerPos: { left: 0, right: 0 }, hPosRange: { //水平方向取值范围 //左分区x的取值范围 leftSecX: [0, 0], //右分区x的取值范围 rightSecX: [0, 0], //水平方向y的取值范围 y: [0, 0] }, vPosRange: { //垂直方向取值范围 //垂直方向x的取值范围 x: [0, 0], //上分区 topY: [0, 0] } }; //state初始化 //state变化,视图会重新渲染 this.state = { //对象里存的是图片位置 imgsArrageArr: [ // pos:{ // left:'0', // top:'0' // }, // rotate:0, //旋转角度 // isInverse:false, //图片正面 // isCenter:false //图片是否居中 ] }; } //组件加载以后,为每张图计算其位置的范围 //初始化 componentDidMount() { //首先拿到舞台的大小 //stage是标签 //这里获取refs的节点 var stageDOM = ReactDOM.findDOMNode(this.refs.stage), stageW = stageDOM.scrollWidth, stageH = stageDOM.scrollHeight, halfStageW = Math.ceil(stageW / 2), halfStageH = Math.ceil(stageH / 2); //拿到一个imageFigure的大小 //获取图片节点 var imgFigureDOM = ReactDOM.findDOMNode(this.refs.imgFigure0), imgW = imgFigureDOM.scrollWidth, imgH = imgFigureDOM.scrollHeight, halfImgW = Math.ceil(imgW / 2), halfImgH = Math.ceil(imgH / 2); //中间图片的定位 this.Constant.centerPos = { left: halfStageW - halfImgH, top: halfStageH - halfImgW } //计算左侧,右侧区域图片排布位置的取值范围 this.Constant.hPosRange.leftSecX[0] = -halfImgW; this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3; this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW; this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW; this.Constant.hPosRange.y[0] = -halfImgH; this.Constant.hPosRange.y[1] = stageH - halfImgH; //计算上册区域图片排布位置的取值范围 this.Constant.vPosRange.topY[0] = -halfImgH; this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3; this.Constant.vPosRange.x[0] = halfStageW - imgW; this.Constant.vPosRange.x[1] = halfStageW; //重新排列,并选择中心图片 this.rearrange(0); } /* 翻转图片 @param index 输入当前被执行inverse操作的图片低音的图片信息数组的index值 @return{Function}这是一个闭包函数,其内return一个真正被执行的函数 */ //这里使用闭包的原因是,执行的时候结果是返回的函数,函数里是每一次储存的index和imgsArrageArr,点击的时候执行该函数,利用的是对应的值 inverse = (index) => { return function() { var imgsArrageArr = this.state.imgsArrageArr; imgsArrageArr[index].isInverse = !imgsArrageArr[index].isInverse; this.setState({ imgsArrageArr: imgsArrageArr }); }.bind(this) } /* *重新布局所有图片 *@param centerIndex 指定居中排布那个图片 */ rearrange(centerIndex) { //定义变量并赋值 var imgsArrageArr = this.state.imgsArrageArr, //定位 Constant = this.Constant, //中心位置 centerPos = Constant.centerPos, //水平位置 hPosRange = Constant.hPosRange, //垂直位置 vPosRange = Constant.vPosRange, //水平位置的左取值范围 hPosRangeLeftSecX = hPosRange.leftSecX, //水平位置的右取值范围 hPosRangeRightSecX = hPosRange.rightSecX, //水平位置的y取值范围[0,0] hPosRangeY = hPosRange.y, //垂直位置的Y取值范围 vPosRangeTopY = vPosRange.topY, //垂直位置x的取值范围 vPosRangeX = vPosRange.x, //存储在上侧区域的图片信息 imgsArrageTopArr = [], topImgNum = Math.floor(Math.random() * 2), //取一个或不取[0,2) topImgSpliceIndex = 0, //存储居中图片的状态信息,把居中图片从图片数组中取出 imgsArrageCenterArr = imgsArrageArr.splice(centerIndex, 1); //首先居中,centerIndex的图片,居中的centerIndex的图片不需要旋转 imgsArrageCenterArr[0] = { pos: centerPos, rotate: 0, isCenter: true } //取出可能的索引号,删除了居中图片 topImgSpliceIndex = Math.ceil(Math.random() * (imgsArrageArr.length - topImgNum)); //取出要布局在上侧的图片的状态信息 imgsArrageTopArr = imgsArrageArr.splice(topImgSpliceIndex, topImgNum); //布局位于上侧的图片 //数组没有值,就不会进入函数 imgsArrageTopArr.forEach(function(value, index) { imgsArrageTopArr[index] = { pos: { //给取值定区间 top: getRangeRandom(vPosRangeTopY[0], vPosRangeTopY[1]), //[0,0] left: getRangeRandom(vPosRangeX[0], vPosRangeX[1]) }, rotate: get30DegRandom(), isCenter: false } }) //布局左右两侧的图片 for (var i = 0, j = imgsArrageArr.length, k = j / 2; i < j; i++) { var hPosRangeLORX = null; //前半部分布局左边,右半部分布局右边 if (i < k) { hPosRangeLORX = hPosRangeLeftSecX; } else { hPosRangeLORX = hPosRangeRightSecX; } imgsArrageArr[i] = { pos: { top: getRangeRandom(hPosRangeY[0], hPosRangeY[1]), left: getRangeRandom(hPosRangeLORX[0], hPosRangeLORX[1]) }, rotate: get30DegRandom(), isCenter: false } } //将填充上半区域的值填充回去 if (imgsArrageTopArr && imgsArrageTopArr[0]) { imgsArrageArr.splice(topImgSpliceIndex, 0, imgsArrageTopArr[0]); } //将填充中间区域的值填充回去 imgsArrageArr.splice(centerIndex, 0, imgsArrageCenterArr[0]); //重新渲染 this.setState({ imgsArrageArr: imgsArrageArr }); } /*利用rearrange函数,居中对应index的图片 @param index,需要悲剧中的图片的信息数组对应的index @return {Function} */ center(index) { return function() { this.rearrange(index); }.bind(this); } render() { //控制组件 var controllerUnits = [], //保存图片信息 imgFigures = []; imageDatas.forEach(function(value, index) { //如果没有这个状态对象,就初始化,定位到左上角 if (!this.state.imgsArrageArr[index]) { this.state.imgsArrageArr[index] = { pos: { left: 0, top: 0 }, rotate: 0, isInverse: false, isCenter: false }; } //将单个图片组件存入数组 //{"imgFigure"+index}生成每个图片的索引 //绑定react compontent到函数中 //标签可以是对象,在其他地方可以获得标签对象,并调用其中的属性 //调用封装的函数没有什么两样,同样通过props的方式 //key是新特性,给react自己重新渲染的时候调用 //给标签传入属性,在别处调用 imgFigures.push(<ImgFigure data={value} key={index} ref={"imgFigure"+index} arrage={this.state.imgsArrageArr[index]} inverse={this.inverse(index)} center={this.center(index)}/>) controllerUnits.push(<ControllerUnit key={index} arrage={this.state.imgsArrageArr[index]} inverse={this.inverse(index)} center={this.center(index)}/>); }.bind(this)); return ( <section className="stage" ref="stage"> <section className="img-sec"> {imgFigures} </section> <nav className="controller-nav"> {controllerUnits} </nav> </section> ); } } AppComponent.defaultProps = {}; export default AppComponent;
/** * Trabajo Final de Grado - FirewallTool * Universidad Nacional de Itapua * Facultad de Ingenieria. * User: Raul Benitez Netto * Date: 11/08/13 * Time: 20:19 */ function ControllerComponents (raphael, graphic_network_id){ var thiz = this; var _raphael = raphael; var _graphic_network_id = graphic_network_id; var _simulation_controller; var _index = 1; var _cont_package = 0; var _objects_collection = {}; var _packages_collection = {}; var _connections_objects = []; var btn_run_simulation = $('#btn-run-simulation'); var btn_reset_simulation = $('#btn-reset-simulation'); this.getPackagesObjects = function (){ return _packages_collection; } this.getPackagesObject = function (index){ return _packages_collection[index]; } this.getNetworkObjects = function (){ return _objects_collection; }; /* Get any objects drawn on dashboard (public)*/ this.getNetworkObject = function (index){ return getNetworkObject(index); }; /* Get any objects drawn on dashboard*/ var getNetworkObject = function (index){ return _objects_collection[index]; }; /* Event to let drag and drop a packages above an object on dashboard*/ var packagesEvent = function () { var components = null; var circles = []; $(".draggable-package").draggable({ helper: "clone", start: function (ev, ui){ components = $('.'+ALLOW_PACKAGES_SOURCE); }, drag: function (ev, ui){ if(components != null){ components.each(function() { var elem = $(this); var x = parseFloat(elem.attr('x')); var y = parseFloat(elem.attr('y')); var obj = _raphael.circle(x+16,y+16,24).attr({stroke: 'red'}); $(obj.node).hover(function (e) { $(e.target).attr({ 'opacity': 0.2, 'stroke': 'blue'}); }); circles.push(obj); }); components = null; } }, stop: function (event, ui) { var top = ui.position.top; var left = ui.position.left - DELTA_LEFT; var elem = $(this); var clone = elem.clone(); var type = clone.data('type'); var src = clone.attr('src'); var obj = event.toElement ? event.toElement : event.relatedTarget; if (obj.classList.contains(ALLOW_PACKAGES_SOURCE)){ var indexPackage = thiz.addComponent(elem.data('type'), top, left + 40); var indexObj = obj.getAttribute('data-index'); thiz.connectPackageWithOrigin(indexPackage, indexObj, true); } for(var i=0; i < circles.length ; i++){ circles[i].remove(); } } }); }; this.addSourceAndDestinationForPackageSaved= function (index_package, source_index, destination_index){ var message = getNetworkObject(index_package); var source = getNetworkObject(source_index); var destination = getNetworkObject(destination_index); message.setOnlySource(source); message.setOnlyDestination(destination); } this.connectPackageWithOrigin = function (indexPackage, indexObj){ _listenerController.setChange(); var message = getNetworkObject(indexPackage); var computer = getNetworkObject(indexObj); computer.addPackageForOrigin(message); } this.connectPackageWithDestination = function(indexPackage, indexObj) { var package = getNetworkObject(indexPackage); var destination = getNetworkObject(indexObj); destination.addPackageForDestination(package); } var addPackagesCollection = function (message){ _packages_collection[message.getIndex()] = message; }; /* get all packages added on dashboard*/ var getPackagesCollectionToArray = function () { var packages = []; for(var k in _packages_collection){ packages.push(_packages_collection[k]); } return packages; } /* This event is called when you click on run simulation*/ var runSimpleSimulationEvent = function () { btn_run_simulation.on('click',function (ev) { ev.preventDefault(); var elem = $(this); if(elem.attr('disabled') == null){ _simulation_controller.runSimpleSimulation(getPackagesCollectionToArray(), thiz.getGraphicNetworkId()); btn_reset_simulation.removeAttr('disabled'); } }); }; var resetSimpleSimulationEvent = function () { btn_reset_simulation.on('click', function (ev) { ev.preventDefault(); var elem = $(this); if(elem.attr('disabled') == null){ _simulation_controller.resetSimpleSimulation(); btn_reset_simulation.attr('disabled', 'disabled'); resetFirewallSaturationVars(); } }); }; var resetFirewallSaturationVars = function(){ firewallInactived = false; changeFirewallState(); count_eth0_packet = 0; count_eth1_packet = 0; count_eth2_packet = 0; current_second = 0; package_accept = 0; package_drop = 0; function_count = 0; tcp_package_accept = 0; tcp_package_drop = 0; udp_package_accept = 0; udp_package_drop = 0; icmp_package_accept = 0; icmp_package_drop = 0; package_counter = 0; //debug_mode = false; $("#eth0-id").text(count_eth0_packet); $("#eth1-id").text(count_eth1_packet); $("#eth2-id").text(count_eth2_packet); $("#clock-id").text(current_second); $("#accept-id").text(package_accept); $("#drop-id").text(package_drop); $("#tcp-accept-id").text(tcp_package_accept); $("#udp-accept-id").text(udp_package_accept); $("#icmp-accept-id").text(icmp_package_accept); $("#tcp-drop-id").text(tcp_package_drop); $("#udp-drop-id").text(udp_package_drop); $("#icmp-drop-id").text(icmp_package_drop); $("#package-second-id").text(0); $("#duration-id").text(0); $("#all-rules").find('tr').each(function(i,tr){ $(tr).removeClass("matched")}); $("#all-policies").find('tr').each(function(i,tr){ $(tr).removeClass("matched")}); }; /* this event let drag and drop any objects on left side of the dashboard and move to main-plain */ var draggableFunction = function () { $(".draggable").draggable({ helper: "clone", stop: function (event, ui) { // event.preventDefault(); var obj = event.toElement ? event.toElement : event.relatedTarget; if (obj.id === HOLDER_ID){ var top = ui.position.top; var left = ui.position.left - DELTA_LEFT; var clone = $(this).clone(); var type = clone.data('type'); var src = clone.attr('src'); thiz.addComponent(type, top, left); } } }); }; /* this event let click on image of network fiber and create connection between objects */ var createConnectionsEvents = function(){ var connectionPoint = []; $('img.connection').off(); $('img.connection').on('click',function(){ var svg = $('.main-plain'); var firewall = thiz.getFirewallAdded(); if (firewall != null ){ firewall.showEthPositions() } var elem_to_connect = $('.'+FOR_CONNECTING_CLASS); var r = _raphael; // var controlFactory; svg.css('cursor','pointer'); elem_to_connect.css('cursor','crosshair'); elem_to_connect.on('click',function(){ var elem = this; var x = parseFloat(elem.getAttribute('x')) + (IMAGE_WIDTH / 2); var y = parseFloat(elem.getAttribute('y')) + (IMAGE_HEIGHT / 2); var isAdding = elem.classList.contains('point-adding'); if(!isAdding){ if(connectionPoint.length <= 0){ var path = [["M", x, y], ["L", x, y]]; // controlFactory = r.path(path).attr({stroke: "", "stroke-dasharray": ""}); elem.classList.add("point-adding"); connectionPoint.push(elem); svg.mousemove(function (ev) { var left = ev.pageX - DELTA_LEFT; var top = ev.pageY; path[1][1] = left; path[1][2] = top; // controlFactory.attr({path: path}); }); }else{ svg.off('mousemove'); var pointB = elem; var pointA = connectionPoint.pop(); pointA.classList.remove('point-adding'); // controlFactory.remove(); thiz.createGraphicConnections(pointA, pointB); svg.css('cursor','cell'); elem_to_connect.css('cursor','cell').off('click'); elem_to_connect.css('cursor', 'move'); if (firewall != null ){ firewall.hideEthPositions() } } } }); svg.bind("contextmenu",function(e) { e.preventDefault(); var firewall = thiz.getFirewallAdded(); if (firewall != null ){ firewall.hideEthPositions() } svg.css('cursor','cell'); svg.off(); // controlFactory.remove(); elem_to_connect.css('cursor','cell').off('click'); elem_to_connect.css('cursor', 'move'); }); }); }; /* this method in called when you create a new ControllerComponents*/ var init = function () { _simulation_controller = new SimulationController(_raphael); packagesEvent(); runSimpleSimulationEvent(); draggableFunction(); createConnectionsEvents(); resetSimpleSimulationEvent(); }; init(); /*Create a hash with all data of components (network objects) of the dashboard*/ var buildHashComponents = function (){ var components = {}; for(var key in _objects_collection){ var obj = _objects_collection[key]; var params = obj.getAttributeParams(); components[key]= params; } return components } /* create a hash about all connections on dashboard*/ var buildHashConnection = function () { var connections = {}; var connections_objects = _controllerConnections.getConnectionsCollection(); for(var i = 0; i<connections_objects.length; i++){ var elems = connections_objects[i]; var objA = elems.getObjA(); var objB = elems.getObjB(); connections[i.toString()]= { pointA_id: objA.getIndex(), pointB_id: objB.getIndex()}; } return connections; }; var buildHashPackages = function (){ var packages = {}; var h = thiz.getPackagesObjects(); for(var k in h){ var pack = h[k]; packages[k] = pack.getAttributeParams(); } return packages; } //FUNCTIONS /* This function parse the rules table and returns an array with hash attributes*/ var getRulesParameters = function(){ var rules = []; var order = -1; $("#all-rules select, #all-rules input:text, #all-rules input:checkbox:checked").each(function(index, element){ var name = $(element).attr("name"); var value = $(element).val(); var attr = name.match(/table|chain|input_device|output_device|source_ip|source_mask|destination_ip|destination_mask|protocol|source_port|destination_port|connection_states|job|nat_action_ip|nat_action_mask/)[0]; if(attr == "table") order += 1; if(rules[order] == undefined) rules[order] = {}; if(attr == "connection_states"){ (rules[order][attr] == undefined) ? rules[order][attr] = [value] : rules[order][attr].push(value); }else{ rules[order][attr] = value; } }); return rules; }; /* This funcion parse the rules table and returns an array with hash attributes*/ var getPoliciesParameters = function(){ var rules = []; var order = -1; $("#all-policies select").each(function(index, element){ var name = $(element).attr("name"); var value = $(element).val(); var attr = name.match(/table|chain|job/)[0]; if(attr == "table") order += 1; if(rules[order] == undefined) rules[order] = {}; rules[order][attr] = value; }); return rules; }; /* This function parse the rules table and returns an array with hash attributes*/ var getOptionParameters = function(){ var option = {}; $("#option-form select, #option-form input").each(function(index, element){ var name = $(element).attr("name"); var value = $(element).val(); option[name] = value }); return option; }; var getFirewallParameters = function(){ var data = {}; $.each($("#flood-form").serializeArray(), function(index, element){ data[element["name"]] = element["value"]; }); return data; }; this.checkToSaveUpdateDiagram = function (){ var message = {checked: true , msg: ''} var p = thiz.getPackagesObjects(); for(var k in p){ var pack = p[k]; if(pack.haveDestination() == false) { message['checked'] = false; message['msg'] = "You need to target destination for all packages added to diagram"; break; } } //add another think to check before to save/update diagram return message } /*this method is called when you want to 'save as' a diagram from dashboard*/ this.buildDiagram = function(diagramName){ var data= {connections: '', components:''}; var summary_check = thiz.checkToSaveUpdateDiagram(); if(summary_check['checked'] == true){ data['connections'] = buildHashConnection(); data['components'] = buildHashComponents(); data['packages'] = buildHashPackages(); data['graphic_name'] = diagramName; data['option'] = getOptionParameters(); if(thereIsFirewall()){ data['firewall'] = getFirewallParameters(); data['rules'] = getRulesParameters(); data['policies'] = getPoliciesParameters(); } $.ajax({type:'POST', data:data, url: '/dashboard/create_diagram', dataType:'script'}); }else { showFlashMessageTextError(summary_check['msg']); } }; /*this method is called when you want to 'save' (update) a diagram from dashboard*/ this.updateDiagram = function(graphic_network_id){ var data = {}; var summary_check = thiz.checkToSaveUpdateDiagram(); if(summary_check['checked'] == true){ data['connections'] = buildHashConnection(); data['components'] = buildHashComponents(); data['packages'] = buildHashPackages(); data['graphic_network_id'] = graphic_network_id; data['option'] = getOptionParameters(); if(thereIsFirewall()){ data['firewall'] = getFirewallParameters(); data['rules'] = getRulesParameters(); data['policies'] = getPoliciesParameters(); } $.ajax({type:'PATCH', data:data, url: '/dashboard/' + graphic_network_id, dataType:'script'}); }else { showFlashMessageTextError(summary_check['msg']); } }; /*This method is called when you add a component (Any) to dashboard page (main-plain)*/ this.addComponent = function(type, y, x, params ){ _listenerController.setChange(); _index++; var attributes_params = params || $.extend({}, DEFAULT_ATTR_PARAMS[type]) || {}; attributes_params['type'] = type; attributes_params['posX'] = x; attributes_params['posY'] = y; if (attributes_params['id'] === '' || attributes_params['id'] === undefined ) attributes_params['id'] = _index; var oc = eval("new " + type +"()"); if(oc instanceof Package) { oc.setNumber(_cont_package); _cont_package ++; } var pos = oc.init(_raphael, attributes_params); _objects_collection[pos] = oc; if(oc instanceof Firewall) INDEX_FIREWALL = pos; else if(oc instanceof Package) addPackagesCollection(oc); return pos; }; this.remove = function (index) { delete _objects_collection[index]; delete _packages_collection[index]; }; this.removeAllElements = function(){ _raphael.clear(); _connections_objects = []; _objects_collection = {}; _packages_collection = {}; _index = 0; $('.main-plain .tooltip').remove(); _controllerConnections.clear(); _simulation_controller.clear(); _cont_package = 0; }; this.createGraphicConnections = function(pointA, pointB){ var objA = getNetworkObject(pointA.getAttribute('data-index')); var objB = getNetworkObject(pointB.getAttribute('data-index')); if(pointA.classList.contains('eth-class') && objA instanceof Firewall) { objA.setEthPositionToNextConnection(pointA.getAttribute('data-eth-position')); } if(pointB.classList.contains('eth-class') && objB instanceof Firewall) { objB.setEthPositionToNextConnection(pointB.getAttribute('data-eth-position')); } objA.createConnection(objB); } var getRules = function(){ var rules = []; $("#all-rules select, #all-rules input").each(function(index, element){ rules[$(element).attr("name")] = $(element).val(); }); return rules; }; this.getFirewallAdded = function () { return thiz.getNetworkObject(INDEX_FIREWALL) } this.setGraphicNetworkId = function (id){ _graphic_network_id = id; btn_run_simulation.removeAttr('disabled'); }; this.getGraphicNetworkId = function () { return _graphic_network_id; }; }
var clientModule = require('./client.js'); var client = clientModule.create({id : 1}); var tmpNotification = { id : 1, version : 1, source : 1, target : 2, transfer : 1, fileId : 1, filename : "/foo/bar/baz.txt" }; var notifications = []; notifications.push(tmpNotification); // client.getNotifications("localhost", 3301, function(host, port, obj){ // // console.log("Got notifications: " + JSON.stringify(obj)); // }); // client.deleteNotification("localhost", 3301, tmpNotification); // // client.processNotification("localhost", 3301, 1); // client.getFile("localhost", 3301, tmpNotification, function(host, port, notification){ // // console.log(host + port + notification); // }); // client.processNotification("localhost", 3301, tmpNotification); // client.processNotifications("localhost", 3301, notifications); // client.getNotifications("localhost", 3301, {id: 1}); client.subscribe(1, "localhost", 3301);
(function(){ var app = angular.module('home',[]); app.controller('PageController', function(){ this.tab = 1; this.selectTab= function(setTab){ this.tab = setTab || 1; }; this.isSelected= function(checkTab){ return this.tab === checkTab; }; }) app.directive('resumePage', function(){ return{ restrict: 'E', templateUrl: 'resume-page.html', controller:function(){ this.tab = 1; this.selectTab= function(setTab){ this.tab = setTab || 1; }; this.isSelected= function(checkTab){ return this.tab === checkTab; }; }, controllerAs:'resumePageCtrl' }; }); app.directive('homePage', function(){ return{ restrict: 'E', templateUrl: 'home-page.html', controller: function(){ this.tab = 1; this.selectTab= function(setTab){ this.tab = setTab || 1; }; this.isSelected= function(checkTab){ return this.tab === checkTab; }; }, controllerAs:'homePageCtrl' } }); })();
var world = new VIZI.World({ viewport: document.querySelector("#vizicities-viewport"), layersUI: true, picking: true // center: new VIZI.LatLon(40.01000594412381, -105.2727379358738) // Collada }); var controls = new VIZI.ControlsMap(world.camera, { viewport: world.options.viewport }); var pickControls = new VIZI.ControlsMousePick(world.camera, { scene: world.scene }); var descriptionUI = new VIZI.DescriptionUI({ title: "Basic example", body: "This is a basic example showing a 2D basemap, 3D building tiles and a choropleth of population density." }); var mapConfig = { input: { type: "BlueprintInputMapTiles", options: { tilePath: "https://a.tiles.mapbox.com/v3/examples.map-i86l3621/{z}/{x}/{y}@2x.png" } }, output: { type: "BlueprintOutputImageTiles", options: { grids: [{ zoom: 19, tilesPerDirection: 3, cullZoom: 17 }, { zoom: 18, tilesPerDirection: 3, cullZoom: 16 }, { zoom: 17, tilesPerDirection: 3, cullZoom: 15 }, { zoom: 16, tilesPerDirection: 3, cullZoom: 14 }, { zoom: 15, tilesPerDirection: 3, cullZoom: 13 }, { zoom: 14, tilesPerDirection: 3, cullZoom: 12 }, { zoom: 13, tilesPerDirection: 5, cullZoom: 11 }] } }, triggers: [{ triggerObject: "output", triggerName: "initialised", triggerArguments: ["tiles"], actionObject: "input", actionName: "requestTiles", actionArguments: ["tiles"], actionOutput: { tiles: "tiles" // actionArg: triggerArg } }, { triggerObject: "output", triggerName: "gridUpdated", triggerArguments: ["tiles"], actionObject: "input", actionName: "requestTiles", actionArguments: ["tiles"], actionOutput: { tiles: "tiles" // actionArg: triggerArg } }, { triggerObject: "input", triggerName: "tileReceived", triggerArguments: ["image", "tile"], actionObject: "output", actionName: "outputImageTile", actionArguments: ["image", "tile"], actionOutput: { image: "image", // actionArg: triggerArg tile: "tile" } }] }; var switchboardMap = new VIZI.BlueprintSwitchboard(mapConfig); switchboardMap.addToWorld(world); var buildingsConfig = { input: { type: "BlueprintInputGeoJSON", options: { tilePath: "http://vector.mapzen.com/osm/buildings/{z}/{x}/{y}.json" } }, output: { type: "BlueprintOutputBuildingTiles", options: { grids: [{ zoom: 15, tilesPerDirection: 1, cullZoom: 13 }], workerURL: "../../build/vizi-worker.min.js" } }, triggers: [{ triggerObject: "output", triggerName: "initialised", triggerArguments: ["tiles"], actionObject: "input", actionName: "requestTiles", actionArguments: ["tiles"], actionOutput: { tiles: "tiles" // actionArg: triggerArg } }, { triggerObject: "output", triggerName: "gridUpdated", triggerArguments: ["tiles", "newTiles"], actionObject: "input", actionName: "requestTiles", actionArguments: ["tiles"], actionOutput: { tiles: "newTiles" // actionArg: triggerArg } }, { triggerObject: "input", triggerName: "tileReceived", triggerArguments: ["geoJSON", "tile"], actionObject: "output", actionName: "outputBuildingTile", actionArguments: ["buildings", "tile"], actionOutput: { buildings: { process: "map", itemsObject: "geoJSON", itemsProperties: "features", transformation: { outline: "geometry.coordinates", height: "properties.height", minHeight: "properties.min_height" } }, tile: "tile" } }] }; var switchboardBuildings = new VIZI.BlueprintSwitchboard(buildingsConfig); switchboardBuildings.addToWorld(world); var choroplethConfig = { input: { type: "BlueprintInputGeoJSON", options: { path: "./data/sample.geojson" } }, output: { type: "BlueprintOutputChoropleth", options: { colourRange: ["#ffffe5","#f7fcb9","#d9f0a3","#addd8e","#78c679","#41ab5d","#238443","#006837","#004529"], layer: 100, infoUI: true, description: "Number of people per hectare" } }, triggers: [{ triggerObject: "output", triggerName: "initialised", triggerArguments: [], actionObject: "input", actionName: "requestData", actionArguments: [], actionOutput: {} }, { triggerObject: "input", triggerName: "dataReceived", triggerArguments: ["geoJSON"], actionObject: "output", actionName: "outputChoropleth", actionArguments: ["data"], actionOutput: { data: { // Loop through each item in trigger.geoJSON and return a new array of processed values (a map) process: "map", itemsObject: "geoJSON", itemsProperties: "features", // Return a new object for each item with the given properties transformation: { outline: "geometry.coordinates[0]", value: "properties.POPDEN" } } } }] }; var switchboardChoropleth = new VIZI.BlueprintSwitchboard(choroplethConfig); switchboardChoropleth.addToWorld(world); var clock = new VIZI.Clock(); var update = function() { var delta = clock.getDelta(); world.onTick(delta); world.render(); window.requestAnimationFrame(update); }; update();
jest.unmock('../calculator-store'); jest.unmock('../../constants/constants'); jest.unmock('immutable'); jest.unmock('flux/utils'); import { EventType } from '../../constants/constants'; import Immutable from 'immutable'; function buildNumberAddedAction(num) { return { eventType: EventType.NUMBER_ADDED, number: num }; } function buildOperatorAddedAction(op) { return { eventType: EventType.OPERATOR_ADDED, operator: op }; } function buildCalculateValueAction() { return { eventType: EventType.CALCULATE_VALUE } } function buildClearInputAction() { return { eventType: EventType.CLEAR_INPUT } } describe('CalculatorStore', function() { let CalculatorDispatcher; let CalculatorStore; let callback; beforeEach(function() { CalculatorDispatcher = require('../../dispatchers/calculator-dispatcher'); CalculatorStore = require('../calculator-store'); callback = CalculatorDispatcher.register.mock.calls[0][0]; }); it('registers a callback with the dispatcher', function() { expect(CalculatorDispatcher.register.mock.calls.length).toBe(1); }); it('initializes with empty input', function() { let initialDisplayValue = CalculatorStore.getDisplayValue(); expect(initialDisplayValue).toBe(''); }); it('displays multiple digits', function() { callback(buildNumberAddedAction(1)); callback(buildNumberAddedAction(2)); callback(buildNumberAddedAction(3)); let displayValue = CalculatorStore.getDisplayValue(); expect(displayValue).toBe('123'); }); it('displays expresssions digits', function() { callback(buildNumberAddedAction(1)); callback(buildNumberAddedAction(2)); callback(buildNumberAddedAction(3)); callback(buildOperatorAddedAction('+')); callback(buildNumberAddedAction(4)); callback(buildNumberAddedAction(5)); callback(buildNumberAddedAction(6)); let displayValue = CalculatorStore.getDisplayValue(); expect(displayValue).toBe('123 + 456'); }); it('evaluates single digit addition', function() { callback(buildNumberAddedAction(2)); callback(buildOperatorAddedAction('+')); callback(buildNumberAddedAction(5)); callback(buildCalculateValueAction()); expect(CalculatorStore.getDisplayValue()).toBe('7'); }); it('evaluates single digit subtraction', function() { callback(buildNumberAddedAction(8)); callback(buildOperatorAddedAction('-')); callback(buildNumberAddedAction(5)); callback(buildCalculateValueAction()); expect(CalculatorStore.getDisplayValue()).toBe('3'); }); it('evaluates single digit multiplication', function() { callback(buildNumberAddedAction(3)); callback(buildOperatorAddedAction('*')); callback(buildNumberAddedAction(6)); callback(buildCalculateValueAction()); expect(CalculatorStore.getDisplayValue()).toBe('18'); }); it('evaluates single digit division', function() { callback(buildNumberAddedAction(8)); callback(buildOperatorAddedAction('/')); callback(buildNumberAddedAction(4)); callback(buildCalculateValueAction()); expect(CalculatorStore.getDisplayValue()).toBe('2'); }); it('clears input', function() { callback(buildNumberAddedAction(1)); callback(buildNumberAddedAction(2)); callback(buildNumberAddedAction(3)); callback(buildOperatorAddedAction('+')); callback(buildNumberAddedAction(4)); callback(buildNumberAddedAction(5)); callback(buildNumberAddedAction(6)); let initialDisplayValue = CalculatorStore.getDisplayValue(); expect(initialDisplayValue).toBe('123 + 456'); callback(buildClearInputAction()); let clearedDisplayValue = CalculatorStore.getDisplayValue(); expect(clearedDisplayValue).toBe(''); }); it('evaluates 2 digit addition', function() { callback(buildNumberAddedAction(1)); callback(buildNumberAddedAction(2)); callback(buildOperatorAddedAction('+')); callback(buildNumberAddedAction(7)); callback(buildNumberAddedAction(9)); callback(buildCalculateValueAction()); expect(CalculatorStore.getDisplayValue()).toBe('91'); }); it('evaluates 2 digit subtraction', function() { callback(buildNumberAddedAction(9)); callback(buildNumberAddedAction(7)); callback(buildOperatorAddedAction('-')); callback(buildNumberAddedAction(2)); callback(buildNumberAddedAction(5)); callback(buildCalculateValueAction()); expect(CalculatorStore.getDisplayValue()).toBe('72'); }); it('evaluates 2 digit multiplication', function() { callback(buildNumberAddedAction(2)); callback(buildNumberAddedAction(3)); callback(buildOperatorAddedAction('*')); callback(buildNumberAddedAction(3)); callback(buildNumberAddedAction(4)); callback(buildCalculateValueAction()); expect(CalculatorStore.getDisplayValue()).toBe('782'); }); it('evaluates 2 digit division', function() { callback(buildNumberAddedAction(7)); callback(buildNumberAddedAction(2)); callback(buildOperatorAddedAction('/')); callback(buildNumberAddedAction(1)); callback(buildNumberAddedAction(2)); callback(buildCalculateValueAction()); expect(CalculatorStore.getDisplayValue()).toBe('6'); }); it('evaluates multi digit addition', function() { callback(buildNumberAddedAction(1)); callback(buildNumberAddedAction(2)); callback(buildNumberAddedAction(3)); callback(buildNumberAddedAction(4)); callback(buildOperatorAddedAction('+')); callback(buildNumberAddedAction(5)); callback(buildNumberAddedAction(6)); callback(buildNumberAddedAction(7)); callback(buildNumberAddedAction(8)); callback(buildCalculateValueAction()); expect(CalculatorStore.getDisplayValue()).toBe('6912'); }); it('calculates value when a second operator is added', function() { callback(buildNumberAddedAction(1)); callback(buildOperatorAddedAction('+')); callback(buildNumberAddedAction(5)); expect(CalculatorStore.getDisplayValue()).toBe('1 + 5'); callback(buildOperatorAddedAction('+')); expect(CalculatorStore.getDisplayValue()).toBe('6 + '); callback(buildNumberAddedAction(4)); expect(CalculatorStore.getDisplayValue()).toBe('6 + 4'); }); it('displays 0 correctly', function() { callback(buildNumberAddedAction(0)); expect(CalculatorStore.getDisplayValue()).toBe('0'); }); it('clears the input when entering a number after hitting calculate', function() { callback(buildNumberAddedAction(1)); callback(buildOperatorAddedAction('+')); callback(buildNumberAddedAction(3)); callback(buildCalculateValueAction()); expect(CalculatorStore.getDisplayValue()).toBe('4'); callback(buildNumberAddedAction(5)); expect(CalculatorStore.getDisplayValue()).toBe('5'); }); it('ignores calculate value without a second number', function() { callback(buildNumberAddedAction(1)); callback(buildOperatorAddedAction('+')); expect(CalculatorStore.getDisplayValue()).toBe('1 + '); callback(buildCalculateValueAction()); expect(CalculatorStore.getDisplayValue()).toBe('1 + '); }); it('ignore operator without first number', function() { callback(buildOperatorAddedAction('+')); expect(CalculatorStore.getDisplayValue()).toBe(''); }); });
export * from './drawContour'; export * from './drawDetections'; export * from './drawFaceExpressions'; export * from './DrawBox'; export * from './DrawFaceLandmarks'; export * from './DrawTextField'; //# sourceMappingURL=index.js.map
function is_reached() { var founded = 0; for (var key in this.requires) { for (var obj_key in objectives.db) { if (objectives.db[obj_key].reached && objectives.db[obj_key].name == this.requires[key]) { founded++; } } for (var ach_key in badges.db) { if (badges.db[ach_key].reached && badges.db[ach_key].name == this.requires[key]) { founded++; } } } return (this.requires.length == founded); } /** * Returns a random number between min (inclusive) and max (exclusive) */ function random(min, max) { return Math.random() * (max - min) + min; } /** * Returns a random integer between min (inclusive) and max (inclusive) * Using Math.round() knowledge give you a non-uniform distribution! */ function rand(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } String.prototype.capitalizeFirstLetter = function() { return this.charAt(0).toUpperCase() + this.slice(1); }; function sum( obj ) { return Object.keys( obj ) .reduce( function( sum, key ){ return sum + parseFloat( obj[key] ); }, 0 ); } function message(text) { if(text == "A new day."){LogPanel.day++;} //else if (text.includes("Balance ratio")) {} else{LogPanel.messages.push(new LogMessage(false,text));} console.log(text); //console.log(LogPanel.messages); } function tick() { message("A new day."); Player.harvest(); Gatherer.tick(); Civilization.tick(); Dungeon.tick(); Space.tick(); Rally.tick(); Castle.tick(); Lecture.tick(); localStorage.setItem("Player", JSON.stringify(Player)); localStorage.setItem("lectures.db", JSON.stringify(lectures.db)); draw_all(); }
/** * v0.0.1 * * Copyright (c) 2017 * * Date: 2017/5/9 by Heaven */ import React from 'react'; import PropTypes from 'prop-types'; import DOMPurify from 'dompurify'; import classNames from 'classnames'; import ReactScroll from 'react-scroll'; import { SparkScroll } from '../../ReactSparkScroll'; import Modal from '../../Modal'; import ReplyItemHeader from './ReplyItemHeader'; import ReplyItemContent from './ReplyItemContent'; import ReplyItemOperation from './ReplyItemOperation'; import CommentList from '../../../containers/CommentList'; import globalConfig from '../../../globalConfig'; // import { isContentTooLongUtil } from '../../../utils/reply'; import './ReplyItem.css'; export default class ReplyItem extends React.PureComponent { static propTypes = { author: PropTypes.object, commentCount: PropTypes.number, content: PropTypes.string, createdTime: PropTypes.string, // 摘要暂时可能用不上,以后可能用到,比如知乎首页显示的就是摘要信息 excerpt: PropTypes.string, id: PropTypes.string, lastUpdatedTime: PropTypes.string, praiseCount: PropTypes.number, replyWrapElementWidth: PropTypes.number, isFirstReplyItem: PropTypes.bool } static contextTypes = { quietWaterLanguage: PropTypes.object, store: PropTypes.object } constructor (props, context) { super(props, context); const isContentTooLong = false; // TODO 用下面这种方式去预估内容的高度,可以提前判断,但是缺点是内容的高度很难去预估,后面再看看有没有更好的办法吧 // TODO 如果通过ref的方法,虽然准确,但是会导致滚动条由最初的很长变得很短,这种抖动用户不一定能接受 // const isContentTooLong = isContentTooLongUtil( // props.content, props.replyWrapElementWidth, contentSyle, this.context.quietWaterLanguage.languageName // ); this.state = { // we can also make ReplyItemContent show first and get its height,if that,we don't need calculate by // the `isContentTooLong` util function ,but that's not friendly to users. isContentTooLong, // isContentExpanded: !isContentTooLong isContentExpanded: true, isContentEnterViewport: false, showCommentList: false }; this._isMounted = false; } componentDidMount () { this._isMounted = true; } handleContentDidMount = (ele) => { if (ele) { const height = getComputedStyle(ele).height; const heightNumber = height.substring(0, height.indexOf('p')); const isContentTooLong = heightNumber > 400; this.setState({ isContentTooLong, isContentExpanded: !isContentTooLong }); } } handleClickReadAll = () => { ReactScroll.scroller.scrollTo(`qw_${this.props.id}_h`); this.setState({ isContentExpanded: true }); } handleClickFold = () => { // ReactScroll.scroller.scrollTo(`qw_${this.props.id}_ob`); // ob means operation-bottom ReactScroll.scroller.scrollTo(`qw_${this.props.id}_h`); this.setState({ isContentExpanded: false }); } handleClickExpandComment = () => { !this.state.showCommentList ? console.log('加载并展开评论') : console.log('折叠评论'); this.setState({ showCommentList: !this.state.showCommentList }); } // 对于内容较多的item(即需要折叠的),当用户滚动使这个item进入视窗的时候,将与之对应的操作栏设置为fixed // for the item which has much content,when it enter the viewport by scrolling of users, // we should set the corresponding operation bar's style to fixed handleScrollIntoLongContetnItem = (e) => { console.log('进入内容区域'); const newHash = `#qw_${this.props.id}_h`; this.setState({ isContentEnterViewport: true }); const key = globalConfig.sessionStorage.keyOfCurrentReplyItemHash; if (sessionStorage.getItem(key) !== newHash) { sessionStorage.setItem(key, newHash); console.log(`替换sessionStorage中的当前reply为: ${newHash}`); } } handleScrollOutOfLongContetnItem = (e) => { console.log('离开内容区域'); this.setState({ isContentEnterViewport: false }); } handleCancelCommentListModal = () => { this.setState({ showCommentList: false }); } render () { const { id: replyId, author, commentCount, createdTime, lastUpdatedTime, praiseCount, excerpt: _excerpt, content: _content, isFirstReplyItem, replyWrapElementWidth } = this.props; const { isContentTooLong, isContentExpanded, isContentEnterViewport } = this.state; // 很多html文本,如回复和评论都是由后端发过来的,因为所以要进行xss过滤,因为要用dangerouslySetInnerHTML // sanitize all the potential xss text const [excerpt, content] = [_excerpt, _content].map(maybeDirtyHtml => DOMPurify.sanitize(maybeDirtyHtml)); const commonReplyItemContentProps = { content, excerpt, lastUpdatedTime, isContentExpanded }; // 为什么这样做条件判断见下方的注释 // please see below comment if you want to know why judge by this conditions const operationBarClassName = classNames({ 'fixed-operationBar': isContentTooLong && isContentExpanded && isContentEnterViewport }); // TODO 如果回复的开头是图片,那么不应该是'topTop-30',而应该大概是'topTop-80'这里的-80根据图片的高度来定,反正基本要让图片显示完 // TODO 可以只用css实现(选择到第一个),但是不确定是否有跟css无关的逻辑需要判断是否为第一个,暂时先这样 // 在react-scroll-spark中,对于top属性,从上往下滑动时,top离window的top的距离是由负到正 // 而对于bottom属性,从下往上里滑动时,bottom离window的bottom的距离是由正到负 const itemSparkScrollTopTopKey = isFirstReplyItem ? 'topTop-100' : 'topTop-30'; /* eslint-disable */ /* 内容较多且目前内容处于展开状态(即内容全部被显示, isContentExpanded为true就代表内容较多了,因为只有内容较多时 才会存在展开)的才需要绑定滚动事件检测,看是否需要将操作栏fixed,对于内容较少的则不绑定事件,避免浪费性能 just when item which has long content and window displays all of them now, we bind scroll event to fixed operation bar,if there are no many contents, don't bind to improve perf */ return ( <div styleName="wrap" ref={this.handleContentDidMount}> <ReactScroll.Element name={`qw_${replyId}_h`}> <ReplyItemHeader {...author} replyCreatedTime={createdTime} /> </ReactScroll.Element> { this._isMounted && isContentExpanded ? <SparkScroll.div key="ric1" timeline={{ 'topTop+100': { onUp: this.handleScrollOutOfLongContetnItem }, [itemSparkScrollTopTopKey]: { onDown: this.handleScrollIntoLongContetnItem }, 'bottomBottom+60': { onUp: this.handleScrollIntoLongContetnItem }, 'bottomBottom': { onDown: this.handleScrollOutOfLongContetnItem } }} > <ReplyItemContent{...commonReplyItemContentProps}/> </SparkScroll.div> : <ReplyItemContent key="ric2" {...commonReplyItemContentProps} /> } <ReactScroll.Element name={`qw_${replyId}_ob`}> <ReplyItemOperation key="rio" style={{ width: `calc(${replyWrapElementWidth}px - 30px)` }} styleName={operationBarClassName} excerpt={excerpt} authorId={author.userId} replyId={replyId} commentCount={commentCount} praiseCount={praiseCount} isContentTooLong={isContentTooLong} isContentExpanded={isContentExpanded} showCommentList={this.state.showCommentList} onClickReadAll={this.handleClickReadAll} onClickFold={this.handleClickFold} onClickExpandComment={this.handleClickExpandComment} /> </ReactScroll.Element> { this.state.showCommentList && ( this.state.isContentExpanded && this.state.isContentEnterViewport ? <Modal key="m-cl" width="52%" styleName="commentListBox" style={globalConfig.styles.conversationBox} visible onCancel={this.handleCancelCommentListModal} dialogContentElement={ <CommentList replyId={replyId} store={this.context.store} context={this.context} showConversationBtn={false} /> } /> : <CommentList key="cl" styleName="commentList-wrap" replyId={replyId} /> ) } </div> ); /* eslint-disable */ } };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _jsx2 = _interopRequireDefault(require("@babel/runtime/helpers/builtin/jsx")); var _react = _interopRequireDefault(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _reactI18next = require("react-i18next"); var _compose = _interopRequireDefault(require("recompose/compose")); var _pure = _interopRequireDefault(require("recompose/pure")); var _Tooltip = _interopRequireDefault(require("@material-ui/core/Tooltip")); var _IconButton = _interopRequireDefault(require("@material-ui/core/IconButton")); var _History = _interopRequireDefault(require("@material-ui/icons/History")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _ref2 = /*#__PURE__*/ (0, _jsx2.default)(_History.default, { className: "HeaderHistoryButton-icon" }); var HistoryButton = function HistoryButton(_ref) { var t = _ref.t, onClick = _ref.onClick; return (0, _jsx2.default)(_Tooltip.default, { title: t('history.title'), position: "bottom" }, void 0, (0, _jsx2.default)(_IconButton.default, { "aria-label": t('history.title'), className: "HeaderHistoryButton", onClick: onClick }, void 0, _ref2)); }; HistoryButton.propTypes = process.env.NODE_ENV !== "production" ? { t: _propTypes.default.func.isRequired, onClick: _propTypes.default.func.isRequired } : {}; var _default = (0, _compose.default)((0, _reactI18next.translate)(), _pure.default)(HistoryButton); exports.default = _default; //# sourceMappingURL=HistoryButton.js.map
/* eslint-env node */ 'use strict'; const FastbootTransform = require('fastboot-transform'); module.exports = { name: 'ember-offline', options: { nodeAssets: { 'offline-js': { vendor: { include: ['offline.js', 'themes/*'], processTree(input) { return FastbootTransform(input); } } } } }, included(app) { this._super.included.apply(this, arguments); this._ensureThisImport(); let config = this.project.config(app.env); let themes = config.emberOffline.themes; let themesDir = 'vendor/offline-js/themes'; if(!themes) { themes = { theme: 'default', indicator: false, language: 'english', } } if (themes.theme) { this.import(`${themesDir}/offline-theme-${themes.theme}.css`); this.import(`${themesDir}/offline-language-${themes.language}.css`); } if (themes.indicator) { this.import(`${themesDir}/offline-theme-${themes.indicator}-indicator.css`); this.import(`${themesDir}/offline-language-${themes.language}-indicator.css`); } this.import('vendor/offline-js/offline.js'); }, _ensureThisImport() { if (!this.import) { this._findHost = function findHostShim() { let current = this; let app; do { app = current.app || app; } while (current.parent.parent && (current = current.parent)); return app; }; this.import = function importShim(asset, options) { let app = this._findHost(); app.import(asset, options); }; } } };
"use strict"; var fs = require('fs'); var path = require('path'); var dns = require('dns'); var net = require('net'); var util = require("util"); var events = require("events"); var utils = require('./utils'); var sock = require('./line_socket'); var server = require('./server'); var logger = require('./logger'); var config = require('./config'); var constants = require('./constants'); var trans = require('./transaction'); var plugins = require('./plugins'); var async = require('async'); var Address = require('./address').Address; var date_to_str = utils.date_to_str; var existsSync = utils.existsSync; var FsyncWriteStream = require('./fsync_writestream'); var core_consts = require('constants'); var WRITE_EXCL = core_consts.O_CREAT | core_consts.O_TRUNC | core_consts.O_WRONLY | core_consts.O_EXCL; var DENY = constants.deny; var OK = constants.ok; var MAX_UNIQ = 10000; var host = require('os').hostname().replace(/\\/, '\\057').replace(/:/, '\\072'); var fn_re = /^(\d+)_(\d+)_/; // I like how this looks like a person var queue_dir = path.resolve(config.get('queue_dir') || (process.env.HARAKA + '/queue')); var uniq = Math.round(Math.random() * MAX_UNIQ); var MAX_CONCURRENCY = config.get('outbound.concurrency_max') || 100; var delivery_queue = async.queue(function (hmail, cb) { hmail.next_cb = cb; hmail.send() }, MAX_CONCURRENCY); var queue_count = 0; exports.list_queue = function (cb) { this._load_cur_queue("_list_file", cb); } exports.stat_queue = function (cb) { var self = this; this._load_cur_queue("_stat_file", function () { return cb(self.stats()); }); } exports.load_queue = function () { // Initialise and load queue // we create the dir here because this is used when Haraka is running // properly. // no reason not to do this stuff syncronously - we're just loading here if (!existsSync(queue_dir)) { this.logdebug("Creating queue directory " + queue_dir); try { fs.mkdirSync(queue_dir, 493); // 493 == 0755 } catch (err) { if (err.code != 'EEXIST') { throw err; } } } this._load_cur_queue("_add_file"); } exports._load_cur_queue = function (cb_name, cb) { var plugin = this; plugin.loginfo("Loading outbound queue from ", queue_dir); fs.readdir(queue_dir, function (err, files) { if (err) { return plugin.logerror("Failed to load queue directory (" + queue_dir + "): " + err); } plugin.cur_time = new Date(); // set this once so we're not calling it a lot plugin.load_queue_files(cb_name, files); if (cb) cb(); }); } exports.load_queue_files = function (cb_name, files) { var plugin = this; if (files.length === 0) return; this.loginfo("Loading the queue..."); if (config.get('outbound.disabled') && cb_name === '_add_file') { // try again in 1 second if delivery is disabled setTimeout(function () {plugin.load_queue_files(cb_name, files)}, 1000); return; } files.forEach(function (file) { if (/^\./.test(file)) { // dot-file... plugin.logwarn("Removing left over dot-file: " + file); return fs.unlink(file, function () {}); } var hmail = new HMailItem(file, path.join(queue_dir, file)); plugin[cb_name](hmail); }); } exports._add_file = function (hmail) { var self = this; this.loginfo("Adding file: " + hmail.filename); if (hmail.next_process < this.cur_time) { delivery_queue.push(hmail); } else { setTimeout(function () { delivery_queue.push(hmail) }, hmail.next_process - this.cur_time); } } exports._list_file = function (hmail) { // TODO: output more data here console.log("Q: " + hmail.filename); } exports._stat_file = function (hmail) { queue_count++; } exports.stats = function () { // TODO: output more data here var results = { queue_dir: queue_dir, queue_count: queue_count, }; return results; } function _next_uniq () { var result = uniq++; if (uniq >= MAX_UNIQ) { uniq = 1; } return result; } function _fname () { var time = new Date().getTime(); return time + '_0_' + process.pid + "_" + _next_uniq() + '.' + host; } exports.send_email = function () { if (arguments.length === 2) { this.loginfo("Sending email as with a transaction"); return this.send_trans_email(arguments[0], arguments[1]); } var self = this; var from = arguments[0], to = arguments[1], contents = arguments[2]; var next = arguments[3]; this.loginfo("Sending email via params"); var transaction = trans.createTransaction(); this.loginfo("Created transaction: " + transaction.uuid); // set MAIL FROM address, and parse if it's not an Address object if (from instanceof Address) { transaction.mail_from = from; } else { try { from = new Address(from); } catch (err) { return next(DENY, "Malformed from: " + err); } transaction.mail_from = from; } // Make sure to is an array if (!(Array.isArray(to))) { // turn into an array to = [ to ]; } if (to.length === 0) { return next(DENY, "No recipients for email"); } // Set RCPT TO's, and parse each if it's not an Address object. for (var i=0,l=to.length; i < l; i++) { if (!(to[i] instanceof Address)) { try { to[i] = new Address(to[i]); } catch (err) { return next(DENY, "Malformed to address (" + to[i] + "): " + err); } } } transaction.rcpt_to = to; // Set data_lines to lines in contents var match; var re = /^([^\n]*\n?)/; while (match = re.exec(contents)) { var line = match[1]; line = line.replace(/\n?$/, '\r\n'); // make sure it ends in \r\n transaction.add_data(line); contents = contents.substr(match[1].length); if (contents.length === 0) { break; } } transaction.message_stream.add_line_end(); this.send_trans_email(transaction, next); } exports.send_trans_email = function (transaction, next) { var self = this; // add in potentially missing headers if (!transaction.header.get_all('Message-Id').length) { this.loginfo("Adding missing Message-Id header"); transaction.add_header('Message-Id', '<' + transaction.uuid + '@' + config.get('me') + '>'); } if (!transaction.header.get_all('Date').length) { this.loginfo("Adding missing Date header"); transaction.add_header('Date', date_to_str(new Date())); } transaction.add_leading_header('Received', 'via haraka outbound.js at ' + date_to_str(new Date())); // First get each domain var recips = {}; var num_domains = 0; transaction.rcpt_to.forEach(function (item) { var domain = item.host; if (!recips[domain]) { recips[domain] = []; num_domains++; } recips[domain].push(item); }); var hmails = []; var ok_paths = []; async.forEachSeries(Object.keys(recips), function (domain, cb) { var todo = new TODOItem(domain, recips[domain], transaction); self.process_domain(ok_paths, todo, hmails, cb); }, function (err) { if (err) { for (var i=0,l=ok_paths.length; i<l; i++) { fs.unlink(ok_paths[i], function () {}); } if (next) next(DENY, err); return; } for (var i = 0; i < hmails.length; i++) { var hmail = hmails[i]; // Ugh should find out why I setTimeout here... Can't recall setTimeout(function (h) { return function () { delivery_queue.push(h) } }(hmail), 0); } if (next) next(OK, "Mail Queued"); }) } exports.process_domain = function (ok_paths, todo, hmails, cb) { var plugin = this; this.loginfo("Processing domain: " + todo.domain); var fname = _fname(); var tmp_path = path.join(queue_dir, '.' + fname); var ws = new FsyncWriteStream(tmp_path, { flags: WRITE_EXCL }); // var ws = fs.createWriteStream(tmp_path, { flags: WRITE_EXCL }); ws.on('close', function () { var dest_path = path.join(queue_dir, fname); fs.rename(tmp_path, dest_path, function (err) { if (err) { plugin.logerror("Unable to rename tmp file!: " + err); fs.unlink(tmp_path, function () {}); cb("Queue error"); } else { hmails.push(new HMailItem (fname, dest_path, todo.notes)); ok_paths.push(dest_path); cb(); } }); }); ws.on('error', function (err) { plugin.logerror("Unable to write queue file (" + fname + "): " + err); ws.destroy(); fs.unlink(tmp_path, function () {}); cb("Queueing failed"); }); plugin.build_todo(todo, ws); todo.message_stream.pipe(ws, { line_endings: '\r\n', dot_stuffing: true, ending_dot: false }); } exports.build_todo = function (todo, ws) { // Replacer function to exclude items from the queue file header function exclude_from_json(key, value) { switch (key) { case 'message_stream': return undefined; default: return value; } } var todo_str = new Buffer(JSON.stringify(todo, exclude_from_json), 'binary'); // since JS has no pack() we have to manually write the bytes of a long var todo_length = new Buffer(4); var todo_l = todo_str.length; todo_length[3] = todo_str.length & 0xff; todo_length[2] = (todo_str.length >> 8) & 0xff; todo_length[1] = (todo_str.length >> 16) & 0xff; todo_length[0] = (todo_str.length >> 24) & 0xff; var buf = Buffer.concat([todo_length, todo_str], todo_str.length + 4); ws.write(buf); } exports.split_to_new_recipients = function (hmail, recipients, response, cb) { var plugin = this; var fname = _fname(); var tmp_path = path.join(queue_dir, '.' + fname); var ws = new FsyncWriteStream(tmp_path, { flags: WRITE_EXCL }); // var ws = fs.createWriteStream(tmp_path, { flags: WRITE_EXCL }); var err_handler = function (err, location) { plugin.logerror("Error while splitting to new recipients (" + location + "): " + err); hmail.bounce("Error splitting to new recipients"); } ws.on('error', function (err) { err_handler(err, "tmp file writer") }); var writing = false; var write_more = function () { if (writing) return; writing = true; var rs = hmail.data_stream(); rs.pipe(ws, {end: false}); rs.on('error', function (err) { err_handler(err, "hmail.data_stream reader"); }) rs.on('end', function () { ws.on('close', function () { var dest_path = path.join(queue_dir, fname); fs.rename(tmp_path, dest_path, function (err) { if (err) { err_handler(err, "tmp file rename"); } else { var split_mail = new HMailItem (fname, dest_path); split_mail.once('ready', function () { cb(split_mail); }); } }); }); ws.destroySoon(); return; }); } ws.on('error', function (err) { plugin.logerror("Unable to write queue file (" + fname + "): " + err); ws.destroy(); hmail.bounce("Error re-queueing some recipients"); }); ws.on('drain', write_more); hmail.todo.rcpt_to = recipients; plugin.build_todo(hmail.todo, ws, write_more); } // TODOItem - queue file header data function TODOItem (domain, recipients, transaction) { this.domain = domain; this.rcpt_to = recipients; this.mail_from = transaction.mail_from; this.message_stream = transaction.message_stream; this.notes = transaction.notes; this.uuid = transaction.uuid; return this; } ///////////////////////////////////////////////////////////////////////////// // HMailItem - encapsulates an individual outbound mail item function HMailItem (filename, path, notes) { events.EventEmitter.call(this); var matches = filename.match(fn_re); if (!matches) { throw new Error("Bad filename: " + filename); } this.path = path; this.filename = filename; this.next_process = matches[1]; this.num_failures = matches[2]; this.notes = notes || {}; this.refcount = 1; this.next_cb = null; this.size_file(); } util.inherits(HMailItem, events.EventEmitter); exports.HMailItem = HMailItem; // populate log functions - so we can use hooks for (var key in logger) { if (key.match(/^log\w/)) { exports[key] = (function (key) { return function () { var args = ["[outbound] "]; for (var i=0, l=arguments.length; i<l; i++) { args.push(arguments[i]); } logger[key].apply(logger, args); } })(key); HMailItem.prototype[key] = (function (key) { return function () { var args = [ this ]; for (var i=0, l=arguments.length; i<l; i++) { args.push(arguments[i]); } logger[key].apply(logger, args); } })(key); } } HMailItem.prototype.data_stream = function () { return fs.createReadStream(this.path, {start: this.data_start, end: this.file_size}); } HMailItem.prototype.size_file = function () { var self = this; fs.stat(self.path, function (err, stats) { if (err) { // we are fucked... guess I need somewhere for this to go logger.logerror("Error obtaining file size: " + err); } else { self.file_size = stats.size; self.read_todo(); } }); } HMailItem.prototype.read_todo = function () { var self = this; var tl_reader = fs.createReadStream(self.path, {start: 0, end: 3}); tl_reader.on('data', function (buf) { // I'm making the assumption here we won't ever read less than 4 bytes // as no filesystem on the planet should be that dumb... tl_reader.destroy(); var todo_len = (buf[0] << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3]; var td_reader = fs.createReadStream(self.path, {encoding: 'utf8', start: 4, end: todo_len + 3}); self.data_start = todo_len + 4; var todo = ''; td_reader.on('data', function (str) { todo += str; if (todo.length === todo_len) { // we read everything todo = JSON.parse(todo); self.todo = todo; self.emit('ready'); } }); td_reader.on('error', function (err) { logger.logerror("Error reading todo: " + err); }) td_reader.on('end', function () { if (todo.length === todo_len) { logger.logerror("Didn't find enough data in todo!"); } }) }); } HMailItem.prototype.send = function () { if (config.get('outbound.disabled')) { // try again in 1 second if delivery is disabled this.logdebug("delivery disabled temporarily. Retrying in 1s."); var hmail = this; setTimeout(function () {hmail.send()}, 1000); return; } if (!this.todo) { var self = this; this.once('ready', function () { self._send() }); } else { this._send(); } } HMailItem.prototype._send = function () { plugins.run_hooks('send_email', this); } HMailItem.prototype.send_email_respond = function (retval, delaySeconds) { if (retval === constants.delay) { // Try again in 'delay' seconds. this.logdebug("Delivery of this email delayed for " + delaySeconds + " seconds"); var hmail = this; hmail.next_cb(); setTimeout(function () { delivery_queue.push(hmail) }, delaySeconds*1000); } else { this.logdebug("Sending mail: " + this.filename); this.get_mx(); } } HMailItem.prototype.get_mx = function () { var domain = this.todo.domain; plugins.run_hooks('get_mx', this, domain); } HMailItem.prototype.get_mx_respond = function (retval, mx) { switch(retval) { case constants.ok: var mx_list; if (Array.isArray(mx)) { mx_list = mx; } else if (typeof mx === "object") { mx_list = [mx]; } else { // assume string var matches = /^(.*?)(:(\d+))?$/.exec(mx); if (!matches) { throw("get_mx returned something that doesn't match hostname or hostname:port"); } mx_list = [{priority: 0, exchange: matches[1], port: matches[3]}]; } this.logdebug("Got an MX from Plugin: " + this.todo.domain + " => 0 " + mx); return this.found_mx(null, mx_list); case constants.deny: this.logwarn("get_mx plugin returned DENY: " + mx); return this.bounce("No MX for " + this.domain); case constants.denysoft: this.logwarn("get_mx plugin returned DENYSOFT: " + mx); return this.temp_fail("Temporary MX lookup error for " + this.domain); } var hmail = this; // if none of the above return codes, drop through to this... exports.lookup_mx(this.todo.domain, function (err, mxs) { hmail.found_mx(err, mxs); }); } exports.lookup_mx = function lookup_mx (domain, cb) { var mxs = []; // Possible DNS errors // NODATA // FORMERR // BADRESP // NOTFOUND // BADNAME // TIMEOUT // CONNREFUSED // NOMEM // DESTRUCTION // NOTIMP // EREFUSED // SERVFAIL // default wrap_mx just returns our object with "priority" and "exchange" keys var wrap_mx = function (a) { return a }; var process_dns = function (err, addresses) { if (err) { if (err.code === 'ENODATA') { // Most likely this is a hostname with no MX record // Drop through and we'll get the A record instead. return 0; } cb(err); } else if (addresses && addresses.length) { for (var i=0,l=addresses.length; i < l; i++) { var mx = wrap_mx(addresses[i]); // hmail.logdebug("Got an MX from DNS: " + hmail.todo.domain + " => " + mx.priority + " " + mx.exchange); mxs.push(mx); } cb(null, mxs); } else { // return zero if we need to keep trying next option return 0; } return 1; }; dns.resolveMx(domain, function(err, addresses) { if (process_dns(err, addresses)) { return; } // if MX lookup failed, we lookup an A record. To do that we change // wrap_mx() to return same thing as resolveMx() does. wrap_mx = function (a) { return {priority:0,exchange:a} }; dns.resolve(domain, function(err, addresses) { if (process_dns(err, addresses)) { return; } var err = new Error("Found nowhere to deliver to"); err.code = 'NOMX'; cb(err); }); }); } HMailItem.prototype.found_mx = function (err, mxs) { if (err) { this.logerror("MX Lookup for " + this.todo.domain + " failed: " + err); if (err.code === dns.NXDOMAIN || err.code === 'ENOTFOUND') { this.bounce("No Such Domain: " + this.todo.domain); } else if (err.code === 'NOMX') { this.bounce("Nowhere to deliver mail to for domain: " + this.todo.domain); } else { // every other error is transient this.temp_fail("DNS lookup failure: " + err); } } else { // got MXs var mxlist = sort_mx(mxs); this.mxlist = mxlist; this.try_deliver(); } } // MXs must be sorted by priority order, but matched priorities must be // randomly shuffled in that list, so this is a bit complex. function sort_mx (mx_list) { var sorted = mx_list.sort(function (a,b) { return a.priority - b.priority; }); // This isn't a very good shuffle but it'll do for now. for (var i=0,l=sorted.length-1; i<l; i++) { if (sorted[i].priority === sorted[i+1].priority) { if (Math.round(Math.random())) { // 0 or 1 var j = sorted[i]; sorted[i] = sorted[i+1]; sorted[i+1] = j; } } } return sorted; } HMailItem.prototype.try_deliver = function () { var self = this; // check if there are any MXs left if (this.mxlist.length === 0) { return this.temp_fail("Tried all MXs"); } var mx = this.mxlist.shift(); var host = mx.exchange; // IP or IP:port if (net.isIP(host)) { self.hostlist = [ host ]; return self.try_deliver_host(mx); } this.loginfo("Looking up A records for: " + host); // now we have a host, we have to lookup the addresses for that host // and try each one in order they appear dns.resolve(host, function (err, addresses) { if (err) { self.logerror("DNS lookup of " + host + " failed: " + err); return self.try_deliver(); // try next MX } if (addresses.length === 0) { // NODATA or empty host list self.logerror("DNS lookup of " + host + " resulted in no data"); return self.try_deliver(); // try next MX } self.hostlist = addresses; self.try_deliver_host(mx); }); } var smtp_regexp = /^([0-9]{3})([ -])(.*)/; HMailItem.prototype.try_deliver_host = function (mx) { if (this.hostlist.length === 0) { return this.try_deliver(); // try next MX } var host = this.hostlist.shift(); var port = mx.port || 25; var socket = sock.connect({port: port, host: host, localAddress: mx.bind}); var self = this; var processing_mail = true; this.loginfo("Attempting to deliver to: " + host + ":" + port + " (" + delivery_queue.length() + ")"); socket.on('error', function (err) { self.logerror("Ongoing connection failed: " + err); processing_mail = false; // try the next MX self.try_deliver_host(mx); }); socket.on('close', function () { if (processing_mail) { return self.try_deliver_host(mx); } }); socket.setTimeout(300 * 1000); // TODO: make this configurable var command = 'connect'; var response = []; var recipients = this.todo.rcpt_to.map(function (a) { return new Address (a.original) }); var mail_from = new Address (this.todo.mail_from.original); var data_marker = 0; var last_recip = null; var ok_recips = 0; var fail_recips = []; var bounce_recips = []; var smtp_properties = { "tls": false, "max_size": 0, "eightbitmime": false, "enh_status_codes": false, }; socket.send_command = function (cmd, data) { if (!this.writable) { self.logerror("Socket writability went away"); return self.try_deliver_host(mx); } var line = cmd + (data ? (' ' + data) : ''); if (cmd === 'dot') { line = '.'; } self.logprotocol("C: " + line); this.write(line + "\r\n"); command = cmd.toLowerCase(); response = []; }; socket.process_ehlo_data = function () { for (var i=0,l=response.length; i < l; i++) { var r = response[i]; if (r.toUpperCase() === '8BITMIME') { smtp_properties.eightbitmime = true; } else if (r.toUpperCase() === 'STARTTLS') { smtp_properties.tls = true; } else if (r.toUpperCase() === 'ENHANCEDSTATUSCODES') { smtp_properties.enh_status_codes = true; } else { var matches; matches = r.match(/^SIZE\s+(\d+)$/); if (matches) { smtp_properties.max_size = matches[1]; } } } if (smtp_properties.tls && config.get('outbound.enable_tls')) { this.on('secure', function () { socket.send_command('EHLO', config.get('me')); }); this.send_command('STARTTLS'); } else { this.send_command('MAIL', 'FROM:' + mail_from); } } socket.on('timeout', function () { self.logerror("Outbound connection timed out"); processing_mail = false; socket.end(); self.try_deliver_host(mx); }); socket.on('connect', function () { }); socket.on('line', function (line) { var matches; self.logprotocol("S: " + line); if (matches = smtp_regexp.exec(line)) { var code = matches[1], cont = matches[2], rest = matches[3]; response.push(rest); if (cont === ' ') { if (code.match(/^4/)) { if (/^rcpt/.test(command)) { // this recipient was rejected fail_recips.push(last_recip); } else { var reason = response.join(' '); socket.send_command('QUIT'); processing_mail = false; return self.temp_fail("Upstream error: " + code + " " + reason); } } else if (code.match(/^5/)) { if (/^rcpt/.test(command)) { bounce_recips.push(last_recip); } else { var reason = response.join(' '); socket.send_command('QUIT'); processing_mail = false; return self.bounce(reason); } } switch (command) { case 'connect': socket.send_command('EHLO', config.get('me')); break; case 'ehlo': socket.process_ehlo_data(); break; case 'starttls': var key = config.get('tls_key.pem', 'data').join("\n"); var cert = config.get('tls_cert.pem', 'data').join("\n"); var tls_options = { key: key, cert: cert }; smtp_properties = {}; socket.upgrade(tls_options); break; case 'helo': socket.send_command('MAIL', 'FROM:' + mail_from); break; case 'mail': last_recip = recipients.shift(); socket.send_command('RCPT', 'TO:' + last_recip.format()); break; case 'rcpt': if (last_recip && code.match(/^250/)) ok_recips++; if (!recipients.length) { if (fail_recips.length) { self.refcount++; exports.split_to_new_recipients(self, fail_recips, "Some recipients temporarily failed", function (hmail) { self.discard(); hmail.temp_fail("Some recipients temp failed: " + fail_recips.join(', ')); }); } if (bounce_recips.length) { self.refcount++; exports.split_to_new_recipients(self, bounce_recips, "Some recipients rejected", function (hmail) { self.discard(); hmail.bounce("Some recipients failed: " + bounce_recips.join(', ')); }); } if (ok_recips) { socket.send_command('DATA'); } else { processing_mail = false; socket.send_command('QUIT'); self.discard(); } } else { last_recip = recipients.shift(); socket.send_command('RCPT', 'TO:' + last_recip.format()); } break; case 'data': var data_stream = self.data_stream(); data_stream.on('data', function (data) { self.logdata("C: " + data); }); data_stream.on('error', function (err) { self.logerror("Reading from the data stream failed: " + err); }); data_stream.on('end', function () { socket.send_command('dot'); }); data_stream.pipe(socket, {end: false}); break; case 'dot': processing_mail = false; var reason = response.join(' '); socket.send_command('QUIT'); self.delivered(reason); break; case 'quit': socket.end(); break; default: // should never get here - means we did something // wrong. throw new Error("Unknown command: " + command); } } } else { // Unrecognised response. self.logerror("Unrecognised response from upstream server: " + line); processing_mail = false; socket.end(); return self.bounce("Unrecognised response from upstream server: " + line); } }); } function populate_bounce_message (from, to, reason, hmail, cb) { var values = { date: new Date().toString(), me: config.get('me'), from: from, to: to, reason: reason, pid: process.pid, msgid: '<' + utils.uuid() + '@' + config.get('me') + '>', }; var bounce_msg_ = config.get('outbound.bounce_message', 'data'); var bounce_msg = bounce_msg_.map(function (item) { return item.replace(/\{(\w+)\}/g, function (i, word) { return values[word] || '?' }) + '\n'; }); var data_stream = hmail.data_stream(); data_stream.on('data', function (data) { bounce_msg.push(data.toString()); }); data_stream.on('end', function () { cb(null, bounce_msg); }); data_stream.on('error', function (err) { cb(err); }) } HMailItem.prototype.bounce = function (err) { this.loginfo("bouncing mail: " + err); if (!this.todo) { // haven't finished reading the todo, delay here... var self = this; self.once('ready', function () { self._bounce(err) }); return; } this._bounce(err); } HMailItem.prototype._bounce = function (err) { this.bounce_error = err; plugins.run_hooks("bounce", this, err); } HMailItem.prototype.bounce_respond = function (retval, msg) { if (retval != constants.cont) { this.loginfo("plugin responded with: " + retval + ". Not sending bounce."); if (retval === constants.stop) { this.discard(); } return this.next_cb(); } var self = this; var err = this.bounce_error; if (!this.todo.mail_from.user) { // double bounce - mail was already a bounce return this.double_bounce("Mail was already a bounce"); } var from = new Address ('<>'); var recip = new Address (this.todo.mail_from.user, this.todo.mail_from.host); populate_bounce_message(from, recip, err, this, function (err, data_lines) { if (err) { return self.double_bounce("Error populating bounce message: " + err); } exports.send_email(from, recip, data_lines.join(''), function (code, msg) { self.discard(); if (code === DENY) { // failed to even queue the mail return self.double_bounce("Unable to queue the bounce message. Not sending bounce!"); } }); }); } HMailItem.prototype.double_bounce = function (err) { this.logerror("Double bounce: " + err); fs.unlink(this.path, function () {}); this.next_cb(); // TODO: fill this in... ? // One strategy is perhaps log to an mbox file. What do other servers do? // Another strategy might be delivery "plugins" to cope with this. } HMailItem.prototype.delivered = function (response) { this.lognotice("delivered file=" + this.filename + ' response="' + response + '"'); plugins.run_hooks("delivered", this, response); } HMailItem.prototype.discard = function () { this.refcount--; if (this.refcount === 0) { // Remove the file. fs.unlink(this.path, function () {}); this.next_cb(); } } HMailItem.prototype.temp_fail = function (err) { this.num_failures++; // Test for max failures which is configurable. if (this.num_failures >= (config.get('outbound.maxTempFailures') || 13)) { return this.bounce("Too many failures (" + err + ")"); } // basic strategy is we exponentially grow the delay to the power // two each time, starting at 2 ** 6 seconds // Note: More advanced options should be explored in the future as the // last delay is 2**17 secs (1.5 days), which is a bit long... Exim has a max delay of // 6 hours (configurable) and the expire time is also configurable... But // this is good enough for now. var delay = (Math.pow(2, (this.num_failures + 5)) * 1000); var until = new Date().getTime() + delay; this.loginfo("Temp failing " + this.filename + " for " + (delay/1000) + " seconds: " + err); var new_filename = this.filename.replace(/^(\d+)_(\d+)_/, until + '_' + this.num_failures + '_'); var hmail = this; fs.rename(this.path, path.join(queue_dir, new_filename), function (err) { if (err) { return hmail.bounce("Error re-queueing email: " + err); } hmail.path = path.join(queue_dir, new_filename); hmail.filename = new_filename; setTimeout(function () {delivery_queue.push(hmail)}, delay); }); } // The following handler has an impact on outgoing mail. It does remove the queue file. HMailItem.prototype.delivered_respond = function (retval, msg) { if (retval != constants.cont && retval != constants.ok) { this.logwarn("delivered plugin responded with: " + retval + " msg=" + msg + "."); } this.discard(); };
/** * DevExtreme (viz/tree_map/colorizing.range.js) * Version: 16.2.5 * Build date: Mon Feb 27 2017 * * Copyright (c) 2012 - 2017 Developer Express Inc. ALL RIGHTS RESERVED * EULA: https://www.devexpress.com/Support/EULAs/DevExtreme.xml */ "use strict"; var _createColorCodeGetter = require("./colorizing").createColorCodeGetter; function getPaletteIndex(value, items) { var middle, start = 0, end = items.length - 1, index = -1; if (items[start] <= value && value <= items[end]) { if (value === items[end]) { index = end - 1 } else { while (end - start > 1) { middle = start + end >> 1; if (value < items[middle]) { end = middle } else { start = middle } } index = start } } return index } function rangeColorizer(options, themeManager) { var range = options.range || [], palette = themeManager.createDiscretePalette(options.palette, range.length - 1), getValue = _createColorCodeGetter(options); return function(node) { return palette.getColor(getPaletteIndex(getValue(node), range)) } } require("./colorizing").addColorizer("range", rangeColorizer); module.exports = rangeColorizer;
'use strict'; //region Imports import Argument from './system/argument-check.js'; import CollectionBase from './common/collection-base.js'; import ModelType from './common/model-type.js'; import ModelError from './common/model-error.js'; //endregion //region Private variables const _itemType = new WeakMap(); const _parent = new WeakMap(); const _eventHandlers = new WeakMap(); const _items = new WeakMap(); //endregion //region Helper methods //region Initialization function initialize( name, itemType, parent, eventHandlers ) { // Verify the model type of the parent model. parent = Argument.inConstructor( name ) .check( parent ).for( 'parent' ).asModelType( [ ModelType.ReadOnlyRootObject, ModelType.ReadOnlyChildObject, ModelType.CommandObject ] ); // Resolve tree reference. if (typeof itemType === 'string') { if (itemType === parent.$modelName) itemType = parent.constructor; else throw new ModelError( 'invalidTree', itemType, parent.$modelName ); } // Set up event handlers. if (eventHandlers) eventHandlers.setup( this ); // Initialize instance state. _itemType.set( this, itemType ); _parent.set( this, parent ); _eventHandlers.set( this, eventHandlers ); _items.set( this, [] ); // Immutable definition object. Object.freeze( this ); } //endregion //endregion /** * Represents the definition of a read-only child collection. * * _The name of the model type available as: * __&lt;instance&gt;.constructor.modelType__, returns 'ReadOnlyChildCollection'._ * * @name ReadOnlyChildCollection * @extends CollectionBase */ class ReadOnlyChildCollection extends CollectionBase { //region Constructor /** * Creates a new read-only child collection instance. * * Valid parent model types are: * * * ReadOnlyRootObject * * ReadOnlyChildObject * * CommandObject * * @param {object} parent - The parent business object. * @param {bo.common.EventHandlerList} [eventHandlers] - The event handlers of the instance. * * @throws {@link bo.system.ArgumentError Argument error}: * The parent object must be an ReadOnlyRootObject, ReadOnlyChildObject * or CommandObject instance. */ constructor( name, itemType, parent, eventHandlers ) { super(); /** * The name of the model. * * @member {string} ReadOnlyChildCollection#$modelName * @readonly */ this.$modelName = name; // Initialize the instance. initialize.call( this, name, itemType, parent, eventHandlers ); } //endregion //region Properties /** * The count of the child objects in the collection. * * @member {number} ReadOnlyChildCollection#count * @readonly */ get count() { const items = _items.get( this ); return items.length; } /** * The name of the model type. * * @member {string} ReadOnlyChildCollection.modelType * @readonly */ static get modelType() { return ModelType.ReadOnlyChildCollection; } //endregion //region Actions /** * Initializes the items in the collection with data retrieved from the repository. * * _This method is called by the parent object._ * * @function ReadOnlyChildCollection#fetch * @protected * @param {Array.<object>} [data] - The data to load into the business object collection. * @returns {Promise.<ReadOnlyChildCollection>} Returns a promise to retrieved read-only child collection. */ fetch( data ) { const self = this; return data instanceof Array && data.length ? Promise.all( data.map( dto => { let itemType = _itemType.get( self ); const parent = _parent.get( self ); const eventHandlers = _eventHandlers.get( self ); return itemType.load( parent, dto, eventHandlers ); } ) ) .then( list => { // Add loaded items to the collection. const items = _items.get( self ); list.forEach( item => { items.push( item ); } ); _items.set( self, items ); // Nothing to return. return null; } ) : Promise.resolve( null ); } /** * Indicates whether all items of the business collection are valid. * * _This method is called by the parent object._ * * @function ReadOnlyChildCollection#isValid * @protected * @returns {boolean} */ isValid() { return this.every( item => { return item.isValid(); } ) } /** * Executes validation on all items of the collection. * * _This method is called by the parent object._ * * @function ReadOnlyChildCollection#checkRules * @protected */ checkRules() { this.forEach( item => { item.checkRules(); } ); } /** * Gets the broken rules of all items of the collection. * * _This method is called by the parent object._ * * @function ReadOnlyChildCollection#getBrokenRules * @protected * @param {string} [namespace] - The namespace of the message keys when messages are localizable. * @returns {Array.<bo.rules.BrokenRulesOutput>} The broken rules of the collection. */ getBrokenRules( namespace ) { const bro = []; this.forEach( ( item, index ) => { const childBrokenRules = item.getBrokenRules( namespace ); if (childBrokenRules) { childBrokenRules.$index = index; bro.push( childBrokenRules ); } } ); return bro.length ? bro : null; } //endregion //region Public array methods /** * Gets a collection item at a specific position. * * @function ReadOnlyChildCollection#at * @param {number} index - The index of the required item in the collection. * @returns {ReadOnlyChildObject} The required collection item. */ at( index ) { const items = _items.get( this ); return items[ index ]; } /** * Executes a provided function once per collection item. * * @function ReadOnlyChildCollection#forEach * @param {external.cbCollectionItem} callback - Function that produces an item of the new collection. */ forEach( callback ) { const items = _items.get( this ); items.forEach( callback ); } /** * Tests whether all items in the collection pass the test implemented by the provided function. * * @function ReadOnlyChildCollection#every * @param {external.cbCollectionItem} callback - Function to test for each collection item. * @returns {boolean} True when callback returns truthy value for each item, otherwise false. */ every( callback ) { const items = _items.get( this ); return items.every( callback ); } /** * Tests whether some item in the collection pass the test implemented by the provided function. * * @function ReadOnlyChildCollection#some * @param {external.cbCollectionItem} callback - Function to test for each collection item. * @returns {boolean} True when callback returns truthy value for some item, otherwise false. */ some( callback ) { const items = _items.get( this ); return items.some( callback ); } /** * Creates a new array with all collection items that pass the test * implemented by the provided function. * * @function ReadOnlyChildCollection#filter * @param {external.cbCollectionItem} callback - Function to test for each collection item. * @returns {Array.<ReadOnlyChildObject>} The new array of collection items. */ filter( callback ) { const items = _items.get( this ); return items.filter( callback ); } /** * Creates a new array with the results of calling a provided function * on every item in this collection. * * @function ReadOnlyChildCollection#map * @param {external.cbCollectionItem} callback - Function to test for each collection item. * @returns {Array.<*>} The new array of callback results. */ map( callback ) { const items = _items.get( this ); return items.map( callback ); } /** * Sorts the items of the collection in place and returns the collection. * * @function ReadOnlyChildCollection#sort * @param {external.cbCompare} [fnCompare] - Function that defines the sort order. * If omitted, the collection is sorted according to each character's Unicode * code point value, according to the string conversion of each item. * @returns {ReadOnlyChildCollection} The sorted collection. */ sort( fnCompare ) { const items = _items.get( this ); const sorted = items.sort( fnCompare ); _items.set( this, sorted ); return sorted; } //endregion } /** * Factory class to create definitions of read-only child collections. * * @name bo.ReadOnlyChildCollection */ class ReadOnlyChildCollectionFactory { //region Constructor /** * Creates a definition for a read-only child collection. * * Valid collection item types are: * * * ReadOnlyChildObject * * @param {string} name - The name of the collection. * @param {ReadOnlyChildObject} itemType - The model type of the collection items. * @returns {ReadOnlyChildCollection} The constructor of a read-only child collection. * * @throws {@link bo.system.ArgumentError Argument error}: The collection name must be a non-empty string. * @throws {@link bo.common.ModelError Model error}: The item type must be an ReadOnlyChildObject. */ constructor( name, itemType ) { name = Argument.inConstructor( ModelType.ReadOnlyChildCollection ) .check( name ).forMandatory( 'name' ).asString(); // Verify the model type of the items - when not a tree model. if ( typeof itemType !== 'string' && itemType.modelType !== ModelType.ReadOnlyChildObject ) throw new ModelError( 'invalidItem', itemType.prototype.name, itemType.modelType, ModelType.ReadOnlyChildCollection, ModelType.ReadOnlyChildObject ); // Create model definition. const Model = ReadOnlyChildCollection.bind( undefined, name, itemType ); //region Factory methods /** * The name of the model type. * * @member {string} ReadOnlyChildCollection.modelType * @readonly */ Model.modelType = ModelType.ReadOnlyChildCollection; /** * Creates a new uninitialized read-only child collection instance. * <br/>_This method is called by the parent object._ * * @function ReadOnlyChildCollection.empty * @protected * @param {object} parent - The parent business object. * @param {bo.common.EventHandlerList} [eventHandlers] - The event handlers of the instance. * @returns {ReadOnlyChildCollection} Returns a new read-only child collection. */ Model.empty = function ( parent, eventHandlers ) { return new Model( parent, eventHandlers ); }; //endregion // Immutable definition class. Object.freeze( Model ); return Model; } //endregion } // Immutable factory class. Object.freeze( ReadOnlyChildCollectionFactory ); export default ReadOnlyChildCollectionFactory;
var mysql=require('mysql'); var conn=require('./util'); var reserror=require('./error'); var responseFormat=require('../responseFormat'); exports.getById=function (id,obj,next) { conn.query("SELECT * FROM rtext WHERE id=?",[id],function(err,rows){ if (err) throw err; var data=responseFormat.text(obj['ToUserName'],obj['FromUserName'],rows[0]['content']); next(data); }); // body... }; exports.wechatRtext=function(req,res){ if (typeof req.body.tmp!='undefined') { conn.query("SELECT * FROM rtext",function(err,rows){ if (err) throw err; if (rows.length!=0) { var temp=""; var gtemp=req.body.tmp.split(","); for (var i in rows) { for (var j in gtemp) { if (gtemp[j]==rows[i].id) { temp+=rows[i].content; break; }; }; }; res.send(responseFormat.text(req.body.xml.FromUserName,req.body.xml.ToUserName,temp)); }else{ reserror.response(req,res); } }); }else{ reserror.response(req,res); } return; }
app.controller( 'DeliveryReceiptModalController', [ '$uibModalInstance', 'transferItem', 'UserServices', function( $uibModalInstance, transferItem, UserServices ) { var $ctrl = this; $ctrl.params = { preparedBy: null, checkedBy: null, bearerName: null, bearerId: null, issuedBy: null, approvedBy: null }; $ctrl.findUser = UserServices.findUser; $ctrl.ok = function() { reportParams = { TRANSFER_ID: transferItem.id, PREPARED_BY: $ctrl.params.preparedBy ? $ctrl.params.preparedBy.full_name : null, PREPARED_BY_POSITION: $ctrl.params.preparedBy ? $ctrl.params.preparedBy.position : null, CHECKED_BY: $ctrl.params.checkedBy ? $ctrl.params.checkedBy.full_name : null, CHECKED_BY_POSITION: $ctrl.params.checkedBy ? $ctrl.params.checkedBy.position : null, BEARER: $ctrl.params.bearerName ? $ctrl.params.bearerName : null, BEARER_ID: $ctrl.params.bearerId ? $ctrl.params.bearerId : null, ISSUED_BY: $ctrl.params.issuedBy ? $ctrl.params.issuedBy.full_name : null, ISSUED_BY_POSITION: $ctrl.params.issuedBy ? $ctrl.params.issuedBy.position : null, APPROVED_BY: $ctrl.params.approvedBy ? $ctrl.params.approvedBy.full_name : null, APPROVED_BY_POSITION: $ctrl.params.approvedBy ? $ctrl.params.approvedBy.position : null }; $uibModalInstance.close( reportParams ); }; $ctrl.cancel = function() { $uibModalInstance.dismiss(); }; } ]); app.controller( 'TurnoverItemModalController', [ '$filter', '$uibModalInstance', 'session', 'appData', function( $filter, $uibModalInstance, session, appData ) { var $ctrl = this; $ctrl.input = { datepicker: { value: new Date(), format: 'yyyy-MM-dd', opened: false } }; $ctrl.data = { checkAllItems: true, items: [] }; $ctrl.showDatePicker = function() { $ctrl.input.datepicker.opened = true; }; $ctrl.changeDate = function() { var date = $ctrl.input.datepicker.value; appData.getTurnoverItems( session.data.currentStore.id, date ).then( function( response ) { for( var i = 0; i < response.items.length; i++ ) { response.items[i].selected = true; } $ctrl.data.items = response.items; }, function( reason ) { console.error( reason ); } ); }; $ctrl.toggleCheckboxes = function() { for( var i = 0; i < $ctrl.data.items.length; i++ ) { $ctrl.data.items[i].selected = $ctrl.data.checkAllItems && !$ctrl.data.items[i].turnover_id; } } $ctrl.submit = function() { var selected = []; for( var i = 0; i < $ctrl.data.items.length; i++ ) { if( $ctrl.data.items[i].selected && !$ctrl.data.items[i].turnover_id ) { selected.push( $ctrl.data.items[i] ); } } $uibModalInstance.close( selected ); }; $ctrl.close = function() { $uibModalInstance.dismiss(); }; // Initialize controller $ctrl.changeDate(); } ]); app.controller( 'SalesDepositItemModalController', [ '$filter', '$uibModalInstance', 'session', 'appData', 'businessDate', 'currentShiftId', function( $filter, $uibModalInstance, session, appData, businessDate, currentShiftId ) { var $ctrl = this; $ctrl.data = { businessDate: businessDate, checkAllItems: true, items: [] }; $ctrl.getSalesCollectionItems = function() { appData.getShiftSalesItems( session.data.currentStore.id, businessDate, currentShiftId ).then( function( response ) { for( var i = 0; i < response.items.length; i++ ) { response.items[i].selected = true; } $ctrl.data.items = response.items; }, function( reason ) { console.error( reason ); } ); }; $ctrl.toggleCheckboxes = function() { for( var i = 0; i < $ctrl.data.items.length; i++ ) { $ctrl.data.items[i].selected = $ctrl.data.checkAllItems && !$ctrl.data.items[i].turnover_id; } } $ctrl.submit = function() { var selected = []; for( var i = 0; i < $ctrl.data.items.length; i++ ) { if( $ctrl.data.items[i].selected && !$ctrl.data.items[i].turnover_id ) { selected.push( $ctrl.data.items[i] ); } } $uibModalInstance.close( selected ); }; $ctrl.close = function() { $uibModalInstance.dismiss(); }; // Initialize controller $ctrl.getSalesCollectionItems(); } ]);
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M4 12c0-4.41 3.59-8 8-8s8 3.59 8 8-3.59 8-8 8-8-3.59-8-8m8-1H8v2h4v3l4-4-4-4v3z", opacity: ".3" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M4 12c0-4.41 3.59-8 8-8s8 3.59 8 8-3.59 8-8 8-8-3.59-8-8m-2 0c0 5.52 4.48 10 10 10s10-4.48 10-10S17.52 2 12 2 2 6.48 2 12zm10-1H8v2h4v3l4-4-4-4v3z" }, "1")], 'ArrowCircleRightTwoTone'); exports.default = _default;
define(function() { function PartsIndicator(src) { var parts = src.parts.map(function(part, index) { return "<span class='code-part-indicator'>" + (index + 1) + ": " + part.name + "</span>" }).join('') this.div = document.createElement('div') this.div.className = "code-parts-indicator" this.div.innerHTML = parts document.body.appendChild(this.div) } PartsIndicator.prototype.show = function() { this.div.style.display = "block" } PartsIndicator.prototype.hide = function() { this.div.style.display = "none" } return PartsIndicator })
/** * Plugin dependencies. * * @type {exports} */ var helpers = require('unibot-helpers'); var cheerio = require('cheerio'); /** * Lutakko plugin for UniBot. * * This plugin fetches event information from http://www.jelmu.net/ website. * * Also note that this plugin relies heavily to HTML structure of that site. So there will be times, when this plugin * doesn't work right. * * @todo Make item count configurable * @todo Make bot just to say one message (need more opinions of this) * * @param {Object} options Plugin options object, description below. * db: {mongoose} the mongodb connection * bot: {irc} the irc bot * web: {connect} a connect + connect-rest webserver * config: {object} UniBot configuration * * @return {Function} Init function to access shared resources */ module.exports = function init(options) { // Actual plugin implementation. return function plugin(channel) { // Regex rules for plugin return { '^!lutakko$': function lutakko(from, matches) { helpers.download('http://www.jelmu.net/', function success(data) { if (data == null) { channel.say(from, 'Did not get any data from URL http://www.jelmu.net/ - site maybe down?'); } else { var $ = cheerio.load(data); $("ul[role='upcoming-events'] li").each(function iterator(i, elem) { if (i < 3) { var event = $(this); var date = event.find('div.date span').text().trim(); var artists = []; event.find('a span').each(function iterator() { artists.push($(this).text().trim()); }); if (artists.length > 0) { channel.say(date + ' ' + artists.join(' ')); } else { channel.say(from, 'Did not find any "proper" artist data...'); } } }); } }); } }; }; };
var Node = require('../Node'); Node('Comprehension', function(keyType, keyName, valueType, valueName, expr, as, body) { // TODO dry with Each if (!valueType) { this.key = null; this.value = { type: keyType, name: keyName }; } else { this.key = { type: keyType, name: keyName }; this.value = { type: valueType, name: valueName }; } this.expr = expr; this.as = as; }, { visit: function(visitor, parentNode, depth, fromTop) { if (this.key) { this.key.type.visit(visitor, this, depth + 1, fromTop); this.key.name.visit(visitor, this, depth + 1, fromTop); } this.value.type.visit(visitor, this, depth + 1, fromTop); this.value.name.visit(visitor, this, depth + 1, fromTop); this.expr.visit(visitor, this, depth + 1, fromTop); this.as.visit(visitor, this, depth + 1, fromTop); } });
var express = require("express"); var path = require("path"); var favicon = require("serve-favicon"); var logger = require("morgan"); var cookieParser = require("cookie-parser"); var bodyParser = require("body-parser"); var routes = require("./controllers"); var app = express(); // view engine setup app.set("views", path.join(__dirname, "views")); app.set("view engine", "jade"); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, "public", "favicon.ico"))); app.use(logger("dev")); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(require("less-middleware")(path.join(__dirname, "public"))); app.use(express.static(path.join(__dirname, "public"))); app.use("/", routes); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error("Not Found"); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get("env") === "development") { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render("error", { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render("error", { message: err.message, error: {} }); }); module.exports = app;
/* eslint-disable no-console */ export function log(...args) { console.log(...args) } export function warn(...args) { console.warn(...args) } export function error(...args) { console.error(...args) }
/** * some utils function */ 'use strict'; let fs = require('fs'); let path = require('path'); let log = require('./log'); module.exports = { isExist(tplPath){ let p = path.normalize(tplPath); try { fs.accessSync(p, fs.R_OK & fs.W_OK, (err) => { if(err){ log.tips(); log.error(`Permission Denied to access ${p}`); } }); return true; } catch (e){ return false; } }, isLocalTemplate(tpl){ let isLocal = tpl.startsWith('.') || tpl.startsWith('/') || /^\w:/.test(tpl); if(isLocal){ return isLocal; } else { return this.isExist(path.normalize(path.join(process.cwd(), tpl))); } } };
var Promise = require("bluebird"); var settings = require("../settings"); var Posts = require("./posts").Posts; var postClient = new Posts(); var Ktype = require("./ktype").Ktype; var ktypeClient = new Ktype(); var Host = require("./host").Host; var hostClient = new Host(); var Accounts = require("./accounts-server").Accounts; var accountsClient = new Accounts(); var UserClient = require("./oauth-ropc/client").UserClient; var userClient = new UserClient(); var CollectionDb = require("../collection/collection"); var collectionDb = new CollectionDb(); var NodeHandle = require("./knode").NodeHandle; var nodeClient = new NodeHandle(); var Util = require("../utils/util").Util; var util = new Util(); // print utils var log = util.log; var logError = util.logError; var hasOwnProperty = Object.prototype.hasOwnProperty; // ------------------------------------------------ function KCMS(){ this.name = "KCMS" } exports.KCMS = KCMS; // ------------------------------------------------ /** * test if connected to the server * @return {json} return data about connect status */ KCMS.prototype.test = function(req, res, next) { log("test: API called.") if(!req.clientId) { var errStr = "test: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var userData = req.body; var message = ""; if(!userData) { res.send({error: true, message: "error connect to the server."}) } else { if(Object.prototype.hasOwnProperty.call(userData, "message")){ message = userData.message } res.send({status: 200, message: message}); } next(); } } // ------------------------------------------------ KCMS.prototype.createType = function(req, res, next) { log("createType: API called."); var errStr = ""; if(!req.clientId) { errStr = "createPost: user authorization error."; next(errStr); logError(errStr); res.sendUnauthenticated(); } else { var body = req.body; delete body.grant_type; ktypeClient.createType(body) .then(function(results) { log("createType: create type succeed."); res.send({status: 200, message: "create type succeed."}); next(); }) .catch(function(err) { errStr = "createType: create type error"; logError(errStr, err); res.send({error: true, message: err }); next(errStr); }) } } // ------------------------------------------------ KCMS.prototype.updateType = function(req, res, next) { log("updateType: API called."); var errStr = ""; if(!req.clientId) { errStr = "updateType: user authorization error."; next(errStr); logError(errStr); res.sendUnauthenticated(); } else { var body = req.body; delete body.grant_type; ktypeClient.updateType(body) .then(function(results) { log("updateType: update type succeed."); res.send({status: 200, message: "update type succeed."}); next(); }) .catch(function(err) { errStr = "updateType: update type error"; logError(errStr, err); res.send({error: true, message: err }); next(errStr); }) } } // ------------------------------------------------ KCMS.prototype.removeType = function(req, res, next) { log("removeType: API called."); var errStr = ""; if(!req.clientId) { errStr = "removeType: user authorization error."; next(errStr); logError(errStr); res.sendUnauthenticated(); } else { var body = req.body; delete body.grant_type; ktypeClient.removeType(body) .then(function(results) { log("removeType: remove type succeed."); res.send({status: 200, message: "remove type succeed."}); next(); }) .catch(function(err) { errStr = "removeType: remove type error"; logError(errStr, err); res.send({error: true, message: err }); next(errStr); }) } } // ------------------------------------------------ KCMS.prototype.createPost = function(req, res, next) { log("createPost: API called."); var errStr = ""; if(!req.clientId) { errStr = "createPost: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; postClient.createPost(body) .then(function(results) { log("createPost: create post succeed."); res.send({status: 200, message: "create post succeed."}); }) .catch(function(err) { logError("createPost: create post error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.updatePost = function(req, res, next) { log("updatePost: API called."); var errStr = ""; if(!req.clientId) { errStr = "updatePost: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; postClient.updatePost(body) .then(function(results) { log("updatePost: update post succeed."); res.send({status: 200, message: "update post succeed."}); }) .catch(function(err) { logError("updatePost: update post error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.removePost = function(req, res, next) { log("removePost: API called."); var errStr = ""; if(!req.clientId) { errStr = "removePost: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; postClient.createPost(body) .then(function(results) { log("removePost: remove post succeed."); res.send({status: 200, message: "remove post succeed."}); }) .catch(function(err) { logError("removePost: remove post error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.updateHost = function(req, res, next) { log("updateHost: API called."); var errStr = ""; if(!req.clientId) { errStr = "updateHost: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; hostClient.updateHost(body) .then(function(results) { log("updateHost: update host succeed."); res.send({status: 200, message: "update host succeed."}); }) .catch(function(err) { logError("updateHost: update host error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.removeHost = function(req, res, next) { log("removeHost: API called."); var errStr = ""; if(!req.clientId) { errStr = "removeHost: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; hostClient.removeHost(body) .then(function(results) { log("removeHost: remove host succeed."); res.send({status: 200, message: "remove host succeed."}); }) .catch(function(err) { logError("removeHost: remove host error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.createUser = function(req, res, next) { log("createUser: API called."); var errStr = ""; if(!req.clientId) { errStr = "createUser: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; accountsClient.createUser(body) .then(function(results) { log("createUser: create user succeed."); res.send({status: 200, message: "create user succeed."}); }) .catch(function(err) { logError("createUser: create user error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.resetPassword = function(req, res, next) { log("resetPassword: API called."); var errStr = ""; if(!req.clientId) { errStr = "resetPassword: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; accountsClient.resetPassword(body) .then(function(results) { log("resetPassword: reset password succeed."); res.send({status: 200, message: "reset password succeed."}); }) .catch(function(err) { logError("resetPassword: reset password error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.findUserByQuery = function(req, res, next) { log("findUserByQuery: API called."); var errStr = ""; if(!req.clientId) { errStr = "findUserByQuery: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; accountsClient.findUserByQuery(body) .then(function(results) { log("findUserByQuery: find user by query succeed."); res.send({status: 200, message: "find user by query succeed."}); }) .catch(function(err) { logError("findUserByQuery: find user by query error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.createClientByUser = function(req, res, next) { log("createClientByUser: API called."); var errStr = ""; if(!req.clientId) { errStr = "createClientByUser: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; userClient.createClientByUser(body) .then(function(results) { log("createClientByUser: create clientId and clientSecret succeed."); res.send({status: 200, message: "create clientId and clientSecret succeed."}); }) .catch(function(err) { logError("createClientByUser: create clientId and clientSecret error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.updateClientSecret = function(req, res, next) { log("updateClientSecret: API called."); var errStr = ""; if(!req.clientId) { errStr = "updateClientSecret: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; userClient.updateClientSecret(body) .then(function(results) { log("updateClientSecret: update clientSecret succeed."); res.send({status: 200, message: "update clientSecret succeed."}); }) .catch(function(err) { logError("updateClientSecret: update clientSecret error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.updateClientSecret = function(req, res, next) { log("updateClientSecret: API called."); var errStr = ""; if(!req.clientId) { errStr = "updateClientSecret: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; userClient.updateClientSecret(body) .then(function(results) { log("updateClientSecret: update clientSecret succeed."); res.send({status: 200, message: "update clientSecret succeed."}); }) .catch(function(err) { logError("updateClientSecret: update clientSecret error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.updateClientSecret = function(req, res, next) { log("updateClientSecret: API called."); var errStr = ""; if(!req.clientId) { errStr = "updateClientSecret: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; userClient.updateClientSecret(body) .then(function(results) { log("updateClientSecret: update clientSecret succeed."); res.send({status: 200, message: "update clientSecret succeed."}); }) .catch(function(err) { logError("updateClientSecret: update clientSecret error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.createCollection = function(req, res, next) { log("createCollection: API called."); var errStr = ""; if(!req.clientId) { errStr = "createCollection: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; collectionDb.createCollection(body) .then(function(results) { log("createCollection: create collection succeed."); res.send({status: 200, message: "create collection succeed."}); }) .catch(function(err) { logError("createCollection: create collection error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.dropCollection = function(req, res, next) { log("dropCollection: API called."); var errStr = ""; if(!req.clientId) { errStr = "dropCollection: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; collectionDb.dropCollection(body) .then(function(results) { log("dropCollection: drop collection succeed."); res.send({status: 200, message: "drop collection succeed."}); }) .catch(function(err) { logError("dropCollection: drop collection error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.renameCollection = function(req, res, next) { log("renameCollection: API called."); var errStr = ""; if(!req.clientId) { errStr = "renameCollection: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; collectionDb.renameCollection(body) .then(function(results) { log("renameCollection: rename collection succeed."); res.send({status: 200, message: "rename collection succeed."}); }) .catch(function(err) { logError("renameCollection: rename collection error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.insertOne = function(req, res, next) { log("insertOne: API called."); var errStr = ""; if(!req.clientId) { errStr = "insertOne: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; collectionDb.insertOne(body) .then(function(results) { log("insertOne: insert one doc succeed."); res.send({status: 200, message: "insert one doc succeed."}); }) .catch(function(err) { logError("insertOne: insert one doc error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.findAndModify = function(req, res, next) { log("findAndModify: API called."); var errStr = ""; if(!req.clientId) { errStr = "findAndModify: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; collectionDb.findAndModify(body) .then(function(results) { log("findAndModify: find one doc and modify it succeed."); res.send({status: 200, message: "find one doc and modify it succeed."}); }) .catch(function(err) { logError("findAndModify: find one doc and modify it error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.findAndRemove = function(req, res, next) { log("findAndRemove: API called."); var errStr = ""; if(!req.clientId) { errStr = "findAndRemove: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; collectionDb.findAndRemove(body) .then(function(results) { log("findAndRemove: find one doc and remove it succeed."); res.send({status: 200, message: "find one doc and remove it succeed."}); }) .catch(function(err) { logError("findAndRemove: find one doc and remove it error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.removeDocs = function(req, res, next) { log("removeDocs: API called."); var errStr = ""; if(!req.clientId) { errStr = "removeDocs: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; collectionDb.remove(body) .then(function(results) { log("removeDocs: remove docs succeed."); res.send({status: 200, message: "remove docs succeed."}); }) .catch(function(err) { logError("removeDocs: remove docs error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.queryDocs = function(req, res, next) { log("queryDocs: API called."); var errStr = ""; if(!req.clientId) { errStr = "queryDocs: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; collectionDb.find(body) .then(function(results) { log("queryDocs: query docs succeed."); res.send({status: 200, message: "query docs succeed."}); }) .catch(function(err) { logError("queryDocs: query docs error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.queryOneDoc = function(req, res, next) { log("queryOneDoc: API called."); var errStr = ""; if(!req.clientId) { errStr = "queryOneDoc: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; collectionDb.find(body) .then(function(results) { log("queryOneDoc: query one doc succeed."); res.send({status: 200, message: "query one doc succeed."}); }) .catch(function(err) { logError("queryOneDoc: query one doc error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.updateDocs = function(req, res, next) { log("updateDocs: API called."); var errStr = ""; if(!req.clientId) { errStr = "updateDocs: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; collectionDb.update(body) .then(function(results) { log("updateDocs: query docs succeed."); res.send({status: 200, message: "query docs succeed."}); }) .catch(function(err) { logError("updateDocs: query docs error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.createNode = function(req, res, next) { log("createNode: API called."); var errStr = ""; if(!req.clientId) { errStr = "createNode: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; nodeClient.createNode(body) .then(function(results) { log("createNode: create node succeed."); res.send({status: 200, message: "query docs succeed."}); }) .catch(function(err) { logError("createNode:create node error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.updateNodeByNodeId = function(req, res, next) { log("updateNodeByNodeId: API called."); var errStr = ""; if(!req.clientId) { errStr = "updateNodeByNodeId: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; nodeClient.updateNodeByNodeId(body) .then(function(results) { log("updateNodeByNodeId: update node by id succeed."); res.send({status: 200, message: "query docs succeed."}); }) .catch(function(err) { logError("updateNodeByNodeId:update node by id error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.updateNodeByName = function(req, res, next) { log("updateNodeByName: API called."); var errStr = ""; if(!req.clientId) { errStr = "updateNodeByName: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; nodeClient.updateNodeByName(body) .then(function(results) { log("updateNodeByName: update node by name succeed."); res.send({status: 200, message: "query docs succeed."}); }) .catch(function(err) { logError("updateNodeByName:update node by name error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.linkNode = function(req, res, next) { log("linkNode: API called."); var errStr = ""; if(!req.clientId) { errStr = "linkNode: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; nodeClient.linkNode(body) .then(function(results) { log("linkNode: link node handle succeed."); res.send({status: 200, message: "query docs succeed."}); }) .catch(function(err) { logError("linkNode:link node handle error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.unlinkNode = function(req, res, next) { log("unlinkNode: API called."); var errStr = ""; if(!req.clientId) { errStr = "unlinkNode: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; nodeClient.unlinkNode(body) .then(function(results) { log("unlinkNode: unlink node handle succeed."); res.send({status: 200, message: "query docs succeed."}); }) .catch(function(err) { logError("unlinkNode:unlink node handle error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.removeNode = function(req, res, next) { log("removeNode: API called."); var errStr = ""; if(!req.clientId) { errStr = "removeNode: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; nodeClient.removeNode(body) .then(function(results) { log("removeNode: remove node handle succeed."); res.send({status: 200, message: "query docs succeed."}); }) .catch(function(err) { logError("removeNode: remove node handle error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------ KCMS.prototype.copyNode = function(req, res, next) { log("copyNode: API called."); var errStr = ""; if(!req.clientId) { errStr = "copyNode: error authorization."; res.sendUnauthenticated(); next(errStr); } else { var body = req.body; delete body.grant_type; nodeClient.copyNode(body) .then(function(results) { log("copyNode: copy node handle succeed."); res.send({status: 200, message: "query docs succeed."}); }) .catch(function(err) { logError("copyNode: copy node handle error.", err); res.send({error: true, error: err}) }) next(); } } // ------------------------------------------------
import { Math as Math$1, Texture, UVMapping } from 'three/build/three.js'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } /** Describes a rectangular area witin the knapsack. Abstracts the basic math away from the {@link module:texture-manager/knapsack/node|`KnapsackNode`} module. @module texture-manager/knapsack/rectangle */ /** * @constructor * @param {integer} left - Left most pixel index of this rectangle (0 to `right` - 1 ) * @param {integer} top - Top most pixel index of this rectangle (0 to `bottom` - 1 ) * @param {integer} right - Right most pixel index of this rectangle * @param {integer} bottom - Bottom most pixel index of this rectangle */ var KnapsackRectangle = /*#__PURE__*/function () { function KnapsackRectangle(left, top, right, bottom) { _classCallCheck(this, KnapsackRectangle); this.left = Math.floor(typeof left === "number" && isFinite(left) ? left : 0); this.top = Math.floor(typeof top === "number" && isFinite(top) ? top : 0); this.right = Math.floor(typeof right === "number" && isFinite(right) ? right : 0); this.bottom = Math.floor(typeof bottom === "number" && isFinite(bottom) ? bottom : 0); } /** * The center X coordinate of this rectangle. * @type {integer} * @readonly */ _createClass(KnapsackRectangle, [{ key: "Xcentre", get: function get() { return Math.floor((this.right - this.left) / 2 + this.left) - 0.5; } /** * The center Y coordinate of this rectangle. * @type {integer} * @readonly */ }, { key: "Ycentre", get: function get() { return Math.floor((this.bottom - this.top) / 2 + this.top) - 0.5; } /** * The width of this rectangle in pixels. * @type {integer} * @readonly */ }, { key: "width", get: function get() { return this.right - this.left; } /** * The height of this rectangle in pixels. * @type {integer} * @readonly */ }, { key: "height", get: function get() { return this.bottom - this.top; } }]); return KnapsackRectangle; }(); /** * Do not use this directly, it is managed for you. * @constructor * @param {Knapsack} - The {@link module:texture-manager/knapsack|`Knapsack`} this node is to become a part of. */ var KnapsackNode = /*#__PURE__*/function () { function KnapsackNode(knapsack) { _classCallCheck(this, KnapsackNode); /** * Reference to the {@link module:texture-manager/knapsack|`Knapsack`} this node is a part of * @type {Knapsack} * @private * @readonly * @category provider */ this.knapsack = knapsack; /** * Optional reference to the "left" side {@link module:texture-manager/knapsack/node|`KnapsackNode`} branch of the tree of nodes. * @type {KnapsackNode} * @private * @readonly * @category provider */ this.leftChild = null; /** * Optional reference to the "right" side {@link module:texture-manager/knapsack/node|`KnapsackNode`} branch of the tree of nodes. * @type {KnapsackNode} * @private * @readonly * @category provider */ this.rightChild = null; /** * Describes the coordinates which are the boundaries of this node. * @type {KnapsackRectangle} * @private * @readonly * @category information */ this.rectangle = null; // Overwritten when children are created, but done as a default here to keep // the code cleaner. Instantiating this object is pretty cheap anyway. this.rectangle = new KnapsackRectangle(0, 0, knapsack.textureSize, knapsack.textureSize); /** * Internal unique ID for the image this node represents. * @type {string} * @private * @readonly * @category information */ this.imageID = null; this._texture = null; } /** * The HTML `<canvas>` element as supplied by the {@link module:texture-manager/knapsack|`Knapsack`} which this node is part of. * @type {external:canvas} * @readonly * @category provider */ _createClass(KnapsackNode, [{ key: "canvas", get: function get() { return this.knapsack.canvas; } /** * Convenience accessor for the {@link external:CanvasRenderingContext2D} which is associated with the {@link module:texture-manager/knapsack/node#canvas}. You can use this context to draw on the entire canvas, but you'll probably want to use {@link module:texture-manager/knapsack/node#clipContext|`clipContext()`} instead. * @type {external:CanvasRenderingContext2D} * @readonly * @category provider */ }, { key: "context", get: function get() { return this.knapsack.canvas.getContext("2d"); } /** * The width in pixels of this sprite's texture node. * @type {integer} * @readonly * @category information * @example * textureManager.allocateNode( 30, 10 ).then( function( node ) { * console.log( node.width ); // => 30 * }); */ }, { key: "width", get: function get() { return this.rectangle.width; } /** * The height in pixels of this sprite's texture node. * @type {integer} * @readonly * @category information * @example * textureManager.allocateNode( 30, 10 ).then( function( node ) { * console.log( node.height ); // => 10 * }); */ }, { key: "height", get: function get() { return this.rectangle.height; } /** * Lazily built {@link external:Texture|`THREE.Texture`}, with it's UV coordinates already set for you. You can pass this texture straight to your material, and the GPU memory it requires should be shared with all other texture nodes on the same texture. * @type {external:Texture} * @readonly * @category provider * @example * var material = new THREE.SpriteMaterial({ * map: node.texture, * transparent: true, * blending: THREE.AdditiveBlending * }); * var sprite = new THREE.Sprite( material ); * scene.add( sprite ); */ }, { key: "texture", get: function get() { if (!this._texture) { this._texture = this.knapsack.rootTexture.clone(); this._texture.uuid = this.knapsack.rootTexture.uuid; var uvs = this.uvCoordinates(); this.texture.offset.x = uvs[0]; this.texture.offset.y = uvs[1]; this.texture.repeat.x = uvs[2] - uvs[0]; this.texture.repeat.y = uvs[3] - uvs[1]; } return this._texture; } /** * Returns true if this node has any children, which means it's not available to be drawn in. Its children may be suitable for this though. * @returns {boolean} * @category information * @private */ }, { key: "hasChildren", value: function hasChildren() { return this.leftChild !== null || this.rightChild !== null; } /** * Returns true if this node is available to be used by a texture (i.e. it's not yet been claimed by {@link module:texture-manager/knapsack/node#claim|`claim()`}. * @returns {boolean} Indicates whether this node has been claimed or not. * @category information * @private */ }, { key: "isOccupied", value: function isOccupied() { return this.imageID !== null; } /** * The UV coordinates which describe where in the texture this node is located. This is probably not of any practical use to you as a user of this library; it is used internally to map the texture correctly to a sprite. * @returns {Array} Array with [ left, top, right, bottom ] coordinates. * @category information * @example * var uvs = node.uvCoordinates(); * var left = uvs[ 0 ]; * var top = uvs[ 1 ]; * var right = uvs[ 2 ]; * var bottom = uvs[ 3 ]; */ }, { key: "uvCoordinates", value: function uvCoordinates() { var size = this.knapsack.textureSize; return [this.rectangle.left / size, 1 - this.rectangle.bottom / size, this.rectangle.right / size, 1 - this.rectangle.top / size]; } /** * Release this node back to the {@link module:texture-manager/knapsack|`Knapsack`} where it is contained. This makes it available to be used by new sprites. Only nodes without children can be released, but a user of this library will only get these leaf nodes returned. Branch nodes are used internally only. * @category allocation * @example * node.release(); * // or, if you like typing: * textureManager.release( node ); */ }, { key: "release", value: function release() { if (this.hasChildren()) { throw new Error("Can not release tree node, still has children"); } if (this._texture !== null) { this._texture.dispose(); this._texture = null; } this.clear(); this.imageID = null; return; } /** * Clear the area of this node: it erases the context so that it is empty and transparent, and ready to be drawn to. * @category drawing * @example * // Erase the contents of the sprite * node.clear(); */ }, { key: "clear", value: function clear() { this.context.clearRect(this.rectangle.left, this.rectangle.top, this.width - 1, this.height - 1); } /** * Set the drawing context tailored towards the area of the sprite, clipping anything outside of it. When done drawing, use {@link module:texture-manager/knapsack/node#restoreContext|`restoreContext()`} to restore the original drawing context. * @returns {CanvasRenderingContext2D} Render context configured exclusively for the sprite we're working on. * @category drawing * @example * var context = node.clipContext(); * // Draw a 5px border along the edge of the sprite, some * // of it will fall outside the area, but it is clipped. * context.lineWidth = 5.0; * context.strokeStyle = 'rgba(255,0,0,1)'; * context.strokeRect( 0, 0, node.width, node.height ); * // other drawing commands * node.restoreContext(); */ }, { key: "clipContext", value: function clipContext() { var ctx = this.context; ctx.save(); ctx.beginPath(); ctx.rect(this.rectangle.left + 1, this.rectangle.top + 1, this.width - 2, this.height - 2); ctx.clip(); ctx.translate(this.rectangle.Xcentre, this.rectangle.Ycentre); return ctx; } /** * Restore the draw context of the {@link module:texture-manager/knapsack/node#canvas|`canvas`}. Call this when done drawing the sprite. * @category drawing * @example * var context = node.clipContext(); * // Draw a 5px border along the edge of the sprite, some * // of it will fall outside the area, but it is clipped. * context.lineWidth = 5.0; * context.strokeStyle = 'rgba(255,0,0,1)'; * context.strokeRect( 0, 0, node.width, node.height ); * // other drawing commands * node.restoreContext(); */ }, { key: "restoreContext", value: function restoreContext() { this.context.restore(); } /** * Allocate a node in this {@link module:texture-manager/knapsack|`Knapsack`} for the given width and height. This is the main workhorse of this library. * @param {integer} width * @param {integer} height * @returns {KnapsackNode} A new node which describes a rectangular area in the knapsack. * @ignore * @category allocation */ }, { key: "allocate", value: function allocate(width, height) { // If we're not a leaf node if (this.hasChildren()) { // then try inserting into our first child var newNode = this.leftChild.allocate(width, height); if (newNode instanceof KnapsackNode) { newNode.claim(); return newNode; } // There was no room: try to insert into second child return this.rightChild.allocate(width, height); } else { // if there's already an image here, return if (this.isOccupied()) { return null; } // if this node is too small, give up here if (width > this.width || height > this.height) { return null; } // if we're just the right size, accept if (width === this.width && height === this.height) { this.claim(); return this; } // otherwise, got to split this node and create some kids this.leftChild = new KnapsackNode(this.knapsack); this.rightChild = new KnapsackNode(this.knapsack); // now decide which way to split var remainingWidth = this.width - width; var remainingHeight = this.height - height; if (remainingWidth > remainingHeight) { // horizontal split this.leftChild.rectangle = new KnapsackRectangle(this.rectangle.left, this.rectangle.top, this.rectangle.left + width, this.rectangle.bottom); this.rightChild.rectangle = new KnapsackRectangle(this.rectangle.left + width, this.rectangle.top, this.rectangle.right, this.rectangle.bottom); } else { // vertical split this.leftChild.rectangle = new KnapsackRectangle(this.rectangle.left, this.rectangle.top, this.rectangle.right, this.rectangle.top + height); this.rightChild.rectangle = new KnapsackRectangle(this.rectangle.left, this.rectangle.top + height, this.rectangle.right, this.rectangle.bottom); } // Some crude painting to help troubleshooting if (this.knapsack.textureManager.debug) { var context = this.context; context.lineWidth = 4.0; context.strokeStyle = "rgba(255,0,0,1)"; context.strokeRect(this.leftChild.rectangle.left, this.leftChild.rectangle.top, this.leftChild.width, this.leftChild.height); context.lineWidth = 4.0; context.strokeStyle = "rgba(0,255,0,1)"; context.strokeRect(this.rightChild.rectangle.left, this.rightChild.rectangle.top, this.rightChild.width, this.rightChild.height); } // Recurse into the first child to continue the allocation return this.leftChild.allocate(width, height); } } /** * Claim the node to be in use by giving it a (unique) ID for an image, this prevents it from being used for another image. After calling this method it is ready to be drawn. * @ignore * @category allocation */ }, { key: "claim", value: function claim() { this.imageID = Math$1.generateUUID(); // Some crude painting to help troubleshooting if (this.knapsack.textureManager.debug) { var context = this.context; context.lineWidth = 2.0; context.strokeStyle = "rgba( 0, 0, 255, 1 )"; context.strokeRect(this.rectangle.left + 0.5, this.rectangle.top + 0.5, this.width - 1, this.height - 1); } } }]); return KnapsackNode; }(); /** * @constructor * @param {TextureManager} textureManager - The {@link module:texture-manager|`TextureManager`} which created this `Knapsack` * @param {integer} size - The size of the texture */ var Knapsack = /*#__PURE__*/function () { function Knapsack(textureManager, size) { _classCallCheck(this, Knapsack); this.textureManager = textureManager; this.textureSize = size; this.textureLoaded = false; this.rootNode = new KnapsackNode(this); // Lazy initialising these: this._rootTexture = null; this._canvas = null; } /** * Lazily built HTML `<canvas>` element for this `Knapsack`. * @type {external:canvas} * @readonly */ _createClass(Knapsack, [{ key: "canvas", get: function get() { if (!this._canvas) { this._canvas = document.createElement("canvas"); this._canvas.width = this.textureSize; this._canvas.height = this.textureSize; } return this._canvas; } /** * Lazily built {@link external:Texture|`THREE.Texture`}, this is created as a "master" texture. Each node will get its own `.clone()`, which should be shared in memory. * @type {external:Texture} * @readonly */ }, { key: "rootTexture", get: function get() { if (!this._rootTexture) { this._rootTexture = new Texture(this.canvas, UVMapping); } return this._rootTexture; } /** * Proxy method, allocate a texture atlas node for a sprite image of `width` by `height` pixels. * @param {integer} width * @param {integer} height * @returns {external:Promise} */ }, { key: "allocateNode", value: function allocateNode(width, height) { return this.rootNode.allocate(width, height); } }]); return Knapsack; }(); /** * @constructor * @param {integer} [size=1024] Optional size for the textures. Must be a power of two. * @example * // We want 512x512 pixel textures * var textureManager = new TextureManager( 512 ); * ... * textureManager.allocateNode( ... ); */ var TextureManager = /*#__PURE__*/function () { function TextureManager(size) { _classCallCheck(this, TextureManager); /** * The size of the textures as was validated when constructing the object. * @namespace module:texture-manager~TextureManager#size * @type {integer} * @ignore * @category readonly */ this.size = typeof size === "number" && /^(128|256|512|1024|2048|4096|8192|16384)$/.test(size) ? size : 1024; /** * As the texture manager allocates nodes, it creates a new {@link module:texture-manager/knapsack|`Knapsack`} when it needs to provide space for nodes. This is an array with all the knapsacks which have been created. * @namespace module:texture-manager~TextureManager#knapsacks * @type {Knapsack[]} * @readonly * @category readonly * @example * // Show the canvases in the DOM element with id="canvases" * // (you'd normally do this from the browser console) * textureManager.knapsacks.forEach( function( knapsack ) { * document.getElementById('canvases').appendChild( knapsack.canvas ); * }); */ this.knapsacks = []; /** * The debug property can be set to `true` after instantiating the object, which will make the {@link module:texture-manager/knapsack/node|`KnapsackNode`} class draw outlines as it allocates nodes. This can make it much more obvious what is going on, such as whether your text is properly sized and centered. * @namespace module:texture-manager~TextureManager#debug * @type {boolean} * @example * textureManager.debug = true; */ this.debug = false; } /** * Add a new knapsack to the texture manager. * @param {integer} size * @returns {Knapsack} * @ignore */ _createClass(TextureManager, [{ key: "_addKnapsack", value: function _addKnapsack(size) { var knapsack = new Knapsack(this, size); this.knapsacks.push(knapsack); if (this.debug) { console.log("TextureManager: allocated ".concat(this.textureSize, "px texture map #").concat(this.knapsacks.length)); } return knapsack; } /** * The actual used size of the texture. * @type {integer} * @readonly * @category readonly */ }, { key: "textureSize", get: function get() { return this.size; } /** * Allocate a texture atlas node for a sprite image of `width` by `height` pixels. Unlike allocateNode, it does not return a {external:Promise} and it works synchronously. * @param {integer} width * @param {integer} height * @returns {KnapsackNode} * @category allocation * @throws {Error} The given with and height must fit in the texture. * @example * let node = textureManager.allocate( 100, 20 ); */ }, { key: "allocate", value: function allocate(width, height) { // Prevent allocating knapsacks when there's no chance to fit the node // FIXME TODO: try a bigger texture size if it doesn't fit? this._validateSize(width, height); return this._allocate(width, height); } /** * {external:Promise} based version of {@link allocate}. * * This method will require you to use a {external:Promise} polyfill if you want to support IE11 or older, as that browser doesn't support promises natively. * @param {integer} width * @param {integer} height * @returns {external:Promise} * @category allocation * @example * textureManager.allocateNode( 100, 20 ).then( * function( node ) { * // Do something with the node in this Promise, such as * // creating a sprite and adding it to the scene. * }, * function( error ) { * // Promise was rejected * console.error( "Could not allocate node:", error ); * } * ); */ }, { key: "allocateNode", value: function allocateNode(width, height) { var _this = this; return new Promise(function (resolve, reject) { try { // Prevent allocating knapsacks when there's no chance to fit the node // FIXME TODO: try a bigger texture size if it doesn't fit? _this._validateSize(width, height); resolve(_this._allocate(width, height)); } catch (error) { reject(error); } }); } /** * Asynchronously allocate a texture atlas node for a sprite image of `width` by `height` pixels. Returns a result through resolving the promise. The asynchronous approach will potentially allow for better optimisation of packing nodes in the texture space. * * When done adding nodes, you should call {@link solveASync}. Your queued promises will then be settled. But note that the {external:Promise} will still be rejected straight away if the given width or height don't fit. * @param {integer} width * @param {integer} height * @returns {external:Promise} * @category allocation * @example * // First prepare all your node allocations: * [ 1, 2, 3 ].forEach( function() { * textureManager.allocateASync( 100, 20 ).then( * function( node ) { * // Do something with the node in this Promise, such as * // creating a sprite and adding it to the scene. * // Note: this promise won't succesfully settle until * // after you also called solveASync! * }, * function( error ) { * // Promise was rejected * console.error( "Could not allocate node:", error ); * } * ); * }); * // Then resolve all the outstanding allocations: * textureManager.solveASync().then( function( result ) { * console.log( `${ result.length } allocations have resolved` ); * }); */ }, { key: "allocateASync", value: function allocateASync(width, height) { var _this2 = this; if (!Array.isArray(this._queue)) { this._queue = []; } var queueEntry; var promise = new Promise(function (resolve, reject) { try { // Prevent allocating knapsacks when there's no chance to fit the node // FIXME TODO: try a bigger texture size if it doesn't fit? _this2._validateSize(width, height); // Queue our resolution, which will be settled with .solveASync() queueEntry = { resolve: resolve, reject: reject, width: width, height: height }; } catch (error) { reject(error); } }); if (queueEntry) { queueEntry.promise = promise; this._queue.push(queueEntry); } return promise; } /** * Trigger resolution of any outstanding node allocation promises, i.e. those that have been created with {@link allocateASync}. Call this when you've added nodes, or their promises will not settle. * * This is by design, as postponing of the node allocation makes it possible for the texture manager to optimise packing of the texture space in the most efficient manner possible. * @returns {external:Promise} * @category allocation * @throws {Error} You're trying to resolve a queue which hasn't been set up. Call {@link allocateASync} at least once before calling this. * @example * textureManager.solveASync().then( function( count ) { * console.log( `${ count } node allocations have been resolved` ); * }); */ }, { key: "solveASync", value: function solveASync() { var _this3 = this; /*eslint no-unused-vars: 0*/ if (!Array.isArray(this._queue)) { throw new Error("You're trying to resolve a queue which hasn't been set up. Call allocateASync before using this."); } var promises = []; this._queue.forEach(function (entry) { var promise = entry.promise, resolve = entry.resolve; entry.reject; var width = entry.width, height = entry.height; var node = _this3._allocate(width, height); resolve(node); promises.push(promise); }); this._queue = []; return Promise.all(promises); } /** * Low level helper to assert whether the given width and height will fit. * @param {integer} width * @param {integer} height * @category allocation * @throws {Error} Width of <number> is too large for these textures. * @throws {Error} Height of <number> is too large for these textures. * @private * @ignore */ }, { key: "_validateSize", value: function _validateSize(width, height) { if (width > this.textureSize) { throw new Error("Width of ".concat(width, " is too large for these textures")); } if (height > this.textureSize) { throw new Error("Height of ".concat(height, " is too large for these textures")); } } /** * Low level helper to allocate a texture atlas node for a sprite image of `width` by `height` pixels. * @param {integer} width * @param {integer} height * @returns {KnapsackNode} * @category allocation * @private * @ignore */ }, { key: "_allocate", value: function _allocate(width, height) { var node = null; // First try to get a node from the existing knapsacks this.knapsacks.forEach(function (knapsack) { if (node === null || node === undefined) { node = knapsack.allocateNode(width, height); } }); // Didn't get a node yet but it *should* fit, so make a new texture atlas with the same size if (node === null) { var knapsack = this._addKnapsack(this.textureSize); node = knapsack.allocateNode(width, height); } return node; } /** * Release the given node. * @param {KnapsackNode} node * @category allocation * @example * textureManager.release( node ); */ }, { key: "release", value: function release(node) { if (node) { node.release(); } } }]); return TextureManager; }(); /** The main entry point for 'global' mode, to be used when you're not able to use `require();` or ES6 modules to load the functionality of this library. Include the library by loading the JavaScript directly, or combine it with your other code, and then do: ```javascript // Instantiate a new TextureManager with 512x512 textures var textureManager = new window.threeSpriteAtlasTextureManager( 512 ); ``` * @namespace threeSpriteAtlasTextureManager * @constructor * @global * @param {integer} [size=1024] Optional size for the textures. Must be a power of two. */ export default TextureManager; //# sourceMappingURL=three-sprite-texture-atlas-manager.es6.js.map
export const ic_inbox = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M19 3H4.99c-1.11 0-1.98.89-1.98 2L3 19c0 1.1.88 2 1.99 2H19c1.1 0 2-.9 2-2V5c0-1.11-.9-2-2-2zm0 12h-4c0 1.66-1.35 3-3 3s-3-1.34-3-3H4.99V5H19v10z"},"children":[]}]};
(function($) { // functions for handling the path // thanks sammy.js // var PATH_REPLACER = "([^\/]+)", // PATH_NAME_MATCHER = /:([\w\d]+)/g, // QUERY_STRING_MATCHER = /\?([^#]*)$/, // SPLAT_MATCHER = /(\*)/, // SPLAT_REPLACER = "(.+)", var _currentPath, _lastPath, _pathInterval; function hashChanged() { _currentPath = getPath(); // if path is actually changed from what we thought it was, then react if (_lastPath != _currentPath) { // return triggerOnPath(_currentPath); wiki.open(_currentPath); } } $.tapirWiki = { // changeFuns : [], // paths : [], // begin : function(defaultPath) { // this should trigger the defaultPath if there's not a path in the URL // otherwise it should trigger the URL's path // $(function() { // var loadPath = getPath(); // if (loadPath) { // triggerOnPath(loadPath); // } else { // goPath(defaultPath); // triggerOnPath(defaultPath); // } // }) // }, // go : function(path) { // goPath(path); // triggerOnPath(path); // }, // onChange : function (fun) { // $.pathbinder.changeFuns.push(fun); // }, pageChangeReset: function(page) { _lastPath = _currentPath = page; } }; function pollPath(every) { function hashCheck() { _currentPath = getPath(); // path changed if _currentPath != _lastPath if (_lastPath != _currentPath) { setTimeout(function() { $(window).trigger('hashchange'); }, 1); } } hashCheck(); _pathInterval = setInterval(hashCheck, every); $(window).bind('unload', function() { clearInterval(_pathInterval); }); } //function triggerOnPath(path) { // $.pathbinder.changeFuns.forEach(function(fun) {fun(path)}); // var pathSpec, path_params, params = {}, param_name, param; // for (var i=0; i < $.pathbinder.paths.length; i++) { // pathSpec = $.pathbinder.paths[i]; //$.log("pathSpec", pathSpec); // if ((path_params = pathSpec.matcher.exec(path)) !== null) { //$.log("path_params", path_params); // path_params.shift(); // for (var j=0; j < path_params.length; j++) { // param_name = pathSpec.param_names[j]; // param = decodeURIComponent(path_params[j]); // if (param_name) { // params[param_name] = param; // } else { // if (!params.splat) params.splat = []; // params.splat.push(param); // } // }; // $.log("path trigger for "+path); // wiki.open(params.id); // return true; // removed this to allow for multi match // } // }; // }; // bind the event $(function() { if ('onhashchange' in window) { // we have a native event } else { pollPath(100); } // setTimeout(hashChanged,50); $(window).bind('hashchange', hashChanged); }); // function registerPath(pathSpec) { // $.pathbinder.paths.push(pathSpec); // }; // function setPath(pathSpec, params) { //var newPath = $.mustache(pathSpec.template, params); // var newPath = params // goPath(newPath); // }; function goPath(newPath) { window.location = '_rewrite#' + newPath; _lastPath = getPath(); } function getPath() { var matches = window.location.toString().match(/^[^#]*#(.+)$/); return matches ? matches[1] : ''; } // function makePathSpec(path, callback) { // var param_names = []; // var template = ""; // PATH_NAME_MATCHER.lastIndex = 0; // while ((path_match = PATH_NAME_MATCHER.exec(path)) !== null) { // param_names.push(path_match[1]); // } // return { // param_names : param_names, // matcher : new RegExp(path.replace( // PATH_NAME_MATCHER, PATH_REPLACER).replace( // SPLAT_MATCHER, SPLAT_REPLACER) + "$"), // template : path.replace(PATH_NAME_MATCHER, function(a, b) { // return '{{'+b+'}}'; // }).replace(SPLAT_MATCHER, '{{splat}}'), // callback : callback // }; // }; // $.fn.pathbinder = function(func, path) { // var self = $(this); // var pathSpec = makePathSpec(path, func); // self.bind(name, function(ev, params) { // set the path when triggered // $.log("set path", name, pathSpec) // setPath(pathSpec, params); // }); // trigger when the path matches // registerPath(pathSpec); // }; })(jQuery);
export default { create({Meteor, LocalState}, postId, text) { if (!text) { return LocalState.set('CREATE_COMMENT_ERROR', 'Comment text is required.'); } if (!postId) { return LocalState.set('CREATE_COMMENT_ERROR', 'postId is required.'); } LocalState.set('CREATE_COMMENT_ERROR', null); const id = Meteor.uuid(); Meteor.call('posts.createComment', id, postId, text, (err) => { if (err) { return LocalState.set('CREATE_COMMENT_ERROR', err.message); } }); }, like({Meteor, LocalState, FlowRouter}, id) { console.log("called like") Meteor.call('comments.like', id, (err) => { if (err) { return LocalState.set('SAVING_ERROR', err.message); } }); }, clearErrors({LocalState}) { return LocalState.set('CREATE_COMMENT_ERROR', null); } };
/* LIB */ const radial = require('../radial'); const params = radial.getParams(); /* MODULES */ const request = require('request'); /* CONSTRUCTOR */ (function () { var Nonce = {}; /* PRIVATE VARIABLES */ /* PUBLIC FUNCTIONS */ Nonce.get = function (fn) { var environment = params.environment; var nonceEndpoint = environment === 'development' ? 'https://tst.payments.radial.com/hosted-payments/auth/nonce' : 'https://hostedpayments.radial.com/hosted-payments/auth/nonce'; request({ url: nonceEndpoint, method: 'POST', body: { username: params.storeCode, password: params.apiKey }, json: true }, function (err, response, body) { if (err) { return fn(err); } else if (!response || !body) { return fn('Error - no response on request'); } if (response.statusCode !== 200 || body.error_code) { return fn(body.error_message); } return fn(null, { nonce: body.nonce, expiresInSeconds: body.expire_in_seconds }); }); }; /* NPM EXPORT */ if (typeof module === 'object' && module.exports) { module.exports = Nonce.get; } else { throw new Error('This module only works with NPM in NodeJS environments.'); } }());
module.exports = { entry: './web/index.ts', output: { filename: './dist/web-bundle.js', }, resolve: { extensions: ['', '.webpack.js', '.web.js', '.js', '.ts'] }, module: { loaders: [{ test: /\.ts$/, loader: 'ts-loader' }] } };
// File List // ========= // // The List is an object for tracking all files that karma knows about // currently. // Dependencies // ------------ 'use strict'; require('core-js'); var from = require('core-js/library/fn/array/from'); var Promise = require('bluebird'); var mm = require('minimatch'); var Glob = require('glob').Glob; var fs = Promise.promisifyAll(require('fs')); var pathLib = require('path'); var File = require('./file'); var Url = require('./url'); var helper = require('./helper'); var _ = helper._; var log = require('./logger').create('watcher'); // Constants // --------- var GLOB_OPTS = { cwd: '/', follow: true, nodir: true, sync: true }; // Helper Functions // ---------------- function byPath(a, b) { if (a.path > b.path) return 1; if (a.path < b.path) return -1; return 0; } // Constructor // // patterns - Array // excludes - Array // emitter - EventEmitter // preprocess - Function // batchInterval - Number var List = function List(patterns, excludes, emitter, preprocess, batchInterval) { // Store options this._patterns = patterns; this._excludes = excludes; this._emitter = emitter; this._preprocess = Promise.promisify(preprocess); this._batchInterval = batchInterval; // The actual list of files this.buckets = new Map(); // Internal tracker if we are refreshing. // When a refresh is triggered this gets set // to the promise that `this._refresh` returns. // So we know we are refreshing when this promise // is still pending, and we are done when it's either // resolved or rejected. this._refreshing = Promise.resolve(); var self = this; // Emit the `file_list_modified` event. // This function is throttled to the value of `batchInterval` // to avoid spamming the listener. function emit() { self._emitter.emit('file_list_modified', self.files); } var throttledEmit = _.throttle(emit, self._batchInterval, { leading: false }); self._emitModified = function (immediate) { immediate ? emit() : throttledEmit(); }; }; // Private Interface // ----------------- // Is the given path matched by any exclusion filter // // path - String // // Returns `undefined` if no match, otherwise the matching // pattern. List.prototype._isExcluded = function (path) { return _.find(this._excludes, function (pattern) { return mm(path, pattern); }); }; // Find the matching include pattern for the given path. // // path - String // // Returns the match or `undefined` if none found. List.prototype._isIncluded = function (path) { return _.find(this._patterns, function (pattern) { return mm(path, pattern.pattern); }); }; // Find the given path in the bucket corresponding // to the given pattern. // // path - String // pattern - Object // // Returns a File or undefined List.prototype._findFile = function (path, pattern) { if (!path || !pattern) return; if (!this.buckets.has(pattern.pattern)) return; return _.find(from(this.buckets.get(pattern.pattern)), function (file) { return file.originalPath === path; }); }; // Is the given path already in the files list. // // path - String // // Returns a boolean. List.prototype._exists = function (path) { var self = this; var patterns = this._patterns.filter(function (pattern) { return mm(path, pattern.pattern); }); return !!_.find(patterns, function (pattern) { return self._findFile(path, pattern); }); }; // Check if we are currently refreshing List.prototype._isRefreshing = function () { return this._refreshing.isPending(); }; // Do the actual work of refreshing List.prototype._refresh = function () { var self = this; var buckets = this.buckets; return Promise.all(this._patterns.map(function (patternObject) { var pattern = patternObject.pattern; if (helper.isUrlAbsolute(pattern)) { buckets.set(pattern, new Set([new Url(pattern)])); return Promise.resolve(); } var mg = new Glob(pathLib.normalize(pattern), GLOB_OPTS); var files = mg.found; buckets.set(pattern, new Set()); if (_.isEmpty(files)) { log.warn('Pattern "%s" does not match any file.', pattern); return; } return Promise.all(files.map(function (path) { if (self._isExcluded(path)) { log.debug('Excluded file "%s"', path); return Promise.resolve(); } var mtime = mg.statCache[path].mtime; var doNotCache = patternObject.nocache; var file = new File(path, mtime, doNotCache); if (file.doNotCache) { log.debug('Not preprocessing "%s" due to nocache'); return Promise.resolve(file); } return self._preprocess(file).then(function () { return file; }); })).then(function (files) { files = _.compact(files); if (_.isEmpty(files)) { log.warn('All files matched by "%s" were excluded.', pattern); } else { buckets.set(pattern, new Set(files)); } }); })).cancellable().then(function () { self.buckets = buckets; self._emitModified(true); return self.files; })['catch'](Promise.CancellationError, function () { // We were canceled so return the resolution of the new run return self._refreshing; }); }; // Public Interface // ---------------- Object.defineProperty(List.prototype, 'files', { get: function get() { var self = this; var served = this._patterns.filter(function (pattern) { return pattern.served; }).map(function (p) { return from(self.buckets.get(p.pattern) || []).sort(byPath); }); var included = this._patterns.filter(function (pattern) { return pattern.included; }).map(function (p) { return from(self.buckets.get(p.pattern) || []).sort(byPath); }); var uniqFlat = function uniqFlat(list) { return _.uniq(_.flatten(list), 'path'); }; return { served: uniqFlat(served), included: uniqFlat(included) }; } }); // Reglob all patterns to update the list. // // Returns a promise that is resolved when the refresh // is completed. List.prototype.refresh = function () { if (this._isRefreshing()) { this._refreshing.cancel(); } this._refreshing = this._refresh(); return this._refreshing; }; // Set new patterns and excludes and update // the list accordingly // // patterns - Array, the new patterns. // excludes - Array, the new exclude patterns. // // Returns a promise that is resolved when the refresh // is completed. List.prototype.reload = function (patterns, excludes) { this._patterns = patterns; this._excludes = excludes; // Wait until the current refresh is done and then do a // refresh to ensure a refresh actually happens return this.refresh(); }; // Add a new file from the list. // This is called by the watcher // // path - String, the path of the file to update. // // Returns a promise that is resolved when the update // is completed. List.prototype.addFile = function (path) { var self = this; // Ensure we are not adding a file that should be excluded var excluded = this._isExcluded(path); if (excluded) { log.debug('Add file "%s" ignored. Excluded by "%s".', path, excluded); return Promise.resolve(this.files); } var pattern = this._isIncluded(path); if (!pattern) { log.debug('Add file "%s" ignored. Does not match any pattern.', path); return Promise.resolve(this.files); } if (this._exists(path)) { log.debug('Add file "%s" ignored. Already in the list.', path); return Promise.resolve(this.files); } var file = new File(path); this.buckets.get(pattern.pattern).add(file); return Promise.all([fs.statAsync(path), this._refreshing]).spread(function (stat) { file.mtime = stat.mtime; return self._preprocess(file); }).then(function () { log.info('Added file "%s".', path); self._emitModified(); return self.files; }); }; // Update the `mtime` of a file. // This is called by the watcher // // path - String, the path of the file to update. // // Returns a promise that is resolved when the update // is completed. List.prototype.changeFile = function (path) { var self = this; var pattern = this._isIncluded(path); var file = this._findFile(path, pattern); if (!pattern || !file) { log.debug('Changed file "%s" ignored. Does not match any file in the list.', path); return Promise.resolve(this.files); } return Promise.all([fs.statAsync(path), this._refreshing]).spread(function (stat) { if (stat.mtime <= file.mtime) throw new Promise.CancellationError(); file.mtime = stat.mtime; return self._preprocess(file); }).then(function () { log.info('Changed file "%s".', path); self._emitModified(); return self.files; })['catch'](Promise.CancellationError, function () { return self.files; }); }; // Remove a file from the list. // This is called by the watcher // // path - String, the path of the file to update. // // Returns a promise that is resolved when the update // is completed. List.prototype.removeFile = function (path) { var self = this; return Promise['try'](function () { var pattern = self._isIncluded(path); var file = self._findFile(path, pattern); if (!pattern || !file) { log.debug('Removed file "%s" ignored. Does not match any file in the list.', path); return self.files; } self.buckets.get(pattern.pattern)['delete'](file); log.info('Removed file "%s".', path); self._emitModified(); return self.files; }); }; // Inject dependencies List.$inject = ['config.files', 'config.exclude', 'emitter', 'preprocess', 'config.autoWatchBatchDelay']; // PUBLIC module.exports = List; //# sourceMappingURL=file-list-compiled.js.map
'use strict'; /** * Module dependencies. */ var should = require('should'), mongoose = require('mongoose'), User = mongoose.model('User'), Spork = mongoose.model('Spork'); /** * Globals */ var user, spork; /** * Unit tests */ describe('Spork Model Unit Tests:', function () { beforeEach(function (done) { user = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: 'test@test.com', username: 'username', password: 'M3@n.jsI$Aw3$0m3' }); user.save(function () { spork = new Spork({ title: 'Spork Title', content: 'Spork Content', user: user }); done(); }); }); describe('Method Save', function () { it('should be able to save without problems', function (done) { this.timeout(10000); return spork.save(function (err) { should.not.exist(err); done(); }); }); it('should be able to show an error when try to save without title', function (done) { spork.title = ''; return spork.save(function (err) { should.exist(err); done(); }); }); }); afterEach(function (done) { Spork.remove().exec(function () { User.remove().exec(done); }); }); });
const Discord = require('discord.js'); const settings = require('../settings.json'); exports.run = (client, message, args) => { let reason = args.slice(1).join(' '); let user = message.mentions.users.first(); let logchannel = message.guild.channels.find('name', 'logs'); if (!logchannel) return message.reply('I cannot find a logs channel'); if (!message.member.hasPermission("BAN_MEMBERS")) return msg.reply(":no_entry_sign: **Error:** You don't have the **Ban Members** permission!"); if (reason.length < 1) return message.reply('You must supply a reason for the ban.'); if (message.mentions.users.size < 1) return message.reply('You must mention someone to ban them.').catch(console.error); if (!message.guild.member(user).bannable) return message.reply(`<:redTick:${settings.redTick}> I cannot ban that member`); message.guild.member(user).ban(); const embed = new Discord.RichEmbed() .setColor(0xFF0000) .setTimestamp() .addField('Action:', 'Ban') .addField('User:', `${user.username}#${user.discriminator} (${user.id})`) .addField('Moderator:', `${message.author.username}#${message.author.discriminator}`) .addField('Reason', reason); message.channel.send(`<:hammer:${settings.hammer}> Bippity boppity **BAN**! I\'ve logged the ban in the logs channel.`) return client.channels.get(logchannel.id).send({embed}); }; exports.conf = { enabled: true, guildOnly: false, aliases: [], permLevel: 2 }; exports.help = { name: 'ban', description: 'Bans the mentioned user.', usage: 'ban [mention] [reason]' };
module.exports = { name: 'Search FlashCard', version: '2.0.0', description: 'This extensions is to search flashcard site (flashcard.my.geek.nz).', author: 'Mohamed Alsharaf', manifest_version: 2, icons: { '16': 'icons/16.png', '128': 'icons/128.png', '200': 'icons/icon.png' }, permissions: [ '<all_urls>', '*://*/*', 'activeTab', 'tabs', 'cookies', 'background', 'contextMenus', 'unlimitedStorage', 'storage', 'notifications', 'identity', 'identity.email' ], browser_action: { default_title: 'title', default_popup: 'pages/popup.html' }, // background: { // persistent: false, // page: 'pages/background.html' // }, // devtools_page: 'pages/devtools.html', options_page: 'pages/options.html', content_scripts: [{ js: [ 'js/inject.js' ], run_at: 'document_end', matches: ['<all_urls>'], all_frames: true }], content_security_policy: "script-src 'self' 'unsafe-eval'; object-src 'self'", web_accessible_resources: [ 'panel.html', 'js/content.js' ] }
/* ___ create, usage ___ en_US ___ node kinesthetic.bin.js create <name> options: --help display help message --region <string> AWS region ___ $ ___ en_US ___ name is required: a stream name is required. ___ delete, usage ___ en_US ___ node kinesthetic.bin.js create <name> options: --help display help message --region <string> AWS region ___ $ ___ en_US ___ name is required: a stream name is required. ___ describe, usage ___ en_US ___ node kinesthetic.bin.js describe <name> options: --help display help message --region <string> AWS region ___ $ ___ en_US ___ name is required: a stream name is required. ___ partition, usage ___ en_US ___ node kinesthetic.bin.js describe <name> options: --help display help message --region <string> AWS region ___ $ ___ en_US ___ name is required: a stream name is required. ___ . ___ */ require('arguable')(module, require('cadence')(function (async, program) { program.required('region') var AWS = require('aws-sdk') console.log(program.param.region) var kinesis = new AWS.Kinesis({ region: program.param.region }) var repartition = require('./repartition') switch (program.command[0]) { case 'create': program.assert(program.argv.length == 1, 'name is required') kinesis.createStream({ ShardCount: 1, StreamName: program.argv[0] }, async()) break case 'describe': program.assert(program.argv.length == 1, 'name is required') async(function () { kinesis.describeStream({ StreamName: program.argv[0] }, async()) }, function (response) { console.log(response) }) break case 'partition': program.assert(program.argv.length == 2, 'name is required') repartition(kinesis, program.argv[0], +program.argv[1], async()) break case 'delete': program.assert(program.argv.length == 1, 'name is required') async(function () { kinesis.deleteStream({ StreamName: program.argv[0] }, async()) }, function (response) { console.log(response) }) break } }))
// @flow import React from 'react' import LyraFormBuilderContext from './LyraFormBuilderContext' import {FormBuilderInput} from '../FormBuilderInput' import {Marker} from '../typedefs' type PatchChannel = { subscribe: () => () => {}, receivePatches: (patches: Array<*>) => void } type Props = { value: ?any, schema: any, type: Object, markers: Array<Marker>, patchChannel: PatchChannel, onFocus: Path => void, path: Path, readOnly: boolean, onChange: () => {}, onBlur: () => void, autoFocus: boolean, focusPath: Path } export default class LyraFormBuilder extends React.Component<Props> { _input: ?FormBuilderInput setInput = (input: ?FormBuilderInput) => { this._input = input } componentDidMount() { const {autoFocus} = this.props if (this._input && autoFocus) { this._input.focus() } } render() { const { value, schema, patchChannel, type, path, onChange, readOnly, markers, onFocus, onBlur, focusPath } = this.props return ( <LyraFormBuilderContext value={value} schema={schema} patchChannel={patchChannel} > <FormBuilderInput type={type} path={path} onChange={onChange} level={0} value={value} onFocus={onFocus} onBlur={onBlur} markers={markers} focusPath={focusPath} isRoot readOnly={readOnly} ref={this.setInput} /> </LyraFormBuilderContext> ) } } LyraFormBuilder.createPatchChannel = LyraFormBuilderContext.createPatchChannel
!function(o){o.modal=function(e){window.__zeptoModal?o("#zeptoModal").css("display","block"):(o(document.body).append(o('<div id="zeptoModal" style="font-family:Arial, sans-serif;position:fixed;z-index:1;width:100%;height:100%;overflow:auto;left:0px;top:0px;background-color:rgba(0,0,0,0.4);"><div role="container" style="position:relative;margin:auto;background-color:#eee;width:60%;border:1px solid #333;margin-top:300px;padding:5px"><header style="background-color:#ccc">'+e.title+'<a href="#" role="button" class="close" style="float:right;text-decoration:none;">x</a></header><main>'+e.content+"</main><footer>"+e.footer+"</footer></div></div>")),o("#zeptoModal a.close").on("click",function(){o("#zeptoModal").css("display","none"),o(document).trigger("zeptomodal:hidden")}),o(document).trigger("zeptomodal:created"),window.__zeptoModal={}),o(document).trigger("zeptomodal:shown")}}(Zepto||jQuery);
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M5 15h2V8.41L18.59 20 20 18.59 8.41 7H15V5H5v10z" /> , 'NorthWestOutlined');