code
stringlengths
2
1.05M
// Full list of configuration options available at: // https://github.com/hakimel/reveal.js#configuration Reveal.initialize({ backgroundTransition: 'convex', transition: 'convex', history: true, height: '100%', width: '92%', center: true, slideNumber: 'c', keyboard: { // Customization for my spotlight 39: 'next', // Right Arrow 37: 'prev' // Left Arrow }, viewDistance: 5, // Optional reveal.js plugins dependencies: [ { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } }, { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, { src: 'plugin/bpmn-js/bpmn-viewer.production.min.js'}, { src: 'plugin/bpmn-js/bpmn.js', async: true}, { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }, { src: 'plugin/zoom-js/zoom.js', async: true }, { src: 'plugin/notes/notes.js', async: true } ] });
if("undefined"==typeof jWait)var jWait={}; (function(){function g(a,c,k,l,g){var p=this,d=g?!0:!1;c=c?!0:!1;var m=0<k?k:100,h=0,b=0,n=!1,e=!1,f=l?"["+l+"]":"[cycle:"+(new Date).getTime()+"]";d&&c?console.log(f+" starts at: "+b+"ms"):d&&!c&&console.log(f+" will start in: "+m+"ms");this.call=function(){"function"==typeof a&&a(function(){clearInterval(h);e=!0;d&&console.log(f+" finished at: "+b+"ms")},b)};this.stop=function(){e||clearInterval(h);d&&!e&&console.log(f+" was forced to stop at: "+b+"ms")};this.start=function(){h=setInterval(function(){n|| (n=!0);b++;p.call()},m)};this.isRunnig=function(){return!e};c&&(b++,this.call());this.start()}jWait.list=[];jWait.createCycle=function(a){if("undefined"!=typeof a)return a=new g(a.onUpdate,a.immediate,a.cycleTime,a.name,a.showLogs),this.list.push(a),a}})();
'use strict' var Formatter = require('./Formatter.js') class LogicalEquation { constructor (toNode) { this.operator = null this.toNode = toNode this.nodes = [] this.logicalEdges = [] this.type = 'LogicalEquation' } getNodeList () { var list = [] this.nodes.forEach(n => { if (n instanceof LogicalEquation) { list = list.concat(n.getNodeList()) } else { list.push(n) } }) return list } format (formatter) { formatter = formatter || new Formatter() return formatter.equation(this, formatter) } } module.exports = LogicalEquation
"use strict"; function MsgHandler(api, client, config, sessiondata){ this.api = api; this.client = client; this.config = config; this.sessiondata = sessiondata; var msgHandles = []; require('fs').readdirSync(__dirname + '/' + "msgHandles").forEach(function(file) { // for every file in the 'cmds/' directory if (file.match(/.+\.js/g) !== null) { // if file is a .js file var msgHandle = require(__dirname + '/msgHandles/' + file); // require it msgHandles.push(msgHandle); // store it in cmds for later use } }); this.msgHandles = msgHandles; } MsgHandler.prototype.handle = function(msg, target){ for (var i=0; i<this.msgHandles.length; i++){ var msgHandle = this.msgHandles[i]; try { msgHandle.func(this.api, this.client, this.config, this.sessiondata, target, msg); } catch (err){ console.log(err.stack); } } } module.exports = MsgHandler;
//Define variables //(on smaller screens) menu icons var togglePosition = document.getElementById("togglePosition"); var toggleZoom = togglePosition.nextElementSibling; //dropdown filters menu (on smaller screens) var toolsNav = document.getElementById("toolsNav"); var toggleGrayscale = toolsNav.firstElementChild.children[1]; //menu option grayscale var toggleBrightness = toggleGrayscale.nextElementSibling; //menu option brightness var toggleBlur = toggleBrightness.nextElementSibling; //menu option blur var toggleNegative = toggleBlur.nextElementSibling; //menu option negative var toggleEdgeDetect = toggleNegative.nextElementSibling; //menu option edge-detect var toggleSharpen = toggleEdgeDetect.nextElementSibling; //menu option negative var toggleEmboss = toggleSharpen.nextElementSibling; //menu option negative // last menu icon on smaller screens (open dropdown filters menu) var openFiltersNav = document.getElementById("openFiltersNav"); //close dropdown filters menu var closeFiltersNav = toolsNav.firstElementChild.firstElementChild; //(on smaller screens) tools in the panel below image var controlsPosition = document.getElementsByClassName("controls-position")[0]; var controlsZoom = controlsPosition.nextElementSibling; //grayscale buttons var grayScaleBtns = document.getElementById("grayScale"); var grayScaleBtnsWrapper = grayScaleBtns.children[0]; var grayScaleOn = grayScaleBtnsWrapper.children[0]; var grayScaleOff = grayScaleOn.nextElementSibling; //brighten, blur, play divs var brightenDiv = document.getElementById("brighten-range"); var blurDiv = document.getElementById("blur-range"); var sharpenDiv = document.getElementById("sharpen-range"); //negative buttons var negativeBtns = document.getElementsByClassName("scale-btns")[1]; //div z przyciskami on/off var negativeOn = negativeBtns.children[0].children[0]; var negativeOff = negativeOn.nextElementSibling; //edge-detect buttons var edgeDetectBtns = document.getElementsByClassName("scale-btns")[2]; //div z przyciskami on/off var edgeDetectOn = edgeDetectBtns.children[0].children[0]; var edgeDetectOff = edgeDetectOn.nextElementSibling; //emboss buttons var embossBtns = document.getElementsByClassName("scale-btns")[3]; //div z przyciskami on/off var embossOn = embossBtns.children[0].children[0]; var embossOff = embossOn.nextElementSibling; var sliderFilters = document.getElementsByClassName("slider-filter"); var toolsInfo = document.getElementsByClassName("tools-info")[0]; //filter sliders var brightenRangeSlider = document.getElementById("brightenRange"); var blurRangeSlider = document.getElementById("blurRange"); var sharpenRangeSlider = document.getElementById("sharpenRange"); //variables for image and canvas var imgContainer = document.getElementById("imgContainer"); var userPhoto = document.getElementById("userPhoto"); //user photo var currentPhoto = new Image; //working copy of the photo with all changes included var inputFile = document.getElementById("inputFile"); var uploadPhoto = document.getElementById("uploadPhoto"); //upload button var canvas = document.getElementById("imgCanvas"); var ctx = canvas.getContext("2d"); var resetBtn = document.getElementById("resetBtn"); //reset button var download = document.getElementById("download"); //get it button //controls/buttons in the lower menu (on smaller screens) var moveTop = document.getElementById("moveTop"); var moveRight = document.getElementById("moveRight"); var moveLeft = document.getElementById("moveLeft"); var moveBottom = document.getElementById("moveBottom"); var zoomIn = document.getElementById("zoom-in"); var zoomOut = document.getElementById("zoom-out"); //button on the left-hand panel (on bigger screens) var toolsLeftMoveTop = document.getElementById("toolsLeftMoveTop"); var toolsLeftMoveLeft = document.getElementById("toolsLeftMoveLeft"); var toolsLeftMoveRight = document.getElementById("toolsLeftMoveRight"); var toolsLeftMoveBottom = document.getElementById("toolsLeftMoveBottom"); var toolsLeftZoomIn = document.getElementById("toolsLeftZoomIn"); var toolsLeftZoomOut = document.getElementById("toolsLeftZoomOut"); var x; var y; if (typeof x === "undefined") { x = 0; } if (typeof y === "undefined") { y = 0; }
/** * Created by Arsan Irianto on 12/12/2015. */ function reloadDataTable(){ $('#tgi').DataTable({ ajax: "modules/json_gi.php", pagingType: "full_numbers", dom: "B<'row'<'col-sm-8'l><'col-sm-4'f>>" + "<'row'<'col-sm-12'>>" + "<'row'<'col-sm-12'>>" + "<'row'<'col-sm-8'><'col-sm-4'>>tipr", scrollX: true, buttons: [ 'copy', 'csv', 'excel' ], destroy : true }); $("#tgi_wrapper > .dt-buttons").appendTo("#btnTable"); } function showModals( id ){ waitingDialog.show(); // Untuk Eksekusi Data Yang Ingin di Edit if( id ){ $.ajax({ type: "POST", url: "modules/crud_gi.php", dataType: 'json', data: {id:id,type:"get"}, success: function(res) { waitingDialog.hide(); setModalData( res ); } }); } // Form Add new else{ clearModals(); $("#myModals").modal("show"); //$("#myModalLabel").html("New User"); $("#type").val("new"); waitingDialog.hide(); } } function submitGi() { var formData = $("#form_gi").serialize(); waitingDialog.show(); $.ajax({ type: "POST", url: "modules/crud_gi.php", dataType: 'json', data: formData, success: function(data) { if(data=="OK"){ reloadDataTable(); } else{alert(data);} waitingDialog.hide(); } }); } function submitDelete() { var formData = $("#form_delete").serialize(); waitingDialog.show(); $.ajax({ type: "POST", url: "modules/crud_gi.php", dataType: 'json', data: formData, success: function(data){ reloadDataTable(); waitingDialog.hide(); } }); //clearModals(); } function deleteGi( id ) { $.ajax({ type: "POST", url: "modules/crud_gi.php", dataType: 'json', data: {id:id,type:"get"}, success: function(data) { $('#delModal').modal('show'); $('#delid').val(id); waitingDialog.hide(); } }); } function clearModals() { $("#GIID").val(""); $("#GIID").attr('readonly', false); $("#GI").val(""); $("#DCCID").val(""); $("#DESC").val(""); } //Show Data to edit function setModalData( data ){ $("#type").val("edit"); $("#GIID").val(data.GIID); $("#GIID").attr('readonly', true); $("#GI").val(data.GI.trim()); $("#DCCID").val(data.DCCID); DESCR = (data.DESCR == null) ? "" : data.DESCR.trim(); $("#DESC").val(DESCR); $("#myModals").modal("show"); } $(document).ready(function(){ reloadDataTable(); });
const express = require('express'), app = express(), path = require('path'); app.use('/build', express.static(path.resolve(__dirname, './build'))); app.get('/*', function (req, res) { res.sendFile(path.resolve(__dirname, './index.html')); }); app.listen(3000, function () { console.log('Demo live on localhost:3000'); });
ext.chats = { def: function (id) { return { id: id, name: 'DELETED', abbr: 'DELETED', photo: 'http://vk.com/images/camera_b.gif', users: [], loaded: 0, typing: 0 } }, load: function (id, forced) { if(!ext.scope.chats[id] || forced) { if (!ext.scope.chats[id]) { ext.scope.chats[id] = ext.chats.def(id); ext.apply(); } ext.api('messages.getChat', { chat_id: id, fields: ext.users.fields }, function (resp) { if(resp) { var chat = { id: id, name: resp.title, photo: resp.photo_100 || 'http://vk.com/images/camera_b.gif', users: _.pluck(resp.users, 'id') } ext.scope.chats[id] = _.extend(ext.chats.def(id), _.extend(ext.scope.chats[id] || {}, chat)); ext.apply(); _.each(resp.users, ext.users.add); } }); } return ext.scope.chats[id]; } }
module.exports.timeout = ms => new Promise(res => setTimeout(res, ms))
'use strict'; const tap = require('tap'); const remark = require('remark'); const behead = require('.'); tap.test('remark-behead', t => { let actual; t.throws(() => { remark() .use(behead, {depth: 'foo'}) .processSync('# foo') .toString(); remark() .use(behead, {between: {}}) .processSync('# foo') .toString(); remark() .use(behead, {before: {}}) .processSync('# foo') .toString(); remark() .use(behead, {after: {}}) .processSync('# foo') .toString(); remark() .use(behead, {before: 0}) .processSync('# foo') .toString(); remark() .use(behead, {after: 2}) .processSync('# foo') .toString(); remark() .use(behead, {between: [-1, 0]}) .processSync('# foo') .toString(); }, 'Expect a `number` for depth; Expect a finite index or child `node`'); t.doesNotThrow(() => { t.ok(remark().use(behead).freeze()); t.equal( (actual = remark() .use(behead, { after: {type: 'heading', children: [{value: 'foo'}]}, depth: 1 }) .processSync(['# foo', '# bar'].join('\n')) .toString()), '# foo\n\n## bar\n', actual ); t.equal( (actual = remark() .use(behead, {after: 0, depth: 1}) .processSync(['# foo', '# bar'].join('\n')) .toString()), '# foo\n\n## bar\n', actual ); t.equal( (actual = remark() .use(behead, {before: 1, depth: 1}) .processSync(['# foo', '# bar'].join('\n')) .toString()), '## foo\n\n# bar\n', actual ); t.equal( (actual = remark() .use(behead, {}) .processSync('# foo') .toString()), '# foo\n', actual ); t.equal( (actual = remark() .use(behead, {depth: 1}) .processSync('# foo') .toString()), '## foo\n', actual ); t.equal( (actual = remark() .use(behead, {depth: -1}) .processSync('## foo') .toString()), '# foo\n', actual ); t.equal( (actual = remark() .use(behead, {depth: 100}) .processSync('## foo') .toString()), '###### foo\n', actual ); t.equal( (actual = remark() .use(behead, {depth: -100}) .processSync('## foo') .toString()), '# foo\n', actual ); t.equal( (actual = remark() .use(behead, {after: 'foo', depth: 1}) .processSync('# foo\n# bar') .toString()), '# foo\n\n## bar\n', actual ); t.equal( (actual = remark() .use(behead, {before: 'bar', depth: 1}) .processSync('# foo\n# bar') .toString()), '## foo\n\n# bar\n', actual ); t.equal( (actual = remark() .use(behead, {between: ['foo', 'baz'], depth: 1}) .processSync(['# foo', '# bar', '# baz'].join('\n')) .toString()), '# foo\n\n## bar\n\n# baz\n', actual ); }, 'Should not throw'); t.end(); });
'use strict' var models = require('../models'); var address = "localhost"+":"+config.port;
// ReSharper disable UseOfImplicitGlobalInFunctionScope // SMS version of Poinless. console.log('Loading event'); // Twilio Credentials var accountSid = ''; var authToken = ''; var fromNumber = ''; var https = require('https'); var queryString = require('querystring'); // Lambda function: exports.handler = function (event, context) { console.log('Running event'); // The message body contains the answer to the question. // Process this answer to get our response (Body is the name of // the database field which contains the received message body.) var message = event.body; console.log('Processing message: ' + message); var response = GetResponse(message); console.log('Response: ' + response); // Send the response to the sender of the SMS message. // Then end the lambda function, logging the status message. var mobileNumber = event.from; console.log('Sending SMS response to: ' + mobileNumber); SendSMS(mobileNumber, response, function (status) { context.done(null, status); }); }; // Gets a response to send based on the answer provided. // Ideally this would be coming from a database! function GetResponse(answer) { // Question: // ANIMATED DISNEY FILMS WITH ONE WORD TITLES // Any partially or fully animated film made prior to // the beginning of April 2011, which is animated and produced // by the Walt Disney Animation Studios or Disney/Pixar and has // a one word title. var response = 'Your answer ' + answer + ' '; switch (answer.trim().toUpperCase()) { case 'BAMBI': response += 'scored 51'; break; case 'CINDERELLA': response += 'scored 49'; break; case 'ALADDIN': response += 'scored 34'; break; case 'DUMBO': response += 'scored 33'; break; case 'CARS': response += 'scored 32'; break; case 'PINOCCHIO': response += 'scored 30'; break; case 'POCAHONTAS': response += 'scored 23'; break; case 'FANTASIA': response += 'scored 18'; break; case 'UP': response += 'scored 17'; break; case 'MULAN': response += 'scored 11'; break; case 'TANGLED': response += 'scored 11'; break; case 'RATATOUILLE': response += 'scored 4'; break; case 'TARZAN': response += 'scored 4'; break; case 'ENCHANTED': response += 'scored 2'; break; case 'BOLT': response += 'scored 2'; break; case 'HERCULES': response += 'scored 1'; break; case 'DINOSAUR': response += 'was a pointless answer! Congratulations!'; break; default: response += 'was not found in our list.'; } return response; } // Sends an SMS message using the Twilio API // to: Phone number to send to // body: Message body // completedCallback(status) : Callback with status message when the function completes. function SendSMS(to, body, completedCallback) { // The SMS message to send var message = { To: to, From: fromNumber, Body: body }; var messageString = queryString.stringify(message); // Options and headers for the HTTP request var options = { host: 'api.twilio.com', port: 443, path: '/2010-04-01/Accounts/' + accountSid + '/Messages.json', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': Buffer.byteLength(messageString), 'Authorization': 'Basic ' + new Buffer(accountSid + ':' + authToken).toString('base64') } }; // Setup the HTTP request var req = https.request(options, function (res) { res.setEncoding('utf-8'); // Collect response data as it comes back. var responseString = ''; res.on('data', function (data) { responseString += data; }); // Log the responce received from Twilio. // Or could use JSON.parse(responseString) here to get at individual properties. res.on('end', function () { console.log('Twilio Response: ' + responseString); completedCallback('API request sent successfully.'); }); }); // Handler for HTTP request errors. req.on('error', function (e) { console.error('HTTP error: ' + e.message); completedCallback('API request completed with error(s).'); }); // Send the HTTP request to the Twilio API. // Log the message we are sending to Twilio. console.log('Twilio API call: ' + messageString); req.write(messageString); req.end(); }
Meteor.methods({ /* save an entity and associated methods */ getEntity: function(id) { check(id, String); var entity = Entities.findOne(id); return entity; }, addEntity: function (entity) { console.log("entities.js: checking entity: ", entity); check(entity, { _id: String, name: String, etypes: [String] }); // Make sure the user is logged in before inserting a task if (!this.userId) { var message = "User not authenticated"; console.error(message); return { success: false, message: message}; } //make sure the entity does not already exists check(entity._id, String); var alreadyExisting = Entities.findOne(entity._id); if (alreadyExisting) { var message = "Entity already exists"; console.error(message); return { success: false, message: message}; } entity.creator = this.userId; //entity.updater = this.userId; entity.owners = [this.userId]; var theDate = new Date(); entity.created = theDate; //entity.updated = theDate; entity.valid = 1; //if (!entity.source) entity.source = "biolog/server/entities"; console.log("Inserting entity: " + JSON.stringify(entity)); Entities.insert(entity); return {success: true}; } });
var setFocus = function (a) { a = $(a); var token = a.data('token'); EventBroadcaster.broadcast(BroadcastMessages.SYSTEMTREEBINDING_FOCUS, token); }; var executeAction = function (a) { a = $(a); var providerName = a.data('providername'); var entityToken = a.data('entitytoken'); var actionToken = a.data('actiontoken'); var piggybag = a.data('piggybag'); var piggybagHash = a.data('piggybaghash'); var clientElement = new ClientElement(providerName, entityToken, piggybag, piggybagHash); var actionElement = new ActionElement(a.html(), actionToken); var systemAction = new SystemAction(actionElement); var systemNode = new SystemNode(clientElement); SystemAction.invoke(systemAction, systemNode); }; function ClientElement(providerName, entityToken, piggybag, piggybagHash) { this.ProviderName = providerName; this.EntityToken = entityToken; this.Piggybag = piggybag; this.PiggybagHash = piggybagHash; this.HasChildren = false; this.IsDisabled = false; this.DetailedDropSupported = false; this.ContainsTaggedActions = false; this.TreeLockEnabled = false; return this; }; function ActionElement(label, actionToken) { this.Label = label; this.ActionToken = actionToken; return this; };
import curry from './curry' import surround from './uncurried/surround' /** * Surrounds the list of `cs` with the values `a` and `b`. * * @function * @param a The left value. * @param b The right value. * @param {Array|String} cs The list to surround. * @returns {Array|String} A new list. * @example * * import { surround } from 'fkit' * surround(0, 4, [1, 2, 3]) // [0, 1, 2, 3, 4] * surround('(', ')', 'foo') // '(foo)' */ export default curry(surround)
///////////////////////////////////////////////////////////////////// // Copyright (c) Autodesk, Inc. All rights reserved // Written by Forge Partner Development // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. ///////////////////////////////////////////////////////////////////// 'use strict'; // http://www.w3schools.com/js/js_strict.asp // token handling in session var Credentials = require('./../../credentials'); // forge config information, such as client ID and secret var config = require('./../../config'); // entity type encoder var Encoder = require('node-html-encoder').Encoder; var encoder = new Encoder('entity'); // web framework var express = require('express'); var router = express.Router(); var Dropbox = require('dropbox'); function respondWithError(res, error) { if (error.statusCode) { res.status(error.statusCode).end(error.statusMessage) } else { res.status(500).end(error.message) } } router.get('/api/storage/tree', function (req, res) { var token = new Credentials(req.session); var credentials = token.getStorageCredentials(); if (credentials === undefined) { res.status(401).end(); return; } var id = decodeURIComponent(req.query.id); // item id's look like this: // <drive id>!<file id> // e.g. BF0BDCFE22A2EFD6!161 var driveId = id.split('!')[0]; var path = ''; try { if (id === '#') { path = '' } else { path = encoder.htmlDecode(id); } var dbx = new Dropbox({ accessToken: credentials.access_token }) dbx.filesListFolder({path: path}) .then(function (data) { var treeList = []; for (var key in data.entries) { var item = data.entries[key] var treeItem = { id: encoder.htmlEncode(item.path_display), text: encoder.htmlEncode(item.name), type: item['.tag'] === 'folder' ? 'folders' : 'items', children: item['.tag'] === 'folder' ? true : false // !! turns an object into boolean } treeList.push(treeItem) } res.json(treeList) }) .catch(function (error) { console.log(error) respondWithError(res, error) return }) } catch (err) { respondWithError(res, err) } }); module.exports = router;
// Generated by CoffeeScript 1.7.1 (function() { var Slack, request, _; request = require('request'); _ = require('lodash'); Slack = (function() { function Slack(team, token, options) { this.team = team; this.token = token; this.options = options; this.incomingUrl = "https://" + team + ".slack.com/services/hooks/incoming-webhook?token=" + token; this.validateArguments(); } Slack.prototype.validateArguments = function() { if (this.team == null) { throw new Error("Team name required"); } if (this.token == null) { throw new Error("Token required"); } }; Slack.prototype.notify = function(message, callback) { var chn, count, options, total, _i, _len, _ref, _results; if ((message == null) || (_.isObject(message && ((message != null ? message.text : void 0) == null)))) { throw new Error('Message required'); } options = {}; options.text = typeof message === 'string' ? message : message.text; options.channel = message.channel == null ? '#general' : message.channel; options = _.extend(options, this.options); options = _.extend(options, message); if (_.isArray(options.channel)) { total = options.channel.length; count = 0; _ref = options.channel; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { chn = _ref[_i]; options.channel = chn; _results.push(request.post(this.incomingUrl, { body: JSON.stringify(options) }, function(err, resp, body) { count++; if ((callback != null) && count === total) { if (body === 'ok') { return callback(null, body); } else { return callback(err || body); } } })); } return _results; } else { return request.post(this.incomingUrl, { body: JSON.stringify(options) }, function(err, resp, body) { if (callback != null) { if (body === 'ok') { return callback(null, body); } else { return callback(err || body); } } }); } }; return Slack; })(); module.exports = Slack; }).call(this);
export default [ { type: 'audio', id: 'ambient-sound', url: 'assets/sounds/ambient.mp3', options: { loop: true, volume: 1 } }, { type: 'model', id: 'polar-bear', url: 'assets/models/polar-bear.awd' }, { type: 'image', id: 'panda', url: 'assets/images/panda.jpg' } ]
// ONLY USE ON CI BECAUSE IT MESSES UP `authorized_keys` var SSH = require('../'); describe('ssh-kit', function() { beforeEach(function() { this.ssh = new SSH(); }); it('connects to ssh', function(done) { this.ssh.set('host', 'localhost'); this.ssh.set('quiet', true); this.setKey(this.ssh); this.ssh.exec('ls'); this.ssh.on('finish', done); }); });
import { LitElement } from 'lit-element'; import { render } from 'github-buttons'; import config from '../config/app'; export default class GithubButton extends LitElement { static cName = 'github-button'; static properties = { href: { type: String }, size: { type: String }, theme: { type: String }, showCount: { type: Boolean }, text: { type: String } }; constructor() { super(); this.href = config.repoURL; this.size = undefined; this.theme = 'light'; this.showCount = true; this.text = undefined; } _collectOptions() { return { href: this.href, 'data-size': this.size, 'data-color-scheme': this.theme, 'data-show-count': this.showCount, 'data-text': this.text }; } update() { render(this._collectOptions(), (el) => { if (this.shadowRoot.firstChild) { this.shadowRoot.replaceChild(el, this.shadowRoot.firstChild); } else { this.shadowRoot.appendChild(el); } }); } }
export default { SHOW_BUTTONS: 'SHOW_BUTTONS' }
require.config( { paths: { jsYaml: BASE_URL + "webjars/js-yaml/3.14.0/dist", ace: BASE_URL + "webjars/ace-builds/1.4.11/src", browser: "../../app-browser/modules", projects: "../../app-browser/modules/projects", editor: "../../editor/modules" }, } ) ; require( [ "browser/projects/env-editor/cluster-edit", "editor/json-forms", "browser/utils" ], function ( clusterEditDialog, jsonForms, utils ) { console.log( "\n\n ************** _main: loaded *** \n\n" ) ; // Shared variables need to be visible prior to scope $( document ).ready( function () { initialize() ; } ) ; function initialize() { CsapCommon.configureCsapAlertify() ; jsonForms.setUtils( utils ) ; $( '#showButton' ).click( function () { // alertify.notify("Getting clusters") ; // $( ".releasePackage" ).val(), $( ".lifeSelection" ).val(),$( "#dialogClusterSelect" ).val() var params = { releasePackage: $( ".releasePackage" ).val(), lifeEdit: $( ".lifeSelection" ).val(), clusterName: $( "#dialogClusterSelect" ).val() } $.get( clusterEditUrl, params, clusterEditDialog.show, 'html' ) ; return false ; } ) ; // for testing page without launching dialog let _activeProjectFunction = function () { return $( "select.releasePackage" ).val() ; } ; let refreshFunction = null ; let _launchMenuFunction = null ; utils.initialize( refreshFunction, _launchMenuFunction, _activeProjectFunction ) ; clusterEditDialog.configureForTest() ; } } ) ;
module.exports = function(config) { config.set({ frameworks: ['jasmine', 'browserify'], files: [ 'src/redux-nest.js', 'tests/*.js' ], preprocessors: { 'src/redux-nest.js': ['browserify'], 'tests/*.js': ['browserify'] }, reporters: ['spec'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: false, browsers: ['Firefox'], singleRun: false, browserify: { debug: true, transform: [['babelify', { stage: 0 }]] } }); };
(function (app) { var dataEvent = app('data-event'); var collExpense = app('coll-expense'); var collPeriod = app('coll-period'); var logger = app('logger')('ui-month-coins-counts'); var tp = app('time-processor'); var broadcast = app('broadcast'); var pouchProcEvs = broadcast.events('pouch-processor'); var UiListClass = app('bb-co')('ui-month-coins', { tpl: 'scripts/ui-controllers/components-custom/ui-controls/containers/month-coins/ui-month-coins', init: function () { this.defineScope({ today: '', current: '', prev: '', currentPeriod: '', prevPeriod: '' }); updateSummary.call(this); bindDataChanges.call(this); }, destroy: function () { UiListClass._parent.destroy.apply(this, arguments); var blockActions = collExpense.getBlockActions(); dataEvent.offBlock(blockActions.PUSH, this._dbExpense); dataEvent.offBlock(blockActions.REMOVE, this._dbExpenseDrop); dataEvent.offBlock(blockActions.UPDATE, this._dbExpenseUpdate); broadcast.off(pouchProcEvs.onChanged, this._onPouch); } }); function getCountByPeriod(name, from, to) { var scope = this.getScope(); logger.log(name, new Date(from), new Date(to)); collExpense.getCountByPeriod(from, to) .then(function (data) { scope[name] = data[0].summary; logger.log('----------',data); }); } function updateSummary() { var scope = this.getScope(); var nowDayBegin = tp.getDayStart(); var nowDayEnd = tp.getDayEnd(); var currPeriod = collPeriod.getCurrPeriod(nowDayBegin); var prevPeriod = collPeriod.getPeriodPrev(nowDayBegin); scope.currentPeriod = currPeriod.title; scope.prevPeriod = prevPeriod.title; getCountByPeriod.call(this, 'today', nowDayBegin, nowDayEnd); // getCountByPeriod.call(this, 'current', currPeriod.dateBegin, currPeriod.dateEnd); // getCountByPeriod.call(this, 'prev', prevPeriod.dateBegin, prevPeriod.dateEnd); } function bindDataChanges() { var self = this; broadcast.on(pouchProcEvs.onChanged, this._onPouch = function () { updateSummary.call(self); }); var blockActions = collExpense.getBlockActions(); dataEvent.onBlock(blockActions.REMOVE, this._dbExpenseDrop = function (removedId) { updateSummary.call(self); logger.log('dataEvent.onBlock(REMOVE)', removedId); }); dataEvent.onBlock(blockActions.PUSH, this._dbExpensePush = function (item) { updateSummary.call(self); logger.log('dataEvent.onBlock(PUSH)', item); }); dataEvent.onBlock(blockActions.UPDATE, this._dbExpenseUpdate = function (data) { updateSummary.call(self); logger.log('dataEvent.onBlock(UPDATE)', data); }); } })(window.app);
// @flow import Icon from '@conveyal/woonerf/components/icon' import * as React from 'react' import {MenuItem as BsMenuItem} from 'react-bootstrap' /** * Simple wrapper around Bootstrap's menu item to inject a checkmark if the item * is selected. */ const MenuItem = ({children, selected, ...menuItemProps}: {children?: React.Node, selected?: boolean}) => ( <BsMenuItem {...menuItemProps}> {selected ? <Icon style={{ left: '2px', marginTop: '3px', position: 'absolute' }} type='check' /> : null } {children} </BsMenuItem> ) export default MenuItem
var xhr = new XMLHttpRequest(); // config request // xhr.open('GET', 'https://api.vk.com/method/user.get?user_ids=198047774&fields=photo', false); // otherID 949 888 27 // otherID 9125068 // send request // xhr.send(); /* if (xhr.status != 200) { console.log('xhr status: ' + xhr.status); console.log('xhr statusTXT: ' + xhr.statusText); } else { console.log('Response: ' + xhr.responseText); }; */ /* function show() { $.ajax({ url: "https://api.vk.com/method/users.get?user_ids=91", jsonp: "callback", dataType: "jsonp", success: function(response) { var firstPerson = response.response[0]; draw(firstPerson); console.log(firstPerson.first_name); } }); }; */ /* function draw(firstPerson) { var div = document.createElement('div'); console.log(firstPeson.firs_name); }; */ var res = [{"response":[{"uid": 9125068, "first_name": "Gergen", last_name: "Abagyan", "photo": "htttp:/blabla.com/photo.jpg"}]}, {"response":[{"uid": 9125070, "first_name": "Oleh", last_name: "Abagyan", "photo": "htttp:/blabla.com/photo.jpg"}]}, {"response":[{"uid": 9125067, "first_name": "Nataliia", last_name: "Abagyan", "photo": "htttp:/blabla.com/photo.jpg"}]}, {"response":[{"uid": 9125069, "first_name": "Vania", last_name: "Abagyan", "photo": "htttp:/blabla.com/photo.jpg"}]}]; function show() { var input = document.getElementById('vkId').value; for (i = 0; i < res.length; i++) { var uid = res[i].response[0].uid; var fullName = res[i].response[0].first_name + ' ' + res[i].response[0].last_name; if (input == uid) { var div = document.createElement('div'); var img = document.createElement('img'); var text = document.createTextNode(fullName); div.appendChild(text); document.body.appendChild(div); }; }; };
$( document ).ready(function() { $("#submitLogin").bind('click', function() { login(document.getElementById('username').value, document.getElementById('password').value)}) $("#sendemail").on('click', function() { send(document.getElementById('email').value)}); }); $('.modal-trigger').leanModal({ dismissible: true, // Modal can be dismissed by clicking outside of the modal opacity: .5, // Opacity of modal background in_duration: 300, // Transition in duration out_duration: 200 // Transition out duration } ); Parse.initialize("T4lD84ZeLY7615h43jpGlVTG5cXZyXd8ceSGX29e", "KPVDbWy1zWbJD1WPG4HReba5urgHsPVJgh9wX5D1"); var val = sessionStorage.user; //alert(user); function login(username, password) { Parse.User.logIn(username, password, { success: function(user) { window.location="main.html"; }, error: function(user, error) { Materialize.toast("Username or password incorrect, please try again", 4000) // 4000 is the duration of the toast } }); } function send(email){ Parse.User.requestPasswordReset(email , { success: function () { Materialize.toast("Reset instructions emailed to you."); }, error: function (error) { Materialize.toast("Error: " + error.message, 4000) } }); }
const Util = { myAlert: function(text, time) { if(!document.getElementById('alertBg')) { let _time = time || 1000; let parent = document.createElement('div'); parent.setAttribute('id', 'alertBg'); let child = document.createElement('p'); child.setAttribute('class', 'text'); let _text = document.createTextNode(text); child.appendChild(_text); parent.appendChild(child); document.body.appendChild(parent); setTimeout(() => { document.body.removeChild(parent); }, _time) }; }, trim: function(str) { //删除左右两端的空格 return str.replace(/(^\s*)|(\s*$)/g, ""); }, getSearch: function() { var args = {}; var query = location.search.substring(1); //获取查询串 var len = query.replace(/(^\s*)|(\s*$)/g, "").length; if(len < 1) { return args; }; var pairs = query.split("&"); //在逗号处断开 for(var i = 0; i < pairs.length; i++) { var pos = pairs[i].indexOf('='); //查找name=value if(pos > 0) { var argname = pairs[i].substring(0, pos); //提取name var value = pairs[i].substring(pos + 1); //提取value args[argname] = decodeURI(value); //存为属性 } else { args[pairs[i]] = ''; } }; return args; }, goSearch: function(url,obj){ let toGo = url; for( let i in obj){ if(toGo.indexOf('?') > 0){ toGo += ('&' + i + '=' + obj[i]) }else{ toGo += ('?' + i + '=' + obj[i]) } }; window.location.href = toGo; }, time: function(){//控制提示框停留时间 return 2000 }, setItem : function(name, content){ if (!name) return; if (typeof content !== 'string') { content = JSON.stringify(content); }; window.localStorage.setItem(name, content); }, getItem : function(name){ if (!name) return; return JSON.parse(window.localStorage.getItem(name)); }, removeItem : function(name){ if (!name) return; window.localStorage.removeItem(name); }, dateTime(num,type){ let str = num; if(num){ let _num = new Date(num); let dateStr = _num.getFullYear() + '-' + this.addZero(_num.getMonth() + 1) + '-' + this.addZero(_num.getDate()); let timeStr = this.addZero(_num.getHours()) + ':' + this.addZero(_num.getMinutes()) + ':' + this.addZero(_num.getSeconds()); if(type === 'date' ){ str = dateStr; }else if(type === 'time'){ str = timeStr; }else{ str = dateStr+ ' ' + timeStr; } }; return str; }, addZero(num) { if(num < 10) { return '0' + num; } return num; }, } export { Util }
import Vue from 'vue' import VueRouter from 'vue-router' import routes from '../routes' import VueProgressBar from 'vue-progressbar' Vue.use(VueProgressBar, { color: 'rgb(143, 255, 199)', // failedColor: 'red', height: '3px' }) Vue.use(VueRouter) const router = new VueRouter({ routes, mode: 'history', linkActiveClass: 'active', scrollBehavior(to, from, savedPosition) { return savedPosition || {x: 0, y: 0} } }); const setTitle = (title) => { router.app.$store.commit('setMetaTitle', title); document.title = title + ' - ' + window.Admin.Title; } // route before router.beforeEach((to, from, next) => { // console.log('to', to); // console.log(from); // console.log(window.Admin); if (to.meta.title) { setTitle(to.meta.title); } if (to.fullPath != '/#') { router.app.$Progress.start(); if (to.name != 'admin.login' && Object.keys(router.app.$store.state.user).length == 0) { return next({name: 'admin.login'}); } /*if (typeof to.name == 'undefined' || to.name == '') { return next({name: 'admin.403'}); }*/ if (['admin.404', 'admin.403', 'admin.500'].indexOf(to.name) > -1) { router.app.$Progress.fail(); } next(); } }); // route after router.afterEach(route => { router.app.$Progress.finish(); }); export default router;
import React, { Component } from 'react'; import { connect } from 'react-redux'; import apiClient from '../api/apiClient'; import CONSTANTS from '../shared/constants'; class CreditCards extends Component { constructor() { super(); this.state = { username: "username" }; } componentWillMount() { apiClient.callCreditCardsApi(CONSTANTS.HTTP_METHODS.GET, '/users/profile', (response) => { this.setState({ username: response.data.user.firstName }); }); } render() { return ( <h1>Hello {this.state.username}. This is the credit cards page</h1> ); } } const mapStateToProps = (state) => { return { sessionId: state.session.sessionId }; }; export default connect(mapStateToProps)(CreditCards);
'use babel' /* @flow */ export type Ucompiler$Plugins = { preprocessors: Array<UCompiler$Plugin>, compilers: Array<UCompiler$Plugin>, general: Array<UCompiler$Plugin>, minifiers: Array<UCompiler$Plugin> } export type UCompiler$Plugin = { name: string, compiler: ?boolean, minifier: ?boolean, preprocessor: ?boolean, process: ((contents:string, parameters: UCompiler$Job) => ?UCompiler$Plugin$Result) } export type UCompiler$Plugin$Result = { contents: string, sourceMap?: ?UCompiler$SourceMap } export type UCompiler$SourceMap = { sources: Array<string>, sourcesContent: Array<string>, mappings: string, names: Array<string> } export type UCompiler$Job = { rootDirectory: string, filePath: string, state: Object, config: Object } export type Ucompiler$Config = { defaultRule: string, rules: Array<Ucompiler$Config$Rule> } export type Ucompiler$Config$Rule = { name: string, plugins: Array<string>, include: Array<{ directory: string, deep?: boolean, extensions: Array<string> }>, exclude?: Array<string>, outputPath: string, sourceMapPath?: string } export type Ucompiler$Compile$Results = { status: boolean, contents: Array<{ path: string, contents: string }>, sourceMaps: Array<{ path: string, contents: ?string }>, state: Array<{ path: string, state: Object }> } export type Ucompiler$Compile$Result = { filePath: string, contents: string, sourceMap: ?string, state: Object } export type UCompiler$ErrorCallback = ((error: Error) => void) export type UCompiler$Options = { save: boolean, saveIncludedFiles: boolean, errorCallback: UCompiler$ErrorCallback }
import React, { Component } from 'react'; import GoogleAdv from '../../GoogleAdv' import BaseConfig from '../../../BaseConfig'; import OfferWow from '../../OfferWow' import { Tag } from 'antd' import classes from './HomeContentRightAdv.scss' export default class HomeContentRightAdv extends Component { constructor(props){ super(props); this._lu = this._lu.bind(this); this.state = { showLu : false } } // @type Number(1,2,3) => (super,Clix,Ptcw) _lu(type){ this.setState({ showLu : !this.state.showLu, type:type }); } componentWillUnmount() { } showGoogleAdv (){ const advProps = { style : {display:"inline-block",width:"300px",height:"250px"}, client : 'ca-pub-5722932343401905', slot : '9366759071', // advBoxStyle : { paddingTop:"25px", textAlign : "center"} } return ( <GoogleAdv {...advProps} /> ) } render() { const { client , slot , style , advBoxStyle ,user } = this.props; return ( <div> { this.state.showLu ? <OfferWow user={user} config={BaseConfig} lu={this._lu} type={this.state.type} /> : null } { BaseConfig.show_google_adv ? this.showGoogleAdv() :null } { BaseConfig.show_moon_adv ? <div className={classes.buttonWrap}> <div> <span color="blue" onClick={ ()=>this._lu(1)} >SuperReward</span> </div> <div> <span color="blue" onClick={ ()=>this._lu(2)} >PTCWALL</span> </div> <div> <span color="blue" onClick={ ()=>this._lu(3)} >ClixWall</span> </div> </div> :null } </div> ); } }
/*! * Tiny Carousel 1.9 * http://www.baijs.nl/tinycarousel * * Copyright 2010, Maarten Baijs * Dual licensed under the MIT or GPL Version 2 licenses. * http://www.opensource.org/licenses/mit-license.php * http://www.opensource.org/licenses/gpl-2.0.php * * Date: 01 / 06 / 2011 * Depends on library: jQuery */ (function($){ $.tiny = $.tiny || { }; $.tiny.carousel = { options: { start: 1, // where should the carousel start? display: 1, // how many blocks do you want to move at 1 time? axis: 'x', // vertical or horizontal scroller? ( x || y ). controls: true, // show left and right navigation buttons. pager: false, // is there a page number navigation present? interval: false, // move to another block on intervals. intervaltime: 3000, // interval time in milliseconds. rewind: false, // If interval is true and rewind is true it will play in reverse if the last slide is reached. animation: true, // false is instant, true is animate. duration: 1000, // how fast must the animation move in ms? callback: null // function that executes after every move. } }; $.fn.tinycarousel = function(options) { var options = $.extend({}, $.tiny.carousel.options, options); this.each(function(){ $(this).data('tcl', new Carousel($(this), options)); }); return this; }; $.fn.tinycarousel_start = function(){ $(this).data('tcl').start(); }; $.fn.tinycarousel_stop = function(){ $(this).data('tcl').stop(); }; $.fn.tinycarousel_move = function(iNum){ $(this).data('tcl').move(iNum-1,true); }; function Carousel(root, options){ var oSelf = this; var oViewport = $('.viewport:first', root); var oContent = $('.overview:first', root); var oPages = oContent.children(); var oBtnNext = $('.next:first', root); var oBtnPrev = $('.prev:first', root); var oPager = $('.pager:first', root); var iPageSize, iSteps, iCurrent, oTimer, bPause, bForward = true, bAxis = options.axis == 'x'; function initialize(){ iPageSize = bAxis ? $(oPages[0]).outerWidth(true) : $(oPages[0]).outerHeight(true); var iLeftover = Math.ceil(((bAxis ? oViewport.outerWidth() : oViewport.outerHeight()) / (iPageSize * options.display)) -1); iSteps = Math.max(1, Math.ceil(oPages.length / options.display) - iLeftover); iCurrent = Math.min(iSteps, Math.max(1, options.start)) -2; oContent.css(bAxis ? 'width' : 'height', (iPageSize * oPages.length)); oSelf.move(1); setEvents(); return oSelf; }; function setEvents(){ if(options.controls && oBtnPrev.length > 0 && oBtnNext.length > 0){ oBtnPrev.click(function(){oSelf.move(-1); return false;}); oBtnNext.click(function(){oSelf.move( 1); return false;}); } if(options.interval){ root.hover(oSelf.stop,oSelf.start); } if(options.pager && oPager.length > 0){ $('a',oPager).click(setPager); } }; function setButtons(){ if(options.controls){ oBtnPrev.toggleClass('disable', !(iCurrent > 0)); oBtnNext.toggleClass('disable', !(iCurrent +1 < iSteps)); } if(options.pager){ var oNumbers = $('.pagenum', oPager); oNumbers.removeClass('active'); $(oNumbers[iCurrent]).addClass('active'); } }; function setPager(oEvent){ if($(this).hasClass('pagenum')){ oSelf.move(parseInt(this.rel), true); } return false; }; function setTimer(){ if(options.interval && !bPause){ clearTimeout(oTimer); oTimer = setTimeout(function(){ iCurrent = iCurrent +1 == iSteps ? -1 : iCurrent; bForward = iCurrent +1 == iSteps ? false : iCurrent == 0 ? true : bForward; oSelf.move(bForward ? 1 : -1); }, options.intervaltime); } }; this.stop = function(){ clearTimeout(oTimer); bPause = true; }; this.start = function(){ bPause = false; setTimer(); }; this.move = function(iDirection, bPublic){ iCurrent = bPublic ? iDirection : iCurrent += iDirection; if(iCurrent < 0) iCurrent = iSteps - 1; if(iCurrent >= iSteps) iCurrent = 0; var oPosition = {}; oPosition[bAxis ? 'left' : 'top'] = -(iCurrent * (iPageSize * options.display)); oContent.animate(oPosition,{ queue: false, duration: options.animation ? options.duration : 0, complete: function(){ if(typeof options.callback == 'function') options.callback.call(this, oPages[iCurrent], iCurrent); } }); setButtons(); setTimer(); }; return initialize(); }; })(jQuery);
(function($){ asyncTest( "Opening a second popup causes the first one to close", function() { var initialHRef = location.href; expect( 5 ); $.testHelper.detailedEventCascade([ function() { $( "#test-popup" ).popup( "open" ); }, { opened: { src: $( "#test-popup" ), event: "opened.openAnotherStep1" }, hashchange: { src: $( window ), event: "hashchange.openAnotherStep1" } }, function() { $( "#test-popup-2" ).popup( "open" ); }, { hashchange: { src: $( window ), event: "hashchange.openAnotherStep2" }, closed: { src: $( "#test-popup" ), event: "closed.openAnotherStep2" }, opened: { src: $( "#test-popup-2" ), event: "opened.openAnotherStep2" } }, function( result ) { ok( result.closed.idx < result.opened.idx && result.closed.idx !== -1, "'closed' signal arrived before 'opened' signal" ); ok( result.hashchange.timedOut, "There were no hashchange events" ); $( "#test-popup-2" ).popup( "close" ); }, { closed: { src: $( "#test-popup-2" ), event: "closed.openAnotherStep3" }, hashchange: { src: $( window ), event: "hashchange.openAnotherStep3" } }, function( result ) { ok( !result.closed.timedOut, "'closed' signal was received" ); ok( !result.hashchange.timedOut, "'hashchange' signal was received" ); ok( initialHRef === location.href, "location is unchanged" ); start(); } ]); }); })( jQuery );
/* jshint node: true */ module.exports = function (environment) { var ENV = { modulePrefix: 'share-drop', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created }, FIREBASE_URL: process.env.FIREBASE_URL, sassOptions: { inputFile: 'app.sass', outputFile: 'share-drop.css' } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { ENV.googleAnalytics = { webPropertyId: 'UA-41889586-2' }; } ENV.exportApplicationGlobal = true; return ENV; };
var gulp = require('gulp'); var browserSync = require('browser-sync'); var sass = require('gulp-sass'); var prefix = require('gulp-autoprefixer'); var cp = require('child_process'); var gutil = require('gulp-util'); var jekyll = process.platform === 'win32' ? 'jekyll.bat' : 'jekyll'; var messages = { jekyllBuild: '<span style="color: grey">Running:</span> $ jekyll build' }; /** * Build the Jekyll Site */ gulp.task('jekyll-build', function (done) { var options = ['build']; options.push(gutil.env.drafts === true ? '--drafts' : null); browserSync.notify(messages.jekyllBuild); return cp.spawn( jekyll , options, {stdio: 'inherit'}) .on('close', done); }); /** * Rebuild Jekyll & do page reload */ gulp.task('jekyll-rebuild', ['jekyll-build'], function () { browserSync.reload(); }); /** * Wait for jekyll-build, then launch the Server */ gulp.task('browser-sync', ['sass', 'jekyll-build'], function() { browserSync({ server: { baseDir: '_site' } }); }); /** * Compile files from _scss into both _site/css (for live injecting) and site (for future jekyll builds) */ gulp.task('sass', function () { return gulp.src('_scss/*.scss') .pipe(sass({ outputStyle: 'expanded', // sourceComments: 'map', includePaths: ['scss'], onError: browserSync.notify('Error in sass') })) .on('error', sass.logError) .pipe(prefix(['last 15 versions', '> 1%', 'ie 8', 'ie 7'], { cascade: true })) .pipe(gulp.dest('_site/css')) .pipe(browserSync.reload({stream:true})) .pipe(gulp.dest('css')); }); /** * Watch scss files for changes & recompile * Watch html/md files, run jekyll & reload BrowserSync */ gulp.task('watch', function () { gulp.watch(['_scss/*.scss', '_scss/*/*.scss'], ['sass']); var folders = ['*.html', '_includes/*.html', '_includes/*/*.html', '_layouts/*.html', '_layouts/*/*.html', '_posts/*', 'js/*.js', 'images/*']; if (gutil.env.drafts === true) { folders.push('_drafts/*'); } gulp.watch(folders, ['jekyll-rebuild']); }); /** * Default task, running just `gulp` will compile the sass, * compile the jekyll site, launch BrowserSync & watch files. */ gulp.task('default', ['browser-sync', 'watch']);
(function(){ 'use strict'; // Prepare the 'calender' module for subsequent registration of controllers and delegates angular.module('calender', [ 'ngMaterial' ]); })();
'use strict'; describe('Controller: MainCtrl', function () { // load the controller's module beforeEach(module('wurstApp')); var MainCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); MainCtrl = $controller('MainCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function () { expect(scope.awesomeThings.length).toBe(3); }); });
/* * Original code from https://github.com/itay/node-cover licensed under MIT did * not have a Copyright message in the file. * * Changes for the chain coverage instrumentation Copyright (C) 2014, 2015 Dylan Barrell * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ var esprima = require('./esprima'); var escodegen = require('./escodegen'); var EventEmitter = require('events').EventEmitter; esprima.Syntax = { AssignmentExpression: 'AssignmentExpression', ArrayExpression: 'ArrayExpression', BlockStatement: 'BlockStatement', BinaryExpression: 'BinaryExpression', BreakStatement: 'BreakStatement', CallExpression: 'CallExpression', CatchClause: 'CatchClause', ConditionalExpression: 'ConditionalExpression', ContinueStatement: 'ContinueStatement', DoWhileStatement: 'DoWhileStatement', DebuggerStatement: 'DebuggerStatement', EmptyStatement: 'EmptyStatement', ExpressionStatement: 'ExpressionStatement', ForStatement: 'ForStatement', ForInStatement: 'ForInStatement', FunctionDeclaration: 'FunctionDeclaration', FunctionExpression: 'FunctionExpression', Identifier: 'Identifier', IfStatement: 'IfStatement', Literal: 'Literal', LabeledStatement: 'LabeledStatement', LogicalExpression: 'LogicalExpression', MemberExpression: 'MemberExpression', NewExpression: 'NewExpression', ObjectExpression: 'ObjectExpression', Program: 'Program', Property: 'Property', ReturnStatement: 'ReturnStatement', SequenceExpression: 'SequenceExpression', SwitchStatement: 'SwitchStatement', SwitchCase: 'SwitchCase', ThisExpression: 'ThisExpression', ThrowStatement: 'ThrowStatement', TryStatement: 'TryStatement', UnaryExpression: 'UnaryExpression', UpdateExpression: 'UpdateExpression', VariableDeclaration: 'VariableDeclaration', VariableDeclarator: 'VariableDeclarator', WhileStatement: 'WhileStatement', WithStatement: 'WithStatement' }; module.exports = function(src) { var instrumentor = new Instrumentor(src); return instrumentor; }; function Instrumentor(src) { // Setup our names this.names = { statement: this.generateName(6, "__statement_"), expression: this.generateName(6, "__expression_"), block: this.generateName(6, "__block_"), intro: this.generateName(6, "__intro_"), extro: this.generateName(6, "__extro_") }; // Setup the node store this.nodes = {}; // Setup the counters this.blockCounter = 0; this.nodeCounter = 0; if (src) { this.instrumentedSource = this.instrument(src); } }; Instrumentor.prototype = new EventEmitter; Instrumentor.prototype.objectify = function() { var obj = {}; obj.blockCounter = this.blockCounter; obj.nodeCounter = this.nodeCounter; obj.source = this.source; obj.nodes = {}; for(var key in this.nodes) { if (this.nodes.hasOwnProperty(key)) { var node = this.nodes[key]; obj.nodes[key] = { loc: node.loc, id: node.id }; } } return obj; } Instrumentor.prototype.filter = function(action) { action = action || function() {}; var filtered = []; for(var key in this.nodes) { if (this.nodes.hasOwnProperty(key)) { var node = this.nodes[key]; if (action(node)) { filtered.push(node); } } } return filtered; }; Instrumentor.prototype.instrument = function(code) { this.source = code; // Parse the code var tree = esprima.parse(code, {range: true, loc: true, comment: true}); //console.log(JSON.stringify(tree, null, " ")); var ignoredLines = {}; var ignoreRe = /^\s*cover\s*:\s*false\s*$/; var ignoreBeginJSCRe = /^\s*#JSCOVERAGE_IF\s*$/; var ignoreEndJSCRe = /^\s*(#JSCOVERAGE_IF\s*0)|(#JSCOVERAGE_ENDIF)\s*$/; var begin, end, i, j; // Handle our ignore comment format tree.comments. filter(function(commentNode) { return ignoreRe.test(commentNode.value); }). forEach(function(commentNode) { ignoredLines[commentNode.loc.start.line] = true; }); // Handle the JSCoverage ignore comment format var state = "end"; var JSCComments = tree.comments.filter(function(commentNode) { return ignoreBeginJSCRe.test(commentNode.value) || ignoreEndJSCRe.test(commentNode.value); }).map(function(commentNode) { if (ignoreBeginJSCRe.test(commentNode.value)) { return { type: "begin", node: commentNode }; } else { return { type: "end", node: commentNode }; } }).filter(function(item) { if (state === "end" && item.type === "begin") { state = "begin"; return true; } else if (state === "begin" && item.type === "end") { state = "end"; return true; } return false; }); if (JSCComments.length && JSCComments[JSCComments.length - 1].type !== "end") { // The file ends with an open ignore. Need to estimate the file length // and add a synthetic node to the end of the array JSCComments.push({ type: "end", node: { loc: { start: { line: code.split('\n').length } } } }); } for (i = 0; i < JSCComments.length; i += 2) { begin = JSCComments[i].node.loc.start.line; end = JSCComments[i + 1].node.loc.start.line; for (j = begin; j <= end; j++) { ignoredLines[j] = true; } } this.wrap(tree, ignoredLines); // We need to adjust the nodes for everything on the first line, // such that their location statements will start at 1 and not at header.length for(var nodeKey in this.nodes) { if (this.nodes.hasOwnProperty(nodeKey)) { var node = this.nodes[nodeKey]; if (node.loc.start.line === 1 || node.loc.end.line === 1) { // Copy over the location data, as these are shared across // nodes. We only do it for things on the first line node.loc = { start: { line: node.loc.start.line, column: node.loc.start.column }, end: { line: node.loc.end.line, column: node.loc.end.column } } // Adjust the columns if (node.loc.start.line == 1) { node.loc.start.column = node.loc.start.column; } if (node.loc.end.line == 1) { node.loc.end.column = node.loc.end.column; } } } } return escodegen.generate(tree); }; Instrumentor.prototype.addToContext = function(context) { context = context || {}; var that = this; context[that.names.expression] = function (i) { var node = that.nodes[i]; that.emit('node', node); return function (expr) { return expr; }; }; context[that.names.statement] = function (i) { var node = that.nodes[i]; that.emit('node', node); }; context[that.names.block] = function (i) { that.emit('block', i); }; return context; }; Instrumentor.prototype.generateName = function (len, prefix) { var name = ''; var lower = '$'.charCodeAt(0); var upper = 'z'.charCodeAt(0); while (name.length < len) { var c = String.fromCharCode(Math.floor( Math.random() * (upper - lower + 1) + lower )); if ((name + c).match(/^[A-Za-z_$][A-Za-z0-9_$]*$/)) name += c; } return prefix + name; }; Instrumentor.prototype.traverseAndWrap = function(object, visitor, master) { var key, child, parent, path; parent = (typeof master === 'undefined') ? [] : master; var returned = visitor.call(null, object, parent); if (returned === false) { return; } for (key in object) { if (object.hasOwnProperty(key)) { child = object[key]; path = [ object ]; path.push(parent); var newNode; if (typeof child === 'object' && child !== null && !object.noCover) { newNode = this.traverseAndWrap(child, visitor, path); } if (newNode) { object[key] = newNode; newNode = null; } } } return object.noCover ? undefined : returned; }; Instrumentor.prototype.wrap = function(tree, ignoredLines) { var that = this; this.traverseAndWrap(tree, function(node, path) { if (node.noCover) { return; } if (node.loc && node.loc.start.line in ignoredLines) { return false; } parent = path[0]; switch(node.type) { case esprima.Syntax.ExpressionStatement: case esprima.Syntax.ThrowStatement: case esprima.Syntax.VariableDeclaration: { if (parent && ( (parent.type === esprima.Syntax.ForInStatement) || (parent.type === esprima.Syntax.ForStatement) )) { return; } var newNode = { "type": "BlockStatement", "body": [ { "type": "ExpressionStatement", "expression": { "type": "CallExpression", "callee": { "type": "Identifier", "name": that.names.statement }, "arguments": [ { "type": "Literal", "value": that.nodeCounter++ } ] } }, node ] } that.nodes[that.nodeCounter - 1] = node; node.id = that.nodeCounter - 1; return newNode; } case esprima.Syntax.ReturnStatement: { var newNode = { "type": "SequenceExpression", "expressions": [ { "type": "CallExpression", "callee": { "type": "Identifier", "name": that.names.expression }, "arguments": [ { "type": "Identifier", "name": that.nodeCounter++ } ], noCover: true } ], } if (node.argument) { newNode.expressions.push(node.argument); } that.nodes[that.nodeCounter - 1] = node; node.id = that.nodeCounter - 1; node.argument = newNode break; } case esprima.Syntax.ConditionalExpression: { var newConsequentNode = { "type": "SequenceExpression", "expressions": [ { "type": "CallExpression", "callee": { "type": "Identifier", "name": that.names.expression }, "arguments": [ { "type": "Identifier", "name": that.nodeCounter++ } ], noCover: true }, node.consequent ], } that.nodes[that.nodeCounter - 1] = node.consequent; node.consequent.id = that.nodeCounter - 1 var newAlternateNode = { "type": "SequenceExpression", "expressions": [ { "type": "CallExpression", "callee": { "type": "Identifier", "name": that.names.expression }, "arguments": [ { "type": "Identifier", "name": that.nodeCounter++ } ], noCover: true }, node.alternate ], } that.nodes[that.nodeCounter - 1] = node.alternate; node.alternate.id = that.nodeCounter - 1 node.consequent = newConsequentNode; node.alternate = newAlternateNode; break; } case esprima.Syntax.CallExpression: if (node.callee.type === 'MemberExpression') { var newNode = { "type": "CallExpression", "callee": { "type": "Identifier", "name": that.names.extro }, "arguments": [ { "type": "Identifier", "name": that.nodeCounter }, node ] }, intro = { "type": "CallExpression", "seen": true, "callee": { "type": "Identifier", "name": that.names.intro }, "arguments":[{ "type": "Identifier", "name": that.nodeCounter++ }, node.callee.object ] }; node.callee.object = intro; that.nodes[that.nodeCounter - 1] = node; node.id = that.nodeCounter - 1; } else if (!node.seen) { var newNode = { "type": "SequenceExpression", "expressions": [ { "type": "CallExpression", "callee": { "type": "Identifier", "name": that.names.expression }, "arguments": [ { "type": "Identifier", "name": that.nodeCounter++ } ] }, node ] } that.nodes[that.nodeCounter - 1] = node; node.id = that.nodeCounter - 1; } return newNode case esprima.Syntax.BinaryExpression: case esprima.Syntax.UpdateExpression: case esprima.Syntax.LogicalExpression: case esprima.Syntax.UnaryExpression: case esprima.Syntax.Identifier: { // Only instrument Identifier in certain context. if (node.type === esprima.Syntax.Identifier) { if (!(parent && (parent.type == 'UnaryExpression' || parent.type == 'BinaryExpression' || parent.type == 'LogicalExpression' || parent.type == 'ConditionalExpression' || parent.type == 'SwitchStatement' || parent.type == 'SwitchCase' || parent.type == 'ForStatement' || parent.type == 'IfStatement' || parent.type == 'WhileStatement' || parent.type == 'DoWhileStatement'))) { return; } // Do not instrument Identifier when preceded by typeof if (parent.operator == 'typeof') { return; } } var newNode = { "type": "SequenceExpression", "expressions": [ { "type": "CallExpression", "callee": { "type": "Identifier", "name": that.names.expression }, "arguments": [ { "type": "Identifier", "name": that.nodeCounter++ } ] }, node ] } that.nodes[that.nodeCounter - 1] = node; node.id = that.nodeCounter - 1; return newNode } case esprima.Syntax.BlockStatement: { var newNode = { "type": "ExpressionStatement", "expression": { "type": "CallExpression", "callee": { "type": "Identifier", "name": that.names.block }, "arguments": [ { "type": "Literal", "value": that.blockCounter++ } ] }, "noCover": true } node.body.unshift(newNode) break; } case esprima.Syntax.ForStatement: case esprima.Syntax.ForInStatement: case esprima.Syntax.LabeledStatement: case esprima.Syntax.WhileStatement: case esprima.Syntax.WithStatement: case esprima.Syntax.CatchClause: case esprima.Syntax.DoWhileStatement: { if (node.body && node.body.type !== esprima.Syntax.BlockStatement) { var newNode = { "type": "BlockStatement", "body": [ node.body ] } node.body = newNode; } break; } case esprima.Syntax.TryStatement: { if (node.block && node.block.type !== esprima.Syntax.BlockStatement) { var newNode = { "type": "BlockStatement", "body": [ node.block ] } node.block = newNode; } if (node.finalizer && node.finalizer.type !== esprima.Syntax.BlockStatement) { var newNode = { "type": "BlockStatement", "body": [ node.block ] } node.finalizer = newNode; } break; } case esprima.Syntax.SwitchCase: { if (node.consequent && node.consequent.length > 0 && (node.consequent.length != 1 || node.consequent[0].type !== esprima.Syntax.BlockStatement)) { var newNode = { "type": "BlockStatement", "body": node.consequent } node.consequent = [newNode]; } break; } case esprima.Syntax.IfStatement: { if (node.consequent && node.consequent.type !== esprima.Syntax.BlockStatement) { var newNode = { "type": "BlockStatement", "body": [ node.consequent ] } node.consequent = newNode; } if (node.alternate && node.alternate.type !== esprima.Syntax.BlockStatement && node.alternate.type !== esprima.Syntax.IfStatement) { var newNode = { "type": "BlockStatement", "body": [ node.alternate ] } node.alternate = newNode; } break; } } }); } module.exports.Instrumentor = Instrumentor;
require('ember-bootstrap/mixins/item_view_title_support'); require('ember-bootstrap/mixins/item_view_href_support'); Bootstrap.Pager = Ember.CollectionView.extend({ tagName: 'ul', classNames: ['pager'], itemTitleKey: 'title', itemHrefKey: 'href', content: Ember.A([Ember.Object.create({title: '&larr;'}), Ember.Object.create({title: '&rarr;'})]), itemViewClass: Ember.View.extend(Bootstrap.ItemViewTitleSupport, Bootstrap.ItemViewHrefSupport, { classNameBindings: ['content.next', 'content.previous', 'content.disabled'], template: Ember.Handlebars.compile('<a {{bindAttr href="view.href"}}>{{{view.title}}}</a>') }), arrayDidChange: function(content, start, removed, added) { if (content) { Ember.assert('content must always has at the most 2 elements', content.get('length') <= 2); } return this._super(content, start, removed, added); } });
var pool = require(__dirname + '/dbConnectionPool.js'); function Contract() {} Contract.prototype.UNCONFIRMED = 'UNCONFIRMED'; Contract.prototype.PENDING = 'PENDING'; Contract.prototype.CONFIRMED = 'CONFIRMED'; Contract.prototype.FAILED = 'FAILED'; Contract.prototype.readAll = function() { return pool.query('SELECT * FROM contract'); }; Contract.prototype.read = function(id) { return pool.query('SELECT * FROM contract WHERE id = $1', [id]); }; Contract.prototype.create = function(entity) { return pool.query("SELECT nextval(pg_get_serial_sequence('contractEvent', 'id')) as id;").then(function(result) { var id = result.rows[0].id; return pool.query("INSERT INTO contract (id, name, sourceCode, byteCode, language, compilerVersion, abi, createTimestamp, gasEstimates, status) VALUES " + "($1, $2, $3, $4, $5, $6, $7, now(), $8, $9)", [id, entity.name, entity.sourceCode, entity.byteCode, entity.language, entity.compilerVersion, entity.abi, entity.gasEstimates, Contract.prototype.UNCONFIRMED]) .then(function(){ return id; }).catch(function (err) { console.log(err.message, err.stack); }); }).catch(function (err) { console.log(err.message, err.stack); }); }; Contract.prototype.update = function() { }; Contract.prototype.updateTransactionHash = function(entity) { return pool.query("UPDATE contract SET transactionHash = $1, status = $2, createTimestamp = now() WHERE id = $3", [entity.transactionHash, Contract.prototype.PENDING, entity.id]); } Contract.prototype.updateAddress = function(entity) { return pool.query("UPDATE contract SET address = $1, status = $2, createTimestamp = now() WHERE id = $3", [entity.address, Contract.prototype.CONFIRMED, entity.id]); } Contract.prototype.delete = function() { }; exports = module.exports = new Contract();
GLOBAL.DEBUG = true; debug = require("sys").debug, inspect = require("sys").inspect; test = require("assert"); var Db = require('../lib/mongodb').Db, GridStore = require('../lib/mongodb').GridStore, Chunk = require('../lib/mongodb').Chunk, Server = require('../lib/mongodb').Server, ServerPair = require('../lib/mongodb').ServerPair, ServerCluster = require('../lib/mongodb').ServerCluster, Code = require('../lib/mongodb/bson/bson').Code; Binary = require('../lib/mongodb/bson/bson').Binary; ObjectID = require('../lib/mongodb/bson/bson').ObjectID, DBRef = require('../lib/mongodb/bson/bson').DBRef, Cursor = require('../lib/mongodb/cursor').Cursor, Collection = require('../lib/mongodb/collection').Collection, BinaryParser = require('../lib/mongodb/bson/binary_parser').BinaryParser, Buffer = require('buffer').Buffer, fs = require('fs'), Script = require('vm'); /******************************************************************************************************* Integration Tests *******************************************************************************************************/ var all_tests = { // Test unicode characters test_unicode_characters : function() { client.createCollection('unicode_test_collection', function(err, collection) { var test_strings = ["ouooueauiOUOOUEAUI", "öüóőúéáűíÖÜÓŐÚÉÁŰÍ", "本荘由利地域に洪水警報"]; collection.insert({id: 0, text: test_strings[0]}, function(err, ids) { collection.insert({id: 1, text: test_strings[1]}, function(err, ids) { collection.insert({id: 2, text: test_strings[2]}, function(err, ids) { collection.find(function(err, cursor) { cursor.each(function(err, item) { if(item !== null) { test.equal(test_strings[item.id], item.text); } }); finished_test({test_unicode_characters:'ok'}); }); }); }); }); }); }, // Test the creation of a collection on the mongo db test_collection_methods : function() { client.createCollection('test_collection_methods', function(err, collection) { // Verify that all the result are correct coming back (should contain the value ok) test.equal('test_collection_methods', collection.collectionName); // Let's check that the collection was created correctly client.collectionNames(function(err, documents) { var found = false; documents.forEach(function(document) { if(document.name == "integration_tests_.test_collection_methods") found = true; }); test.ok(true, found); // Rename the collection and check that it's gone client.renameCollection("test_collection_methods", "test_collection_methods2", function(err, reply) { test.equal(1, reply.documents[0].ok); // Drop the collection and check that it's gone client.dropCollection("test_collection_methods2", function(err, result) { test.equal(true, result); finished_test({test_collection_methods:'ok'}); }) }); }); }) }, // Test the authentication method for the user test_authentication : function() { var user_name = 'spongebob'; var password = 'password'; client.authenticate('admin', 'admin', function(err, replies) { test.ok(err instanceof Error); test.ok(!replies); // Add a user client.addUser(user_name, password, function(err, result) { client.authenticate(user_name, password, function(err, replies) { // test.ok(replies); finished_test({test_authentication:'ok'}); }); }); }); }, // Test the access to collections test_collections : function() { // Create two collections client.createCollection('test.spiderman', function(r) { client.createCollection('test.mario', function(r) { // Insert test documents (creates collections) client.collection('test.spiderman', function(err, spiderman_collection) { spiderman_collection.insert({foo:5}); }); client.collection('test.mario', function(err, mario_collection) { mario_collection.insert({bar:0}); }); // Assert collections client.collections(function(err, collections) { var found_spiderman = false; var found_mario = false; var found_does_not_exist = false; collections.forEach(function(collection) { if(collection.collectionName == "test.spiderman") found_spiderman = true; if(collection.collectionName == "test.mario") found_mario = true; if(collection.collectionName == "does_not_exist") found_does_not_exist = true; }); test.ok(found_spiderman); test.ok(found_mario); test.ok(!found_does_not_exist); finished_test({test_collections:'ok'}); }); }); }); }, // Test the generation of the object ids test_object_id_generation : function() { var number_of_tests_done = 0; client.collection('test_object_id_generation.data', function(err, collection) { // Insert test documents (creates collections and test fetch by query) collection.insert({name:"Fred", age:42}, function(err, ids) { test.equal(1, ids.length); test.ok(ids[0]['_id'].toHexString().length == 24); // Locate the first document inserted collection.findOne({name:"Fred"}, function(err, document) { test.equal(ids[0]['_id'].toHexString(), document._id.toHexString()); number_of_tests_done++; }); }); // Insert another test document and collect using ObjectId collection.insert({name:"Pat", age:21}, function(err, ids) { test.equal(1, ids.length); test.ok(ids[0]['_id'].toHexString().length == 24); // Locate the first document inserted collection.findOne(ids[0]['_id'], function(err, document) { test.equal(ids[0]['_id'].toHexString(), document._id.toHexString()); number_of_tests_done++; }); }); // Manually created id var objectId = new client.bson_serializer.ObjectID(null); // Insert a manually created document with generated oid collection.insert({"_id":objectId, name:"Donald", age:95}, function(err, ids) { test.equal(1, ids.length); test.ok(ids[0]['_id'].toHexString().length == 24); test.equal(objectId.toHexString(), ids[0]['_id'].toHexString()); // Locate the first document inserted collection.findOne(ids[0]['_id'], function(err, document) { test.equal(ids[0]['_id'].toHexString(), document._id.toHexString()); test.equal(objectId.toHexString(), document._id.toHexString()); number_of_tests_done++; }); }); }); var intervalId = setInterval(function() { if(number_of_tests_done == 3) { clearInterval(intervalId); finished_test({test_object_id_generation:'ok'}); } }, 100); }, test_object_id_to_and_from_hex_string : function() { var objectId = new client.bson_serializer.ObjectID(null); var originalHex= objectId.toHexString(); var newObjectId= new client.bson_serializer.ObjectID.createFromHexString(originalHex) newHex= newObjectId.toHexString(); test.equal(originalHex, newHex); finished_test({test_object_id_to_and_from_hex_string:'ok'}); }, // Test the auto connect functionality of the db test_automatic_reconnect : function() { var automatic_connect_client = new Db('integration_tests_', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {}); automatic_connect_client.bson_deserializer = client.bson_deserializer; automatic_connect_client.bson_serializer = client.bson_serializer; automatic_connect_client.pkFactory = client.pkFactory; automatic_connect_client.open(function(err, automatic_connect_client) { // Listener for closing event var closeListener = function(has_error) { // Remove the listener for the close to avoid loop automatic_connect_client.serverConfig.masterConnection.removeListener("close", closeListener); // Let's insert a document automatic_connect_client.collection('test_object_id_generation.data2', function(err, collection) { // Insert another test document and collect using ObjectId collection.insert({"name":"Patty", "age":34}, function(err, ids) { test.equal(1, ids.length); test.ok(ids[0]._id.toHexString().length == 24); collection.findOne({"name":"Patty"}, function(err, document) { test.equal(ids[0]._id.toHexString(), document._id.toHexString()); // Let's close the db finished_test({test_automatic_reconnect:'ok'}); automatic_connect_client.close(); }); }); }); }; // Add listener to close event automatic_connect_client.serverConfig.masterConnection.addListener("close", closeListener); automatic_connect_client.serverConfig.masterConnection.connection.end(); }); }, // Test that error conditions are handled correctly test_connection_errors : function() { // Test error handling for single server connection var serverConfig = new Server("127.0.0.1", 21017, {auto_reconnect: true}); var error_client = new Db('integration_tests_', serverConfig, {}); error_client.addListener("error", function(err) {}); error_client.addListener("close", function(connection) { test.ok(typeof connection == typeof serverConfig); test.equal("127.0.0.1", connection.host); test.equal(21017, connection.port); test.equal(true, connection.autoReconnect); }); error_client.open(function(err, error_client) {}); // Test error handling for server pair (works for cluster aswell) var serverConfig = new Server("127.0.0.1", 20017, {}); var normalServer = new Server("127.0.0.1", 27017); var serverPairConfig = new ServerPair(normalServer, serverConfig); var error_client_pair = new Db('integration_tests_21', serverPairConfig, {}); var closeListener = function(connection) { test.ok(typeof connection == typeof serverConfig); test.equal("127.0.0.1", connection.host); test.equal(20017, connection.port); test.equal(false, connection.autoReconnect); // Let's close the db finished_test({test_connection_errors:'ok'}); error_client_pair.removeListener("close", closeListener); normalServer.close(); }; error_client_pair.addListener("error", function(err) {}); error_client_pair.addListener("close", closeListener); error_client_pair.open(function(err, error_client_pair) {}); }, // Test the error reporting functionality test_error_handling : function() { var error_client = new Db('integration_tests2_', new Server("127.0.0.1", 27017, {auto_reconnect: false}), {}); error_client.bson_deserializer = client.bson_deserializer; error_client.bson_serializer = client.bson_serializer; error_client.pkFactory = client.pkFactory; error_client.open(function(err, error_client) { error_client.resetErrorHistory(function() { error_client.error(function(err, documents) { test.equal(true, documents[0].ok); test.equal(0, documents[0].n); // Force error on server error_client.executeDbCommand({forceerror: 1}, function(err, r) { test.equal(0, r.documents[0].ok); test.ok(r.documents[0].errmsg.length > 0); // // Check for previous errors error_client.previousErrors(function(err, documents) { test.equal(true, documents[0].ok); test.equal(1, documents[0].nPrev); test.equal("forced error", documents[0].err); // Check for the last error error_client.error(function(err, documents) { test.equal("forced error", documents[0].err); // Force another error error_client.collection('test_error_collection', function(err, collection) { collection.findOne({name:"Fred"}, function(err, document) { // Check that we have two previous errors error_client.previousErrors(function(err, documents) { test.equal(true, documents[0].ok); test.equal(2, documents[0].nPrev); test.equal("forced error", documents[0].err); error_client.resetErrorHistory(function() { error_client.previousErrors(function(err, documents) { test.equal(true, documents[0].ok); test.equal(-1, documents[0].nPrev); error_client.error(function(err, documents) { test.equal(true, documents[0].ok); test.equal(0, documents[0].n); // Let's close the db finished_test({test_error_handling:'ok'}); error_client.close(); }); }) }); }); }); }); }) }); }); }); }); }); }, // Test the last status functionality of the driver test_last_status : function() { client.createCollection('test_last_status', function(err, collection) { test.ok(collection instanceof Collection); test.equal('test_last_status', collection.collectionName); // Get the collection client.collection('test_last_status', function(err, collection) { // Remove all the elements of the collection collection.remove(function(err, result) { // Check update of a document collection.insert({i:1}, function(err, ids) { test.equal(1, ids.length); test.ok(ids[0]._id.toHexString().length == 24); // Update the record collection.update({i:1}, {"$set":{i:2}}, function(err, result) { // Check for the last message from the server client.lastStatus(function(err, status) { test.equal(true, status.documents[0].ok); test.equal(true, status.documents[0].updatedExisting); // Check for failed update of document collection.update({i:1}, {"$set":{i:500}}, function(err, result) { client.lastStatus(function(err, status) { test.equal(true, status.documents[0].ok); test.equal(false, status.documents[0].updatedExisting); // Check safe update of a document collection.insert({x:1}, function(err, ids) { collection.update({x:1}, {"$set":{x:2}}, {'safe':true}, function(err, document) { }); collection.update({x:1}, {"$set":{x:2}}, {'safe':true}); collection.update({y:1}, {"$set":{y:2}}, {'safe':true}, function(err, result) { test.equal(0, result); // Let's close the db finished_test({test_last_status:'ok'}); }); }); }); }); }); }); }); }); }); }); }, // Test clearing out of the collection test_clear : function() { client.createCollection('test_clear', function(err, r) { client.collection('test_clear', function(err, collection) { collection.insert({i:1}, function(err, ids) { collection.insert({i:2}, function(err, ids) { collection.count(function(err, count) { test.equal(2, count); // Clear the collection collection.remove({}, {safe:true}, function(err, result) { test.equal(2, result); collection.count(function(err, count) { test.equal(0, count); // Let's close the db finished_test({test_clear:'ok'}); }); }); }); }); }); }); }); }, // Test insert of documents test_insert : function() { client.createCollection('test_insert', function(err, r) { client.collection('test_insert', function(err, collection) { for(var i = 1; i < 1000; i++) { collection.insert({c:i}, function(err, r) {}); } collection.insert({a:2}, function(err, r) { collection.insert({a:3}, function(err, r) { collection.count(function(err, count) { test.equal(1001, count); // Locate all the entries using find collection.find(function(err, cursor) { cursor.toArray(function(err, results) { test.equal(1001, results.length); test.ok(results[0] != null); // Let's close the db finished_test({test_insert:'ok'}); }); }); }); }); }); }); }); }, test_failing_insert_due_to_unique_index : function () { client.createCollection('test_failing_insert_due_to_unique_index', function(err, r) { client.collection('test_failing_insert_due_to_unique_index', function(err, collection) { collection.ensureIndex([['a', 1 ]], true, function(err, indexName) { collection.insert({a:2}, {safe: true}, function(err, r) { test.ok(err == null); collection.insert({a:2}, {safe: true}, function(err, r) { test.ok(err != null); finished_test({test_failing_insert_due_to_unique_index:'ok'}); }) }) }) }) }) }, // Test the error reporting functionality test_failing_insert_due_to_unique_index_strict : function() { var error_client = new Db('integration_tests2_', new Server("127.0.0.1", 27017, {auto_reconnect: false}), {strict:true}); error_client.bson_deserializer = client.bson_deserializer; error_client.bson_serializer = client.bson_serializer; error_client.pkFactory = client.pkFactory; error_client.open(function(err, error_client) { error_client.dropCollection('test_failing_insert_due_to_unique_index_strict', function(err, r) { error_client.createCollection('test_failing_insert_due_to_unique_index_strict', function(err, r) { error_client.collection('test_failing_insert_due_to_unique_index_strict', function(err, collection) { collection.ensureIndex([['a', 1 ]], true, function(err, indexName) { collection.insert({a:2}, function(err, r) { test.ok(err == null); collection.insert({a:2}, function(err, r) { test.ok(err != null); error_client.close(); finished_test({test_failing_insert_due_to_unique_index_strict:'ok'}); }) }) }) }) }) }); }); }, // Test multiple document insert test_multiple_insert : function() { client.createCollection('test_multiple_insert', function(err, r) { var collection = client.collection('test_multiple_insert', function(err, collection) { var docs = [{a:1}, {a:2}]; collection.insert(docs, function(err, ids) { ids.forEach(function(doc) { test.ok(((doc['_id']) instanceof ObjectID || Object.prototype.toString.call(doc['_id']) === '[object ObjectID]')); }); // Let's ensure we have both documents collection.find(function(err, cursor) { cursor.toArray(function(err, docs) { test.equal(2, docs.length); var results = []; // Check that we have all the results we want docs.forEach(function(doc) { if(doc.a == 1 || doc.a == 2) results.push(1); }); test.equal(2, results.length); // Let's close the db finished_test({test_multiple_insert:'ok'}); }); }); }); }); }); }, // Test the count result on a collection that does not exist test_count_on_nonexisting : function() { client.collection('test_multiple_insert_2', function(err, collection) { collection.count(function(err, count) { test.equal(0, count); // Let's close the db finished_test({test_count_on_nonexisting:'ok'}); }); }); }, // Test a simple find test_find_simple : function() { client.createCollection('test_find_simple', function(err, r) { var collection = client.collection('test_find_simple', function(err, collection) { var doc1 = null; var doc2 = null; // Insert some test documents collection.insert([{a:2}, {b:3}], function(err, docs) {doc1 = docs[0]; doc2 = docs[1]}); // Ensure correct insertion testing via the cursor and the count function collection.find(function(err, cursor) { cursor.toArray(function(err, documents) { test.equal(2, documents.length); }) }); collection.count(function(err, count) { test.equal(2, count); }); // Fetch values by selection collection.find({'a': doc1.a}, function(err, cursor) { cursor.toArray(function(err, documents) { test.equal(1, documents.length); test.equal(doc1.a, documents[0].a); // Let's close the db finished_test({test_find_simple:'ok'}); }); }); }); }); }, // Test a simple find chained test_find_simple_chained : function() { client.createCollection('test_find_simple_chained', function(err, r) { var collection = client.collection('test_find_simple_chained', function(err, collection) { var doc1 = null; var doc2 = null; // Insert some test documents collection.insert([{a:2}, {b:3}], function(err, docs) {doc1 = docs[0]; doc2 = docs[1]}); // Ensure correct insertion testing via the cursor and the count function collection.find().toArray(function(err, documents) { test.equal(2, documents.length); }); collection.count(function(err, count) { test.equal(2, count); }); // Fetch values by selection collection.find({'a': doc1.a}).toArray(function(err, documents) { test.equal(1, documents.length); test.equal(doc1.a, documents[0].a); // Let's close the db finished_test({test_find_simple_chained:'ok'}); }); }); }); }, // Test advanced find test_find_advanced : function() { client.createCollection('test_find_advanced', function(err, r) { var collection = client.collection('test_find_advanced', function(err, collection) { var doc1 = null, doc2 = null, doc3 = null; // Insert some test documents collection.insert([{a:1}, {a:2}, {b:3}], function(err, docs) { var doc1 = docs[0], doc2 = docs[1], doc3 = docs[2]; // Locate by less than collection.find({'a':{'$lt':10}}, function(err, cursor) { cursor.toArray(function(err, documents) { test.equal(2, documents.length); // Check that the correct documents are returned var results = []; // Check that we have all the results we want documents.forEach(function(doc) { if(doc.a == 1 || doc.a == 2) results.push(1); }); test.equal(2, results.length); }); }); // Locate by greater than collection.find({'a':{'$gt':1}}, function(err, cursor) { cursor.toArray(function(err, documents) { test.equal(1, documents.length); test.equal(2, documents[0].a); }); }); // Locate by less than or equal to collection.find({'a':{'$lte':1}}, function(err, cursor) { cursor.toArray(function(err, documents) { test.equal(1, documents.length); test.equal(1, documents[0].a); }); }); // Locate by greater than or equal to collection.find({'a':{'$gte':1}}, function(err, cursor) { cursor.toArray(function(err, documents) { test.equal(2, documents.length); // Check that the correct documents are returned var results = []; // Check that we have all the results we want documents.forEach(function(doc) { if(doc.a == 1 || doc.a == 2) results.push(1); }); test.equal(2, results.length); }); }); // Locate by between collection.find({'a':{'$gt':1, '$lt':3}}, function(err, cursor) { cursor.toArray(function(err, documents) { test.equal(1, documents.length); test.equal(2, documents[0].a); }); }); // Locate in clause collection.find({'a':{'$in':[1,2]}}, function(err, cursor) { cursor.toArray(function(err, documents) { test.equal(2, documents.length); // Check that the correct documents are returned var results = []; // Check that we have all the results we want documents.forEach(function(doc) { if(doc.a == 1 || doc.a == 2) results.push(1); }); test.equal(2, results.length); }); }); // Locate in _id clause collection.find({'_id':{'$in':[doc1['_id'], doc2['_id']]}}, function(err, cursor) { cursor.toArray(function(err, documents) { test.equal(2, documents.length); // Check that the correct documents are returned var results = []; // Check that we have all the results we want documents.forEach(function(doc) { if(doc.a == 1 || doc.a == 2) results.push(1); }); test.equal(2, results.length); // Let's close the db finished_test({test_find_advanced:'ok'}); }); }); }); }); }); }, // Test sorting of results test_find_sorting : function() { client.createCollection('test_find_sorting', function(err, r) { client.collection('test_find_sorting', function(err, collection) { var doc1 = null, doc2 = null, doc3 = null, doc4 = null; // Insert some test documents collection.insert([{a:1, b:2}, {a:2, b:1}, {a:3, b:2}, {a:4, b:1} ], function(err, docs) {doc1 = docs[0]; doc2 = docs[1]; doc3 = docs[2]; doc4 = docs[3]}); // Test sorting (ascending) collection.find({'a': {'$lt':10}}, {'sort': [['a', 1]]}, function(err, cursor) { cursor.toArray(function(err, documents) { test.equal(4, documents.length); test.equal(1, documents[0].a); test.equal(2, documents[1].a); test.equal(3, documents[2].a); test.equal(4, documents[3].a); }); }); // Test sorting (descending) collection.find({'a': {'$lt':10}}, {'sort': [['a', -1]]}, function(err, cursor) { cursor.toArray(function(err, documents) { test.equal(4, documents.length); test.equal(4, documents[0].a); test.equal(3, documents[1].a); test.equal(2, documents[2].a); test.equal(1, documents[3].a); }); }); // Test sorting (descending), sort is hash collection.find({'a': {'$lt':10}}, {sort: {a: -1}}, function(err, cursor) { cursor.toArray(function(err, documents) { test.equal(4, documents.length); test.equal(4, documents[0].a); test.equal(3, documents[1].a); test.equal(2, documents[2].a); test.equal(1, documents[3].a); }); }); // Sorting using array of names, assumes ascending order collection.find({'a': {'$lt':10}}, {'sort': ['a']}, function(err, cursor) { cursor.toArray(function(err, documents) { test.equal(4, documents.length); test.equal(1, documents[0].a); test.equal(2, documents[1].a); test.equal(3, documents[2].a); test.equal(4, documents[3].a); }); }); // Sorting using single name, assumes ascending order collection.find({'a': {'$lt':10}}, {'sort': 'a'}, function(err, cursor) { cursor.toArray(function(err, documents) { test.equal(4, documents.length); test.equal(1, documents[0].a); test.equal(2, documents[1].a); test.equal(3, documents[2].a); test.equal(4, documents[3].a); }); }); // Sorting using single name, assumes ascending order, sort is hash collection.find({'a': {'$lt':10}}, {sort: {'a':1}}, function(err, cursor) { cursor.toArray(function(err, documents) { test.equal(4, documents.length); test.equal(1, documents[0].a); test.equal(2, documents[1].a); test.equal(3, documents[2].a); test.equal(4, documents[3].a); }); }); collection.find({'a': {'$lt':10}}, {'sort': ['b', 'a']}, function(err, cursor) { cursor.toArray(function(err, documents) { test.equal(4, documents.length); test.equal(2, documents[0].a); test.equal(4, documents[1].a); test.equal(1, documents[2].a); test.equal(3, documents[3].a); }); }); // Sorting using empty array, no order guarantee should not blow up collection.find({'a': {'$lt':10}}, {'sort': []}, function(err, cursor) { cursor.toArray(function(err, documents) { test.equal(4, documents.length); }); }); /* NONACTUAL */ // Sorting using ordered hash collection.find({'a': {'$lt':10}}, {'sort': {a:-1}}, function(err, cursor) { cursor.toArray(function(err, documents) { // Fail test if not an error //test.ok(err instanceof Error); //test.equal("Error: Invalid sort argument was supplied", err.message); test.equal(4, documents.length); // Let's close the db finished_test({test_find_sorting:'ok'}); }); }); }); }); }, // Test the limit function of the db test_find_limits : function() { client.createCollection('test_find_limits', function(err, r) { client.collection('test_find_limits', function(err, collection) { var doc1 = null, doc2 = null, doc3 = null, doc4 = null; // Insert some test documents collection.insert([{a:1}, {b:2}, {c:3}, {d:4} ], function(err, docs) {doc1 = docs[0]; doc2 = docs[1]; doc3 = docs[2]; doc4 = docs[3]}); // Test limits collection.find({}, {'limit': 1}, function(err, cursor) { cursor.toArray(function(err, documents) { test.equal(1, documents.length); }); }); collection.find({}, {'limit': 2}, function(err, cursor) { cursor.toArray(function(err, documents) { test.equal(2, documents.length); }); }); collection.find({}, {'limit': 3}, function(err, cursor) { cursor.toArray(function(err, documents) { test.equal(3, documents.length); }); }); collection.find({}, {'limit': 4}, function(err, cursor) { cursor.toArray(function(err, documents) { test.equal(4, documents.length); }); }); collection.find({}, {}, function(err, cursor) { cursor.toArray(function(err, documents) { test.equal(4, documents.length); }); }); collection.find({}, {'limit':99}, function(err, cursor) { cursor.toArray(function(err, documents) { test.equal(4, documents.length); // Let's close the db finished_test({test_find_limits:'ok'}); }); }); }); }); }, // Test find by non-quoted values (issue #128) test_find_non_quoted_values : function() { client.createCollection('test_find_non_quoted_values', function(err, r) { client.collection('test_find_non_quoted_values', function(err, collection) { // insert test document collection.insert([{ a: 19, b: 'teststring', c: 59920303 }, { a: "19", b: 'teststring', c: 3984929 }]); collection.find({ a: 19 }, function(err, cursor) { cursor.toArray(function(err, documents) { test.equal(1, documents.length); finished_test({test_find_non_quoted_values:'ok'}); }); }); }); }); }, // Test for querying embedded document using dot-notation (issue #126) test_find_embedded_document : function() { client.createCollection('test_find_embedded_document', function(err, r) { client.collection('test_find_embedded_document', function(err, collection) { // insert test document collection.insert([{ a: { id: 10, value: 'foo' }, b: 'bar', c: { id: 20, value: 'foobar' }}, { a: { id: 11, value: 'foo' }, b: 'bar2', c: { id: 20, value: 'foobar' }}]); // test using integer value collection.find({ 'a.id': 10 }, function(err, cursor) { cursor.toArray(function(err, documents) { test.equal(1, documents.length); test.equal('bar', documents[0].b); }); }); // test using string value collection.find({ 'a.value': 'foo' }, function(err, cursor) { cursor.toArray(function(err, documents) { // should yield 2 documents test.equal(2, documents.length); test.equal('bar', documents[0].b); test.equal('bar2', documents[1].b); finished_test({test_find_embedded_document:'ok'}); }); }); }); }); }, // Find no records test_find_one_no_records : function() { client.createCollection('test_find_one_no_records', function(err, r) { client.collection('test_find_one_no_records', function(err, collection) { collection.find({'a':1}, {}, function(err, cursor) { cursor.toArray(function(err, documents) { test.equal(0, documents.length); // Let's close the db finished_test({test_find_one_no_records:'ok'}); }); }); }); }); }, // Test dropping of collections test_drop_collection : function() { client.createCollection('test_drop_collection2', function(err, r) { client.dropCollection('test_drop_collection', function(err, r) { test.ok(err instanceof Error); test.equal("ns not found", err.message); var found = false; // Ensure we don't have the collection in the set of names client.collectionNames(function(err, replies) { replies.forEach(function(err, document) { if(document.name == "test_drop_collection") { found = true; return; } }); // Let's close the db finished_test({test_drop_collection:'ok'}); // If we have an instance of the index throw and error if(found) throw new Error("should not fail"); }); }); }); }, // Test dropping using the collection drop command test_other_drop : function() { client.createCollection('test_other_drop', function(err, r) { client.collection('test_other_drop', function(err, collection) { collection.drop(function(err, reply) { // Ensure we don't have the collection in the set of names client.collectionNames(function(err, replies) { var found = false; replies.forEach(function(document) { if(document.name == "test_other_drop") { found = true; return; } }); // Let's close the db finished_test({test_other_drop:'ok'}); // If we have an instance of the index throw and error if(found) throw new Error("should not fail"); }); }); }); }); }, test_collection_names : function() { client.createCollection('test_collection_names', function(err, r) { client.collectionNames(function(err, documents) { var found = false; var found2 = false; documents.forEach(function(document) { if(document.name == 'integration_tests_.test_collection_names') found = true; }); test.ok(found); // Insert a document in an non-existing collection should create the collection client.collection('test_collection_names2', function(err, collection) { collection.insert({a:1}) client.collectionNames(function(err, documents) { documents.forEach(function(document) { if(document.name == 'integration_tests_.test_collection_names2') found = true; if(document.name == 'integration_tests_.test_collection_names') found2 = true; }); test.ok(found); test.ok(found2); }); // Let's close the db finished_test({test_collection_names:'ok'}); }); }); }); }, test_collections_info : function() { client.createCollection('test_collections_info', function(err, r) { client.collectionsInfo(function(err, cursor) { test.ok((cursor instanceof Cursor)); // Fetch all the collection info cursor.toArray(function(err, documents) { test.ok(documents.length > 1); var found = false; documents.forEach(function(document) { if(document.name == 'integration_tests_.test_collections_info') found = true; }); test.ok(found); }); // Let's close the db finished_test({test_collections_info:'ok'}); }); }); }, test_collection_options : function() { client.createCollection('test_collection_options', {'capped':true, 'size':1024}, function(err, collection) { test.ok(collection instanceof Collection); test.equal('test_collection_options', collection.collectionName); // Let's fetch the collection options collection.options(function(err, options) { test.equal(true, options.capped); test.equal(1024, options.size); test.equal("test_collection_options", options.create); // Let's close the db finished_test({test_collection_options:'ok'}); }); }); }, test_index_information : function() { client.createCollection('test_index_information', function(err, collection) { collection.insert({a:1}, function(err, ids) { // Create an index on the collection client.createIndex(collection.collectionName, 'a', function(err, indexName) { test.equal("a_1", indexName); // Let's fetch the index information client.indexInformation(collection.collectionName, function(err, collectionInfo) { test.ok(collectionInfo['_id_'] != null); test.equal('_id', collectionInfo['_id_'][0][0]); test.ok(collectionInfo['a_1'] != null); test.deepEqual([["a", 1]], collectionInfo['a_1']); client.indexInformation(function(err, collectionInfo2) { var count1 = 0, count2 = 0; // Get count of indexes for(var i in collectionInfo) { count1 += 1;} for(var i in collectionInfo2) { count2 += 1;} // Tests test.ok(count2 >= count1); test.ok(collectionInfo2['_id_'] != null); test.equal('_id', collectionInfo2['_id_'][0][0]); test.ok(collectionInfo2['a_1'] != null); test.deepEqual([["a", 1]], collectionInfo2['a_1']); test.ok((collectionInfo[indexName] != null)); test.deepEqual([["a", 1]], collectionInfo[indexName]); // Let's close the db finished_test({test_index_information:'ok'}); }); }); }); }) }); }, test_multiple_index_cols : function() { client.createCollection('test_multiple_index_cols', function(err, collection) { collection.insert({a:1}, function(err, ids) { // Create an index on the collection client.createIndex(collection.collectionName, [['a', -1], ['b', 1], ['c', -1]], function(err, indexName) { test.equal("a_-1_b_1_c_-1", indexName); // Let's fetch the index information client.indexInformation(collection.collectionName, function(err, collectionInfo) { var count1 = 0; // Get count of indexes for(var i in collectionInfo) { count1 += 1;} // Test test.equal(2, count1); test.ok(collectionInfo[indexName] != null); test.deepEqual([['a', -1], ['b', 1], ['c', -1]], collectionInfo[indexName]); // Let's close the db finished_test({test_multiple_index_cols:'ok'}); }); }); }); }); }, test_unique_index : function() { // Create a non-unique index and test inserts client.createCollection('test_unique_index', function(err, collection) { client.createIndex(collection.collectionName, 'hello', function(err, indexName) { // Insert some docs collection.insert([{'hello':'world'}, {'hello':'mike'}, {'hello':'world'}], function(err, ids) { // Assert that we have no erros client.error(function(err, errors) { test.equal(1, errors.length); test.equal(null, errors[0].err); }); }); }); }); // Create a unique index and test that insert fails client.createCollection('test_unique_index2', function(err, collection) { client.createIndex(collection.collectionName, 'hello', true, function(err, indexName) { // Insert some docs collection.insert([{'hello':'world'}, {'hello':'mike'}, {'hello':'world'}], function(err, ids) { // Assert that we have erros client.error(function(err, errors) { test.equal(1, errors.length); test.ok(errors[0].err != null); // Let's close the db finished_test({test_unique_index:'ok'}); }); }); }); }); }, test_index_on_subfield : function() { // Create a non-unique index and test inserts client.createCollection('test_index_on_subfield', function(err, collection) { collection.insert([{'hello': {'a':4, 'b':5}}, {'hello': {'a':7, 'b':2}}, {'hello': {'a':4, 'b':10}}], function(err, ids) { // Assert that we have no erros client.error(function(err, errors) { test.equal(1, errors.length); test.ok(errors[0].err == null); }); }); }); // Create a unique subfield index and test that insert fails client.createCollection('test_index_on_subfield2', function(err, collection) { client.createIndex(collection.collectionName, 'hello.a', true, function(err, indexName) { collection.insert([{'hello': {'a':4, 'b':5}}, {'hello': {'a':7, 'b':2}}, {'hello': {'a':4, 'b':10}}], function(err, ids) { // Assert that we have erros client.error(function(err, errors) { test.equal(1, errors.length); test.ok(errors[0].err != null); // Let's close the db finished_test({test_index_on_subfield:'ok'}); }); }); }); }); }, test_array : function() { // Create a non-unique index and test inserts client.createCollection('test_array', function(err, collection) { collection.insert({'b':[1, 2, 3]}, function(err, ids) { collection.find(function(err, cursor) { cursor.toArray(function(err, documents) { test.deepEqual([1, 2, 3], documents[0].b); // Let's close the db finished_test({test_array:'ok'}); }); }, {}); }); }); }, test_regex : function() { var regexp = /foobar/i; client.createCollection('test_regex', function(err, collection) { collection.insert({'b':regexp}, function(err, ids) { collection.find({}, {'fields': ['b']}, function(err, cursor) { cursor.toArray(function(err, items) { test.equal(("" + regexp), ("" + items[0].b)); // Let's close the db finished_test({test_regex:'ok'}); }); }); }); }); }, test_utf8_regex : function() { var regexp = /foobaré/; client.createCollection('test_utf8_regex', function(err, collection) { collection.insert({'b':regexp}, function(err, ids) { collection.find({}, {'fields': ['b']}, function(err, cursor) { cursor.toArray(function(err, items) { test.equal(("" + regexp), ("" + items[0].b)); // Let's close the db finished_test({test_utf8_regex:'ok'}); }); }); }); }); }, // Use some other id than the standard for inserts test_non_oid_id : function() { client.createCollection('test_non_oid_id', function(err, collection) { var date = new Date(); date.setUTCDate(12); date.setUTCFullYear(2009); date.setUTCMonth(11 - 1); date.setUTCHours(12); date.setUTCMinutes(0); date.setUTCSeconds(30); collection.insert({'_id':date}, function(err, ids) { collection.find({'_id':date}, function(err, cursor) { cursor.toArray(function(err, items) { test.equal(("" + date), ("" + items[0]._id)); // Let's close the db finished_test({test_non_oid_id:'ok'}); }); }); }); }); }, test_strict_access_collection : function() { var error_client = new Db('integration_tests_', new Server("127.0.0.1", 27017, {auto_reconnect: false}), {strict:true}); error_client.bson_deserializer = client.bson_deserializer; error_client.bson_serializer = client.bson_serializer; error_client.pkFactory = client.pkFactory; test.equal(true, error_client.strict); error_client.open(function(err, error_client) { error_client.collection('does-not-exist', function(err, collection) { test.ok(err instanceof Error); test.equal("Collection does-not-exist does not exist. Currently in strict mode.", err.message); }); error_client.createCollection('test_strict_access_collection', function(err, collection) { error_client.collection('test_strict_access_collection', function(err, collection) { test.ok(collection instanceof Collection); // Let's close the db finished_test({test_strict_access_collection:'ok'}); error_client.close(); }); }); }); }, test_strict_create_collection : function() { var error_client = new Db('integration_tests_', new Server("127.0.0.1", 27017, {auto_reconnect: false}), {strict:true}); error_client.bson_deserializer = client.bson_deserializer; error_client.bson_serializer = client.bson_serializer; error_client.pkFactory = client.pkFactory; test.equal(true, error_client.strict); error_client.open(function(err, error_client) { error_client.createCollection('test_strict_create_collection', function(err, collection) { test.ok(collection instanceof Collection); // Creating an existing collection should fail error_client.createCollection('test_strict_create_collection', function(err, collection) { test.ok(err instanceof Error); test.equal("Collection test_strict_create_collection already exists. Currently in strict mode.", err.message); // Switch out of strict mode and try to re-create collection error_client.strict = false; error_client.createCollection('test_strict_create_collection', function(err, collection) { test.ok(collection instanceof Collection); // Let's close the db finished_test({test_strict_create_collection:'ok'}); error_client.close(); }); }); }); }); }, test_to_a : function() { client.createCollection('test_to_a', function(err, collection) { test.ok(collection instanceof Collection); collection.insert({'a':1}, function(err, ids) { collection.find({}, function(err, cursor) { cursor.toArray(function(err, items) { // Should fail if called again (cursor should be closed) cursor.toArray(function(err, items) { test.ok(err instanceof Error); test.equal("Cursor is closed", err.message); // Should fail if called again (cursor should be closed) cursor.each(function(err, item) { test.ok(err instanceof Error); test.equal("Cursor is closed", err.message); // Let's close the db finished_test({test_to_a:'ok'}); }); }); }); }); }); }); }, test_to_a_after_each : function() { client.createCollection('test_to_a_after_each', function(err, collection) { test.ok(collection instanceof Collection); collection.insert({'a':1}, function(err, ids) { collection.find(function(err, cursor) { cursor.each(function(err, item) { if(item == null) { cursor.toArray(function(err, items) { test.ok(err instanceof Error); test.equal("Cursor is closed", err.message); // Let's close the db finished_test({test_to_a_after_each:'ok'}); }); }; }); }); }); }); }, test_stream_records_calls_data_the_right_number_of_times : function() { client.createCollection('test_stream_records', function(err, collection) { test.ok(collection instanceof Collection); collection.insert([{'a':1}, {'b' : 2}, {'c' : 3}, {'d' : 4}, {'e' : 5}], function(err, ids) { collection.find({}, {'limit' : 3}, function(err, cursor) { var stream = cursor.streamRecords(); var callsToEnd = 0; stream.addListener('end', function() { finished_test({test_stream_records_calls_data_the_right_number_of_times:'ok'}); }); var callsToData = 0; stream.addListener('data',function(data){ callsToData += 1; test.ok(callsToData <= 3); }); }); }); }); }, test_stream_records_calls_end_the_right_number_of_times : function() { client.createCollection('test_stream_records', function(err, collection) { test.ok(collection instanceof Collection); collection.insert([{'a':1}, {'b' : 2}, {'c' : 3}, {'d' : 4}, {'e' : 5}], function(err, ids) { collection.find({}, {'limit' : 3}, function(err, cursor) { var stream = cursor.streamRecords(function(er,item) {}); var callsToEnd = 0; stream.addListener('end', function() { callsToEnd += 1; test.equal(1, callsToEnd); setTimeout(function() { // Let's close the db if (callsToEnd == 1) { finished_test({test_stream_records_calls_end_the_right_number_of_times:'ok'}); } }.bind(this), 1000); }); stream.addListener('data',function(data){ /* nothing here */ }); }); }); }); }, test_where : function() { client.createCollection('test_where', function(err, collection) { test.ok(collection instanceof Collection); collection.insert([{'a':1}, {'a':2}, {'a':3}], function(err, ids) { collection.count(function(err, count) { test.equal(3, count); // Let's test usage of the $where statement collection.find({'$where':new client.bson_serializer.Code('this.a > 2')}, function(err, cursor) { cursor.count(function(err, count) { test.equal(1, count); }); }); collection.find({'$where':new client.bson_serializer.Code('this.a > i', {i:1})}, function(err, cursor) { cursor.count(function(err, count) { test.equal(2, count); // Let's close the db finished_test({test_where:'ok'}); }); }); }); }); }); }, test_eval : function() { client.eval('function (x) {return x;}', [3], function(err, result) { test.equal(3, result); }); client.eval('function (x) {db.test_eval.save({y:x});}', [5], function(err, result) { test.equal(null, result) // Locate the entry client.collection('test_eval', function(err, collection) { collection.findOne(function(err, item) { test.equal(5, item.y); }); }); }); client.eval('function (x, y) {return x + y;}', [2, 3], function(err, result) { test.equal(5, result); }); client.eval('function () {return 5;}', function(err, result) { test.equal(5, result); }); client.eval('2 + 3;', function(err, result) { test.equal(5, result); }); client.eval(new client.bson_serializer.Code("2 + 3;"), function(err, result) { test.equal(5, result); }); client.eval(new client.bson_serializer.Code("return i;", {'i':2}), function(err, result) { test.equal(2, result); }); client.eval(new client.bson_serializer.Code("i + 3;", {'i':2}), function(err, result) { test.equal(5, result); }); client.eval("5 ++ 5;", function(err, result) { test.ok(err instanceof Error); test.ok(err.message != null); // Let's close the db finished_test({test_eval:'ok'}); }); }, test_hint : function() { client.createCollection('test_hint', function(err, collection) { collection.insert({'a':1}, function(err, ids) { client.createIndex(collection.collectionName, "a", function(err, indexName) { collection.find({'a':1}, {'hint':'a'}, function(err, cursor) { cursor.toArray(function(err, items) { test.equal(1, items.length); }); }); collection.find({'a':1}, {'hint':['a']}, function(err, cursor) { cursor.toArray(function(err, items) { test.equal(1, items.length); }); }); collection.find({'a':1}, {'hint':{'a':1}}, function(err, cursor) { cursor.toArray(function(err, items) { test.equal(1, items.length); }); }); // Modify hints collection.hint = 'a'; test.equal(1, collection.hint['a']); collection.find({'a':1}, function(err, cursor) { cursor.toArray(function(err, items) { test.equal(1, items.length); }); }); collection.hint = ['a']; test.equal(1, collection.hint['a']); collection.find({'a':1}, function(err, cursor) { cursor.toArray(function(err, items) { test.equal(1, items.length); }); }); collection.hint = {'a':1}; test.equal(1, collection.hint['a']); collection.find({'a':1}, function(err, cursor) { cursor.toArray(function(err, items) { test.equal(1, items.length); }); }); collection.hint = null; test.ok(collection.hint == null); collection.find({'a':1}, function(err, cursor) { cursor.toArray(function(err, items) { test.equal(1, items.length); // Let's close the db finished_test({test_hint:'ok'}); }); }); }); }); }); }, test_group : function() { client.createCollection('test_group', function(err, collection) { collection.group([], {}, {"count":0}, "function (obj, prev) { prev.count++; }", function(err, results) { test.deepEqual([], results); }); collection.group([], {}, {"count":0}, "function (obj, prev) { prev.count++; }", true, function(err, results) { test.deepEqual([], results); // Trigger some inserts collection.insert([{'a':2}, {'b':5}, {'a':1}], function(err, ids) { collection.group([], {}, {"count":0}, "function (obj, prev) { prev.count++; }", function(err, results) { test.equal(3, results[0].count); }); collection.group([], {}, {"count":0}, "function (obj, prev) { prev.count++; }", true, function(err, results) { test.equal(3, results[0].count); }); collection.group([], {'a':{'$gt':1}}, {"count":0}, "function (obj, prev) { prev.count++; }", function(err, results) { test.equal(1, results[0].count); }); collection.group([], {'a':{'$gt':1}}, {"count":0}, "function (obj, prev) { prev.count++; }", true, function(err, results) { test.equal(1, results[0].count); // Insert some more test data collection.insert([{'a':2}, {'b':3}], function(err, ids) { collection.group(['a'], {}, {"count":0}, "function (obj, prev) { prev.count++; }", function(err, results) { test.equal(2, results[0].a); test.equal(2, results[0].count); test.equal(null, results[1].a); test.equal(2, results[1].count); test.equal(1, results[2].a); test.equal(1, results[2].count); }); collection.group(['a'], {}, {"count":0}, "function (obj, prev) { prev.count++; }", true, function(err, results) { test.equal(2, results[0].a); test.equal(2, results[0].count); test.equal(null, results[1].a); test.equal(2, results[1].count); test.equal(1, results[2].a); test.equal(1, results[2].count); }); collection.group([], {}, {}, "5 ++ 5", function(err, results) { test.ok(err instanceof Error); test.ok(err.message != null); }); collection.group([], {}, {}, "5 ++ 5", true, function(err, results) { test.ok(err instanceof Error); test.ok(err.message != null); // Let's close the db finished_test({test_group:'ok'}); }); }); }); }); }); }); }, test_deref : function() { client.createCollection('test_deref', function(err, collection) { collection.insert({'a':1}, function(err, ids) { collection.remove(function(err, result) { collection.count(function(err, count) { test.equal(0, count); // Execute deref a db reference client.dereference(new client.bson_serializer.DBRef("test_deref", new client.bson_serializer.ObjectID()), function(err, result) { collection.insert({'x':'hello'}, function(err, ids) { collection.findOne(function(err, document) { test.equal('hello', document.x); client.dereference(new client.bson_serializer.DBRef("test_deref", document._id), function(err, result) { test.equal('hello', document.x); }); }); }); }); client.dereference(new client.bson_serializer.DBRef("test_deref", 4), function(err, result) { var obj = {'_id':4}; collection.insert(obj, function(err, ids) { client.dereference(new client.bson_serializer.DBRef("test_deref", 4), function(err, document) { test.equal(obj['_id'], document._id); collection.remove(function(err, result) { collection.insert({'x':'hello'}, function(err, ids) { client.dereference(new client.bson_serializer.DBRef("test_deref", null), function(err, result) { test.equal(null, result); // Let's close the db finished_test({test_deref:'ok'}); }); }); }); }); }); }); }) }) }) }); }, test_save : function() { client.createCollection('test_save', function(err, collection) { var doc = {'hello':'world'}; collection.save(doc, function(err, docs) { test.ok(docs._id instanceof ObjectID || Object.prototype.toString.call(docs._id) === '[object ObjectID]'); collection.count(function(err, count) { test.equal(1, count); doc = docs; collection.save(doc, function(err, doc) { collection.count(function(err, count) { test.equal(1, count); }); collection.findOne(function(err, doc) { test.equal('world', doc.hello); // Modify doc and save doc.hello = 'mike'; collection.save(doc, function(err, doc) { collection.count(function(err, count) { test.equal(1, count); }); collection.findOne(function(err, doc) { test.equal('mike', doc.hello); // Save another document collection.save({hello:'world'}, function(err, doc) { collection.count(function(err, count) { test.equal(2, count); // Let's close the db finished_test({test_save:'ok'}); }); }); }); }); }); }); }); }); }); }, test_save_long : function() { client.createCollection('test_save_long', function(err, collection) { collection.insert({'x':client.bson_serializer.Long.fromNumber(9223372036854775807)}); collection.findOne(function(err, doc) { test.ok(client.bson_serializer.Long.fromNumber(9223372036854775807).equals(doc.x)); // Let's close the db finished_test({test_save_long:'ok'}); }); }); }, test_find_by_oid : function() { client.createCollection('test_find_by_oid', function(err, collection) { collection.save({'hello':'mike'}, function(err, docs) { test.ok(docs._id instanceof ObjectID || Object.prototype.toString.call(docs._id) === '[object ObjectID]'); collection.findOne({'_id':docs._id}, function(err, doc) { test.equal('mike', doc.hello); var id = doc._id.toString(); collection.findOne({'_id':new client.bson_serializer.ObjectID(id)}, function(err, doc) { test.equal('mike', doc.hello); // Let's close the db finished_test({test_find_by_oid:'ok'}); }); }); }); }); }, test_save_with_object_that_has_id_but_does_not_actually_exist_in_collection : function() { client.createCollection('test_save_with_object_that_has_id_but_does_not_actually_exist_in_collection', function(err, collection) { var a = {'_id':'1', 'hello':'world'}; collection.save(a, function(err, docs) { collection.count(function(err, count) { test.equal(1, count); collection.findOne(function(err, doc) { test.equal('world', doc.hello); doc.hello = 'mike'; collection.save(doc, function(err, doc) { collection.count(function(err, count) { test.equal(1, count); }); collection.findOne(function(err, doc) { test.equal('mike', doc.hello); // Let's close the db finished_test({test_save_with_object_that_has_id_but_does_not_actually_exist_in_collection:'ok'}); }); }); }); }); }); }); }, test_invalid_key_names : function() { client.createCollection('test_invalid_key_names', function(err, collection) { // Legal inserts collection.insert([{'hello':'world'}, {'hello':{'hello':'world'}}]); // Illegal insert for key collection.insert({'$hello':'world'}, function(err, doc) { test.ok(err instanceof Error); test.equal("key $hello must not start with '$'", err.message); }); collection.insert({'hello':{'$hello':'world'}}, function(err, doc) { test.ok(err instanceof Error); test.equal("key $hello must not start with '$'", err.message); }); collection.insert({'he$llo':'world'}, function(err, docs) { test.ok(docs[0].constructor == Object); }) collection.insert({'hello':{'hell$o':'world'}}, function(err, docs) { test.ok(err == null); }) collection.insert({'.hello':'world'}, function(err, doc) { test.ok(err instanceof Error); test.equal("key .hello must not contain '.'", err.message); }); collection.insert({'hello':{'.hello':'world'}}, function(err, doc) { test.ok(err instanceof Error); test.equal("key .hello must not contain '.'", err.message); }); collection.insert({'hello.':'world'}, function(err, doc) { test.ok(err instanceof Error); test.equal("key hello. must not contain '.'", err.message); }); collection.insert({'hello':{'hello.':'world'}}, function(err, doc) { test.ok(err instanceof Error); test.equal("key hello. must not contain '.'", err.message); // Let's close the db finished_test({test_invalid_key_names:'ok'}); }); }); }, test_utf8_key_name : function() { client.createCollection('test_utf8_key_name', function(err, collection) { collection.insert({'šđžčćŠĐŽČĆ':1}, function(err, ids) { // finished_test({test_utf8_key_name:'ok'}); collection.find({}, {'fields': ['šđžčćŠĐŽČĆ']}, function(err, cursor) { cursor.toArray(function(err, items) { test.equal(1, items[0]['šđžčćŠĐŽČĆ']); // Let's close the db finished_test({test_utf8_key_name:'ok'}); }); }); }); }); }, test_collection_names2 : function() { client.collection(5, function(err, collection) { test.equal("collection name must be a String", err.message); }); client.collection("", function(err, collection) { test.equal("collection names cannot be empty", err.message); }); client.collection("te$t", function(err, collection) { test.equal("collection names must not contain '$'", err.message); }); client.collection(".test", function(err, collection) { test.equal("collection names must not start or end with '.'", err.message); }); client.collection("test.", function(err, collection) { test.equal("collection names must not start or end with '.'", err.message); }); client.collection("test..t", function(err, collection) { test.equal("collection names cannot be empty", err.message); // Let's close the db finished_test({test_collection_names2:'ok'}); }); }, test_rename_collection : function() { client.createCollection('test_rename_collection', function(err, collection) { client.createCollection('test_rename_collection2', function(err, collection) { client.collection('test_rename_collection', function(err, collection1) { client.collection('test_rename_collection2', function(err, collection2) { // Assert rename collection1.rename(5, function(err, collection) { test.ok(err instanceof Error); test.equal("collection name must be a String", err.message); }); collection1.rename("", function(err, collection) { test.ok(err instanceof Error); test.equal("collection names cannot be empty", err.message); }); collection1.rename("te$t", function(err, collection) { test.ok(err instanceof Error); test.equal("collection names must not contain '$'", err.message); }); collection1.rename(".test", function(err, collection) { test.ok(err instanceof Error); test.equal("collection names must not start or end with '.'", err.message); }); collection1.rename("test.", function(err, collection) { test.ok(err instanceof Error); test.equal("collection names must not start or end with '.'", err.message); }); collection1.rename("tes..t", function(err, collection) { test.equal("collection names cannot be empty", err.message); }); collection1.count(function(err, count) { test.equal(0, count); collection1.insert([{'x':1}, {'x':2}], function(err, docs) { collection1.count(function(err, count) { test.equal(2, count); collection1.rename('test_rename_collection2', function(err, collection) { test.ok(err instanceof Error); test.ok(err.message.length > 0); collection1.rename('test_rename_collection3', function(err, collection) { test.equal("test_rename_collection3", collection.collectionName); // Check count collection.count(function(err, count) { test.equal(2, count); // Let's close the db finished_test({test_rename_collection:'ok'}); }); }); }); }); }) }) collection2.count(function(err, count) { test.equal(0, count); }) }); }); }); }); }, test_explain : function() { client.createCollection('test_explain', function(err, collection) { collection.insert({'a':1}); collection.find({'a':1}, function(err, cursor) { cursor.explain(function(err, explaination) { test.ok(explaination.cursor != null); test.ok(explaination.n.constructor == Number); test.ok(explaination.millis.constructor == Number); test.ok(explaination.nscanned.constructor == Number); // Let's close the db finished_test({test_explain:'ok'}); }); }); }); }, test_count : function() { client.createCollection('test_count', function(err, collection) { collection.find(function(err, cursor) { cursor.count(function(err, count) { test.equal(0, count); for(var i = 0; i < 10; i++) { collection.insert({'x':i}); } collection.find(function(err, cursor) { cursor.count(function(err, count) { test.equal(10, count); test.ok(count.constructor == Number); }); }); collection.find({}, {'limit':5}, function(err, cursor) { cursor.count(function(err, count) { test.equal(10, count); }); }); collection.find({}, {'skip':5}, function(err, cursor) { cursor.count(function(err, count) { test.equal(10, count); }); }); collection.find(function(err, cursor) { cursor.count(function(err, count) { test.equal(10, count); cursor.each(function(err, item) { if(item == null) { cursor.count(function(err, count2) { test.equal(10, count2); test.equal(count, count2); // Let's close the db finished_test({test_count:'ok'}); }); } }); }); }); client.collection('acollectionthatdoesn', function(err, collection) { collection.count(function(err, count) { test.equal(0, count); }); }) }); }); }); }, test_sort : function() { client.createCollection('test_sort', function(err, collection) { for(var i = 0; i < 5; i++) { collection.insert({'a':i}); } collection.find(function(err, cursor) { cursor.sort(['a', 1], function(err, cursor) { test.ok(cursor instanceof Cursor); test.deepEqual(['a', 1], cursor.sortValue); }); }); collection.find(function(err, cursor) { cursor.sort('a', 1, function(err, cursor) { cursor.nextObject(function(err, doc) { test.equal(0, doc.a); }); }); }); collection.find(function(err, cursor) { cursor.sort('a', -1, function(err, cursor) { cursor.nextObject(function(err, doc) { test.equal(4, doc.a); }); }); }); collection.find(function(err, cursor) { cursor.sort('a', "asc", function(err, cursor) { cursor.nextObject(function(err, doc) { test.equal(0, doc.a); }); }); }); collection.find(function(err, cursor) { cursor.sort([['a', -1], ['b', 1]], function(err, cursor) { test.ok(cursor instanceof Cursor); test.deepEqual([['a', -1], ['b', 1]], cursor.sortValue); }); }); collection.find(function(err, cursor) { cursor.sort('a', 1, function(err, cursor) { cursor.sort('a', -1, function(err, cursor) { cursor.nextObject(function(err, doc) { test.equal(4, doc.a); }); }) }); }); collection.find(function(err, cursor) { cursor.sort('a', -1, function(err, cursor) { cursor.sort('a', 1, function(err, cursor) { cursor.nextObject(function(err, doc) { test.equal(0, doc.a); }); }) }); }); collection.find(function(err, cursor) { cursor.nextObject(function(err, doc) { cursor.sort(['a'], function(err, cursor) { test.ok(err instanceof Error); test.equal("Cursor is closed", err.message); // Let's close the db finished_test({test_sort:'ok'}); }); }); }); collection.find(function(err, cursor) { cursor.sort('a', 25, function(err, cursor) { cursor.nextObject(function(err, doc) { test.ok(err instanceof Error); test.equal("Error: Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]", err.message); }); }); }); collection.find(function(err, cursor) { cursor.sort(25, function(err, cursor) { cursor.nextObject(function(err, doc) { test.ok(err instanceof Error); test.equal("Error: Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]", err.message); }); }); }); }); }, test_to_array : function() { client.createCollection('test_to_array', function(err, collection) { for(var i = 0; i < 2; i++) { collection.save({'x':1}, function(err, document) {}); } collection.find(function(err, cursor) { test.throws(function () { cursor.toArray(); }); finished_test({test_to_array:'ok'}); }); }); }, test_each : function() { client.createCollection('test_each', function(err, collection) { for(var i = 0; i < 2; i++) { collection.save({'x':1}, function(err, document) {}); } collection.find(function(err, cursor) { test.throws(function () { cursor.each(); }); finished_test({test_each:'ok'}); }); }); }, test_cursor_limit : function() { client.createCollection('test_cursor_limit', function(err, collection) { for(var i = 0; i < 10; i++) { collection.save({'x':1}, function(err, document) {}); } collection.find(function(err, cursor) { cursor.count(function(err, count) { test.equal(10, count); }); }); collection.find(function(err, cursor) { cursor.limit(5, function(err, cursor) { cursor.toArray(function(err, items) { test.equal(5, items.length); // Let's close the db finished_test({test_cursor_limit:'ok'}); }); }); }); }); }, test_limit_exceptions : function() { client.createCollection('test_limit_exceptions', function(err, collection) { collection.insert({'a':1}, function(err, docs) {}); collection.find(function(err, cursor) { cursor.limit('not-an-integer', function(err, cursor) { test.ok(err instanceof Error); test.equal("limit requires an integer", err.message); }); }); collection.find(function(err, cursor) { cursor.nextObject(function(err, doc) { cursor.limit(1, function(err, cursor) { test.ok(err instanceof Error); test.equal("Cursor is closed", err.message); // Let's close the db finished_test({test_limit_exceptions:'ok'}); }); }); }); collection.find(function(err, cursor) { cursor.close(function(err, cursor) { cursor.limit(1, function(err, cursor) { test.ok(err instanceof Error); test.equal("Cursor is closed", err.message); }); }); }); }); }, test_skip : function() { client.createCollection('test_skip', function(err, collection) { for(var i = 0; i < 10; i++) { collection.insert({'x':i}); } collection.find(function(err, cursor) { cursor.count(function(err, count) { test.equal(10, count); }); }); collection.find(function(err, cursor) { cursor.toArray(function(err, items) { test.equal(10, items.length); collection.find(function(err, cursor) { cursor.skip(2, function(err, cursor) { cursor.toArray(function(err, items2) { test.equal(8, items2.length); // Check that we have the same elements var numberEqual = 0; var sliced = items.slice(2, 10); for(var i = 0; i < sliced.length; i++) { if(sliced[i].x == items2[i].x) numberEqual = numberEqual + 1; } test.equal(8, numberEqual); // Let's close the db finished_test({test_skip:'ok'}); }); }); }); }); }); }); }, test_skip_exceptions : function() { client.createCollection('test_skip_exceptions', function(err, collection) { collection.insert({'a':1}, function(err, docs) {}); collection.find(function(err, cursor) { cursor.skip('not-an-integer', function(err, cursor) { test.ok(err instanceof Error); test.equal("skip requires an integer", err.message); }); }); collection.find(function(err, cursor) { cursor.nextObject(function(err, doc) { cursor.skip(1, function(err, cursor) { test.ok(err instanceof Error); test.equal("Cursor is closed", err.message); // Let's close the db finished_test({test_skip_exceptions:'ok'}); }); }); }); collection.find(function(err, cursor) { cursor.close(function(err, cursor) { cursor.skip(1, function(err, cursor) { test.ok(err instanceof Error); test.equal("Cursor is closed", err.message); }); }); }); }); }, test_batchSize_exceptions : function() { client.createCollection('test_batchSize_exceptions', function(err, collection) { collection.insert({'a':1}, function(err, docs) {}); collection.find(function(err, cursor) { cursor.batchSize('not-an-integer', function(err, cursor) { test.ok(err instanceof Error); test.equal("batchSize requires an integer", err.message); }); }); collection.find(function(err, cursor) { cursor.nextObject(function(err, doc) { cursor.nextObject(function(err, doc) { cursor.batchSize(1, function(err, cursor) { test.ok(err instanceof Error); test.equal("Cursor is closed", err.message); // Let's close the db finished_test({test_batchSize_exceptions:'ok'}); }); }); }); }); collection.find(function(err, cursor) { cursor.close(function(err, cursor) { cursor.batchSize(1, function(err, cursor) { test.ok(err instanceof Error); test.equal("Cursor is closed", err.message); }); }); }); }); }, test_not_multiple_batch_size : function() { client.createCollection('test_not_multiple_batch_size', function(err, collection) { var records = 6; var batchSize = 2; var docs = []; for(var i = 0; i < records; i++) { docs.push({'a':i}); } collection.insert(docs, function() { collection.find({}, {batchSize : batchSize}, function(err, cursor) { //1st cursor.nextObject(function(err, items) { //cursor.items should contain 1 since nextObject already popped one test.equal(1, cursor.items.length); test.ok(items != null); //2nd cursor.nextObject(function(err, items) { test.equal(0, cursor.items.length); test.ok(items != null); //test batch size modification on the fly batchSize = 3; cursor.batchSize(batchSize); //3rd cursor.nextObject(function(err, items) { test.equal(2, cursor.items.length); test.ok(items != null); //4th cursor.nextObject(function(err, items) { test.equal(1, cursor.items.length); test.ok(items != null); //5th cursor.nextObject(function(err, items) { test.equal(0, cursor.items.length); test.ok(items != null); //6th cursor.nextObject(function(err, items) { test.equal(0, cursor.items.length); test.ok(items != null); //No more cursor.nextObject(function(err, items) { test.ok(items == null); test.ok(cursor.isClosed()); finished_test({test_not_multiple_batch_size:'ok'}); }); }); }); }); }); }); }); }); }); }); }, test_multiple_batch_size : function() { client.createCollection('test_multiple_batch_size', function(err, collection) { //test with the last batch that is a multiple of batchSize var records = 4; var batchSize = 2; var docs = []; for(var i = 0; i < records; i++) { docs.push({'a':i}); } collection.insert(docs, function() { collection.find({}, {batchSize : batchSize}, function(err, cursor) { //1st cursor.nextObject(function(err, items) { test.equal(1, cursor.items.length); test.ok(items != null); //2nd cursor.nextObject(function(err, items) { test.equal(0, cursor.items.length); test.ok(items != null); //3rd cursor.nextObject(function(err, items) { test.equal(1, cursor.items.length); test.ok(items != null); //4th cursor.nextObject(function(err, items) { test.equal(0, cursor.items.length); test.ok(items != null); //No more cursor.nextObject(function(err, items) { test.ok(items == null); test.ok(cursor.isClosed()); finished_test({test_multiple_batch_size:'ok'}); }); }); }); }); }); }); }); }); }, test_limit_greater_than_batch_size : function() { client.createCollection('test_limit_greater_than_batch_size', function(err, collection) { var limit = 4; var records = 10; var batchSize = 3; var docs = []; for(var i = 0; i < records; i++) { docs.push({'a':i}); } collection.insert(docs, function() { collection.find({}, {batchSize : batchSize, limit : limit}, function(err, cursor) { //1st cursor.nextObject(function(err, items) { test.equal(2, cursor.items.length); //2nd cursor.nextObject(function(err, items) { test.equal(1, cursor.items.length); //3rd cursor.nextObject(function(err, items) { test.equal(0, cursor.items.length); //4th cursor.nextObject(function(err, items) { test.equal(0, cursor.items.length); //No more cursor.nextObject(function(err, items) { test.ok(items == null); test.ok(cursor.isClosed()); finished_test({test_limit_greater_than_batch_size:'ok'}); }); }); }); }); }); }); }); }); }, test_limit_less_than_batch_size : function () { client.createCollection('test_limit_less_than_batch_size', function(err, collection) { var limit = 2; var records = 10; var batchSize = 4; var docs = []; for(var i = 0; i < records; i++) { docs.push({'a':i}); } collection.insert(docs, function() { collection.find({}, {batchSize : batchSize, limit : limit}, function(err, cursor) { //1st cursor.nextObject(function(err, items) { test.equal(1, cursor.items.length); //2nd cursor.nextObject(function(err, items) { test.equal(0, cursor.items.length); //No more cursor.nextObject(function(err, items) { test.ok(items == null); test.ok(cursor.isClosed()); finished_test({test_limit_less_than_batch_size:'ok'}); }); }); }); }); }); }); }, test_limit_skip_chaining : function() { client.createCollection('test_limit_skip_chaining', function(err, collection) { for(var i = 0; i < 10; i++) { collection.insert({'x':1}); } collection.find(function(err, cursor) { cursor.toArray(function(err, items) { test.equal(10, items.length); collection.find(function(err, cursor) { cursor.limit(5, function(err, cursor) { cursor.skip(3, function(err, cursor) { cursor.toArray(function(err, items2) { test.equal(5, items2.length); // Check that we have the same elements var numberEqual = 0; var sliced = items.slice(3, 8); for(var i = 0; i < sliced.length; i++) { if(sliced[i].x == items2[i].x) numberEqual = numberEqual + 1; } test.equal(5, numberEqual); // Let's close the db finished_test({test_limit_skip_chaining:'ok'}); }); }); }); }); }); }); }); }, test_limit_skip_chaining_inline : function() { client.createCollection('test_limit_skip_chaining_inline', function(err, collection) { for(var i = 0; i < 10; i++) { collection.insert({'x':1}); } collection.find(function(err, cursor) { cursor.toArray(function(err, items) { test.equal(10, items.length); collection.find(function(err, cursor) { cursor.limit(5).skip(3).toArray(function(err, items2) { test.equal(5, items2.length); // Check that we have the same elements var numberEqual = 0; var sliced = items.slice(3, 8); for(var i = 0; i < sliced.length; i++) { if(sliced[i].x == items2[i].x) numberEqual = numberEqual + 1; } test.equal(5, numberEqual); // Let's close the db finished_test({test_limit_skip_chaining_inline:'ok'}); }); }); }); }); }); }, test_close_no_query_sent : function() { client.createCollection('test_close_no_query_sent', function(err, collection) { collection.find(function(err, cursor) { cursor.close(function(err, cursor) { test.equal(true, cursor.isClosed()); // Let's close the db finished_test({test_close_no_query_sent:'ok'}); }); }); }); }, test_refill_via_get_more : function() { client.createCollection('test_refill_via_get_more', function(err, collection) { for(var i = 0; i < 1000; i++) { collection.save({'a': i}, function(err, doc) {}); } collection.count(function(err, count) { test.equal(1000, count); }); var total = 0; collection.find(function(err, cursor) { cursor.each(function(err, item) { if(item != null) { total = total + item.a; } else { test.equal(499500, total); collection.count(function(err, count) { test.equal(1000, count); }); collection.count(function(err, count) { test.equal(1000, count); var total2 = 0; collection.find(function(err, cursor) { cursor.each(function(err, item) { if(item != null) { total2 = total2 + item.a; } else { test.equal(499500, total2); collection.count(function(err, count) { test.equal(1000, count); test.equal(total, total2); // Let's close the db finished_test({test_refill_via_get_more:'ok'}); }); } }); }); }); } }); }); }); }, test_refill_via_get_more_alt_coll : function() { client.createCollection('test_refill_via_get_more_alt_coll', function(err, collection) { for(var i = 0; i < 1000; i++) { collection.save({'a': i}, function(err, doc) {}); } collection.count(function(err, count) { test.equal(1000, count); }); var total = 0; collection.find(function(err, cursor) { cursor.each(function(err, item) { if(item != null) { total = total + item.a; } else { test.equal(499500, total); collection.count(function(err, count) { test.equal(1000, count); }); collection.count(function(err, count) { test.equal(1000, count); var total2 = 0; collection.find(function(err, cursor) { cursor.each(function(err, item) { if(item != null) { total2 = total2 + item.a; } else { test.equal(499500, total2); collection.count(function(err, count) { test.equal(1000, count); test.equal(total, total2); // Let's close the db finished_test({test_refill_via_get_more_alt_coll:'ok'}); }); } }); }); }); } }); }); }); }, test_close_after_query_sent : function() { client.createCollection('test_close_after_query_sent', function(err, collection) { collection.insert({'a':1}); collection.find({'a':1}, function(err, cursor) { cursor.nextObject(function(err, item) { cursor.close(function(err, cursor) { test.equal(true, cursor.isClosed()); // Let's close the db finished_test({test_close_after_query_sent:'ok'}); }) }); }); }); }, // test_kill_cursors : function() { // var test_kill_cursors_client = new Db('integration_tests4_', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {}); // test_kill_cursors_client.bson_deserializer = client.bson_deserializer; // test_kill_cursors_client.bson_serializer = client.bson_serializer; // test_kill_cursors_client.pkFactory = client.pkFactory; // // test_kill_cursors_client.open(function(err, test_kill_cursors_client) { // var number_of_tests_done = 0; // // test_kill_cursors_client.dropCollection('test_kill_cursors', function(err, collection) { // test_kill_cursors_client.createCollection('test_kill_cursors', function(err, collection) { // test_kill_cursors_client.cursorInfo(function(err, cursorInfo) { // var clientCursors = cursorInfo.clientCursors_size; // var byLocation = cursorInfo.byLocation_size; // // for(var i = 0; i < 1000; i++) { // collection.save({'i': i}, function(err, doc) {}); // } // // test_kill_cursors_client.cursorInfo(function(err, cursorInfo) { // test.equal(clientCursors, cursorInfo.clientCursors_size); // test.equal(byLocation, cursorInfo.byLocation_size); // // for(var i = 0; i < 10; i++) { // collection.findOne(function(err, item) {}); // } // // test_kill_cursors_client.cursorInfo(function(err, cursorInfo) { // test.equal(clientCursors, cursorInfo.clientCursors_size); // test.equal(byLocation, cursorInfo.byLocation_size); // // for(var i = 0; i < 10; i++) { // collection.find(function(err, cursor) { // cursor.nextObject(function(err, item) { // cursor.close(function(err, cursor) {}); // // if(i == 10) { // test_kill_cursors_client.cursorInfo(function(err, cursorInfo) { // test.equal(clientCursors, cursorInfo.clientCursors_size); // test.equal(byLocation, cursorInfo.byLocation_size); // // collection.find(function(err, cursor) { // cursor.nextObject(function(err, item) { // test_kill_cursors_client.cursorInfo(function(err, cursorInfo) { // test.equal(clientCursors, cursorInfo.clientCursors_size); // test.equal(byLocation, cursorInfo.byLocation_size); // // cursor.close(function(err, cursor) { // test_kill_cursors_client.cursorInfo(function(err, cursorInfo) { // test.equal(clientCursors, cursorInfo.clientCursors_size); // test.equal(byLocation, cursorInfo.byLocation_size); // // collection.find({}, {'limit':10}, function(err, cursor) { // cursor.nextObject(function(err, item) { // test_kill_cursors_client.cursorInfo(function(err, cursorInfo) { // test_kill_cursors_client.cursorInfo(function(err, cursorInfo) { // sys.puts("===================================== err: " + err) // sys.puts("===================================== cursorInfo: " + sys.inspect(cursorInfo)) // // // test.equal(clientCursors, cursorInfo.clientCursors_size); // test.equal(byLocation, cursorInfo.byLocation_size); // number_of_tests_done = 1; // }); // }); // }); // }); // }); // }); // }); // }); // }); // }); // } // }); // }); // } // }); // }); // }); // }); // }); // // var intervalId = setInterval(function() { // if(number_of_tests_done == 1) { // clearInterval(intervalId); // finished_test({test_kill_cursors:'ok'}); // test_kill_cursors_client.close(); // } // }, 100); // }); // }, test_count_with_fields : function() { client.createCollection('test_count_with_fields', function(err, collection) { collection.save({'x':1, 'a':2}, function(err, doc) { collection.find({}, {'fields':['a']}, function(err, cursor) { cursor.toArray(function(err, items) { test.equal(1, items.length); test.equal(2, items[0].a); test.equal(null, items[0].x); }); }); collection.findOne({}, {'fields':['a']}, function(err, item) { test.equal(2, item.a); test.equal(null, item.x); finished_test({test_count_with_fields:'ok'}); }); }); }); }, test_count_with_fields_using_exclude : function() { client.createCollection('test_count_with_fields_using_exclude', function(err, collection) { collection.save({'x':1, 'a':2}, function(err, doc) { collection.find({}, {'fields':{'x':0}}, function(err, cursor) { cursor.toArray(function(err, items) { test.equal(1, items.length); test.equal(2, items[0].a); test.equal(null, items[0].x); finished_test({test_count_with_fields_using_exclude:'ok'}); }); }); }); }); }, // Gridstore tests test_gs_exist : function() { var gridStore = new GridStore(client, "foobar", "w"); gridStore.open(function(err, gridStore) { gridStore.write("hello world!", function(err, gridStore) { gridStore.close(function(err, result) { GridStore.exist(client, 'foobar', function(err, result) { test.equal(true, result); }); GridStore.exist(client, 'does_not_exist', function(err, result) { test.equal(false, result); }); GridStore.exist(client, 'foobar', 'another_root', function(err, result) { test.equal(false, result); finished_test({test_gs_exist:'ok'}); }); }); }); }); }, test_gs_list : function() { var gridStore = new GridStore(client, "foobar2", "w"); gridStore.open(function(err, gridStore) { gridStore.write("hello world!", function(err, gridStore) { gridStore.close(function(err, result) { GridStore.list(client, function(err, items) { var found = false; items.forEach(function(filename) { if(filename == 'foobar2') found = true; }); test.ok(items.length >= 1); test.ok(found); }); GridStore.list(client, 'fs', function(err, items) { var found = false; items.forEach(function(filename) { if(filename == 'foobar2') found = true; }); test.ok(items.length >= 1); test.ok(found); }); GridStore.list(client, 'my_fs', function(err, items) { var found = false; items.forEach(function(filename) { if(filename == 'foobar2') found = true; }); test.ok(items.length >= 0); test.ok(!found); var gridStore2 = new GridStore(client, "foobar3", "w"); gridStore2.open(function(err, gridStore) { gridStore2.write('my file', function(err, gridStore) { gridStore.close(function(err, result) { GridStore.list(client, function(err, items) { var found = false; var found2 = false; items.forEach(function(filename) { if(filename == 'foobar2') found = true; if(filename == 'foobar3') found2 = true; }); test.ok(items.length >= 2); test.ok(found); test.ok(found2); finished_test({test_gs_list:'ok'}); }); }); }); }); }); }); }); }); }, test_gs_small_write : function() { var gridStore = new GridStore(client, "test_gs_small_write", "w"); gridStore.open(function(err, gridStore) { gridStore.write("hello world!", function(err, gridStore) { gridStore.close(function(err, result) { client.collection('fs.files', function(err, collection) { collection.find({'filename':'test_gs_small_write'}, function(err, cursor) { cursor.toArray(function(err, items) { test.equal(1, items.length); var item = items[0]; test.ok(item._id instanceof ObjectID || Object.prototype.toString.call(item._id) === '[object ObjectID]'); client.collection('fs.chunks', function(err, collection) { collection.find({'files_id':item._id}, function(err, cursor) { cursor.toArray(function(err, items) { test.equal(1, items.length); finished_test({test_gs_small_write:'ok'}); }) }); }); }); }); }); }); }); }); }, test_gs_small_write_with_buffer : function() { var gridStore = new GridStore(client, "test_gs_small_write_with_buffer", "w"); gridStore.open(function(err, gridStore) { var data = new Buffer("hello world", "utf8"); gridStore.writeBuffer(data, function(err, gridStore) { gridStore.close(function(err, result) { client.collection('fs.files', function(err, collection) { collection.find({'filename':'test_gs_small_write_with_buffer'}, function(err, cursor) { cursor.toArray(function(err, items) { test.equal(1, items.length); var item = items[0]; test.ok(item._id instanceof ObjectID || Object.prototype.toString.call(item._id) === '[object ObjectID]'); client.collection('fs.chunks', function(err, collection) { collection.find({'files_id':item._id}, function(err, cursor) { cursor.toArray(function(err, items) { test.equal(1, items.length); finished_test({test_gs_small_write_with_buffer:'ok'}); }) }); }); }); }); }); }); }); }); }, test_gs_small_file : function() { var gridStore = new GridStore(client, "test_gs_small_file", "w"); gridStore.open(function(err, gridStore) { gridStore.write("hello world!", function(err, gridStore) { gridStore.close(function(err, result) { client.collection('fs.files', function(err, collection) { collection.find({'filename':'test_gs_small_file'}, function(err, cursor) { cursor.toArray(function(err, items) { test.equal(1, items.length); // Read test of the file GridStore.read(client, 'test_gs_small_file', function(err, data) { test.equal('hello world!', data); finished_test({test_gs_small_file:'ok'}); }); }); }); }); }); }); }); }, test_gs_overwrite : function() { var gridStore = new GridStore(client, "test_gs_overwrite", "w"); gridStore.open(function(err, gridStore) { gridStore.write("hello world!", function(err, gridStore) { gridStore.close(function(err, result) { var gridStore2 = new GridStore(client, "test_gs_overwrite", "w"); gridStore2.open(function(err, gridStore) { gridStore2.write("overwrite", function(err, gridStore) { gridStore2.close(function(err, result) { // Assert that we have overwriten the data GridStore.read(client, 'test_gs_overwrite', function(err, data) { test.equal('overwrite', data); finished_test({test_gs_overwrite:'ok'}); }); }); }); }); }); }); }); }, test_gs_read_length : function() { var gridStore = new GridStore(client, "test_gs_read_length", "w"); gridStore.open(function(err, gridStore) { gridStore.write("hello world!", function(err, gridStore) { gridStore.close(function(err, result) { // Assert that we have overwriten the data GridStore.read(client, 'test_gs_read_length', 5, function(err, data) { test.equal('hello', data); finished_test({test_gs_read_length:'ok'}); }); }); }); }); }, test_gs_read_with_offset : function() { var gridStore = new GridStore(client, "test_gs_read_with_offset", "w"); gridStore.open(function(err, gridStore) { gridStore.write("hello, world!", function(err, gridStore) { gridStore.close(function(err, result) { // Assert that we have overwriten the data GridStore.read(client, 'test_gs_read_with_offset', 5, 7, function(err, data) { test.equal('world', data); }); GridStore.read(client, 'test_gs_read_with_offset', null, 7, function(err, data) { test.equal('world!', data); finished_test({test_gs_read_with_offset:'ok'}); }); }); }); }); }, test_gs_seek_with_buffer : function() { var gridStore = new GridStore(client, "test_gs_seek_with_buffer", "w"); gridStore.open(function(err, gridStore) { var data = new Buffer("hello, world!", "utf8"); gridStore.writeBuffer(data, function(err, gridStore) { gridStore.close(function(result) { var gridStore2 = new GridStore(client, "test_gs_seek_with_buffer", "r"); gridStore2.open(function(err, gridStore) { gridStore.seek(0, function(err, gridStore) { gridStore.getc(function(err, chr) { test.equal('h', chr); }); }); }); var gridStore3 = new GridStore(client, "test_gs_seek_with_buffer", "r"); gridStore3.open(function(err, gridStore) { gridStore.seek(7, function(err, gridStore) { gridStore.getc(function(err, chr) { test.equal('w', chr); }); }); }); var gridStore4 = new GridStore(client, "test_gs_seek_with_buffer", "r"); gridStore4.open(function(err, gridStore) { gridStore.seek(4, function(err, gridStore) { gridStore.getc(function(err, chr) { test.equal('o', chr); }); }); }); var gridStore5 = new GridStore(client, "test_gs_seek_with_buffer", "r"); gridStore5.open(function(err, gridStore) { gridStore.seek(-1, GridStore.IO_SEEK_END, function(err, gridStore) { gridStore.getc(function(err, chr) { test.equal('!', chr); }); }); }); var gridStore6 = new GridStore(client, "test_gs_seek_with_buffer", "r"); gridStore6.open(function(err, gridStore) { gridStore.seek(-6, GridStore.IO_SEEK_END, function(err, gridStore) { gridStore.getc(function(err, chr) { test.equal('w', chr); }); }); }); var gridStore7 = new GridStore(client, "test_gs_seek_with_buffer", "r"); gridStore7.open(function(err, gridStore) { gridStore.seek(7, GridStore.IO_SEEK_CUR, function(err, gridStore) { gridStore.getc(function(err, chr) { test.equal('w', chr); gridStore.seek(-1, GridStore.IO_SEEK_CUR, function(err, gridStore) { gridStore.getc(function(err, chr) { test.equal('w', chr); gridStore.seek(-4, GridStore.IO_SEEK_CUR, function(err, gridStore) { gridStore.getc(function(err, chr) { test.equal('o', chr); gridStore.seek(3, GridStore.IO_SEEK_CUR, function(err, gridStore) { gridStore.getc(function(err, chr) { test.equal('o', chr); finished_test({test_gs_seek_with_buffer:'ok'}); }); }); }); }); }); }); }); }); }); }); }); }); }, test_gs_seek : function() { var gridStore = new GridStore(client, "test_gs_seek", "w"); gridStore.open(function(err, gridStore) { gridStore.write("hello, world!", function(err, gridStore) { gridStore.close(function(result) { var gridStore2 = new GridStore(client, "test_gs_seek", "r"); gridStore2.open(function(err, gridStore) { gridStore.seek(0, function(err, gridStore) { gridStore.getc(function(err, chr) { test.equal('h', chr); }); }); }); var gridStore3 = new GridStore(client, "test_gs_seek", "r"); gridStore3.open(function(err, gridStore) { gridStore.seek(7, function(err, gridStore) { gridStore.getc(function(err, chr) { test.equal('w', chr); }); }); }); var gridStore4 = new GridStore(client, "test_gs_seek", "r"); gridStore4.open(function(err, gridStore) { gridStore.seek(4, function(err, gridStore) { gridStore.getc(function(err, chr) { test.equal('o', chr); }); }); }); var gridStore5 = new GridStore(client, "test_gs_seek", "r"); gridStore5.open(function(err, gridStore) { gridStore.seek(-1, GridStore.IO_SEEK_END, function(err, gridStore) { gridStore.getc(function(err, chr) { test.equal('!', chr); }); }); }); var gridStore6 = new GridStore(client, "test_gs_seek", "r"); gridStore6.open(function(err, gridStore) { gridStore.seek(-6, GridStore.IO_SEEK_END, function(err, gridStore) { gridStore.getc(function(err, chr) { test.equal('w', chr); }); }); }); var gridStore7 = new GridStore(client, "test_gs_seek", "r"); gridStore7.open(function(err, gridStore) { gridStore.seek(7, GridStore.IO_SEEK_CUR, function(err, gridStore) { gridStore.getc(function(err, chr) { test.equal('w', chr); gridStore.seek(-1, GridStore.IO_SEEK_CUR, function(err, gridStore) { gridStore.getc(function(err, chr) { test.equal('w', chr); gridStore.seek(-4, GridStore.IO_SEEK_CUR, function(err, gridStore) { gridStore.getc(function(err, chr) { test.equal('o', chr); gridStore.seek(3, GridStore.IO_SEEK_CUR, function(err, gridStore) { gridStore.getc(function(err, chr) { test.equal('o', chr); finished_test({test_gs_seek:'ok'}); }); }); }); }); }); }); }); }); }); }); }); }); }, test_gs_multi_chunk : function() { var fs_client = new Db('integration_tests_10', new Server("127.0.0.1", 27017, {auto_reconnect: false})); fs_client.bson_deserializer = client.bson_deserializer; fs_client.bson_serializer = client.bson_serializer; fs_client.pkFactory = client.pkFactory; fs_client.open(function(err, fs_client) { fs_client.dropDatabase(function(err, done) { var gridStore = new GridStore(fs_client, "test_gs_multi_chunk", "w"); gridStore.open(function(err, gridStore) { gridStore.chunkSize = 512; var file1 = ''; var file2 = ''; var file3 = ''; for(var i = 0; i < gridStore.chunkSize; i++) { file1 = file1 + 'x'; } for(var i = 0; i < gridStore.chunkSize; i++) { file2 = file2 + 'y'; } for(var i = 0; i < gridStore.chunkSize; i++) { file3 = file3 + 'z'; } gridStore.write(file1, function(err, gridStore) { gridStore.write(file2, function(err, gridStore) { gridStore.write(file3, function(err, gridStore) { gridStore.close(function(err, result) { fs_client.collection('fs.chunks', function(err, collection) { collection.count(function(err, count) { test.equal(3, count); GridStore.read(fs_client, 'test_gs_multi_chunk', function(err, data) { test.equal(512*3, data.length); finished_test({test_gs_multi_chunk:'ok'}); fs_client.close(); }); }) }); }); }); }); }); }); }); }); }, test_gs_puts_and_readlines : function() { var gridStore = new GridStore(client, "test_gs_puts_and_readlines", "w"); gridStore.open(function(err, gridStore) { gridStore.puts("line one", function(err, gridStore) { gridStore.puts("line two\n", function(err, gridStore) { gridStore.puts("line three", function(err, gridStore) { gridStore.close(function(err, result) { GridStore.readlines(client, 'test_gs_puts_and_readlines', function(err, lines) { test.deepEqual(["line one\n", "line two\n", "line three\n"], lines); finished_test({test_gs_puts_and_readlines:'ok'}); }); }); }); }); }); }); }, test_gs_weird_name_unlink : function() { var fs_client = new Db('awesome_f0eabd4b52e30b223c010000', new Server("127.0.0.1", 27017, {auto_reconnect: false})); fs_client.bson_deserializer = client.bson_deserializer; fs_client.bson_serializer = client.bson_serializer; fs_client.pkFactory = client.pkFactory; fs_client.open(function(err, fs_client) { fs_client.dropDatabase(function(err, done) { var gridStore = new GridStore(fs_client, "9476700.937375426_1271170118964-clipped.png", "w", {'root':'articles'}); gridStore.open(function(err, gridStore) { gridStore.write("hello, world!", function(err, gridStore) { gridStore.close(function(err, result) { fs_client.collection('articles.files', function(err, collection) { collection.count(function(err, count) { test.equal(1, count); }) }); fs_client.collection('articles.chunks', function(err, collection) { collection.count(function(err, count) { test.equal(1, count); // Unlink the file GridStore.unlink(fs_client, '9476700.937375426_1271170118964-clipped.png', {'root':'articles'}, function(err, gridStore) { fs_client.collection('articles.files', function(err, collection) { collection.count(function(err, count) { test.equal(0, count); }) }); fs_client.collection('articles.chunks', function(err, collection) { collection.count(function(err, count) { test.equal(0, count); finished_test({test_gs_weird_name_unlink:'ok'}); fs_client.close(); }) }); }); }) }); }); }); }); }); }); }, test_gs_unlink : function() { var fs_client = new Db('integration_tests_11', new Server("127.0.0.1", 27017, {auto_reconnect: false})); fs_client.bson_deserializer = client.bson_deserializer; fs_client.bson_serializer = client.bson_serializer; fs_client.pkFactory = client.pkFactory; fs_client.open(function(err, fs_client) { fs_client.dropDatabase(function(err, done) { var gridStore = new GridStore(fs_client, "test_gs_unlink", "w"); gridStore.open(function(err, gridStore) { gridStore.write("hello, world!", function(err, gridStore) { gridStore.close(function(err, result) { fs_client.collection('fs.files', function(err, collection) { collection.count(function(err, count) { test.equal(1, count); }) }); fs_client.collection('fs.chunks', function(err, collection) { collection.count(function(err, count) { test.equal(1, count); // Unlink the file GridStore.unlink(fs_client, 'test_gs_unlink', function(err, gridStore) { fs_client.collection('fs.files', function(err, collection) { collection.count(function(err, count) { test.equal(0, count); }) }); fs_client.collection('fs.chunks', function(err, collection) { collection.count(function(err, count) { test.equal(0, count); finished_test({test_gs_unlink:'ok'}); fs_client.close(); }) }); }); }) }); }); }); }); }); }); }, test_gs_unlink_as_array : function() { var fs_client = new Db('integration_tests_11', new Server("127.0.0.1", 27017, {auto_reconnect: false})); fs_client.bson_deserializer = client.bson_deserializer; fs_client.bson_serializer = client.bson_serializer; fs_client.pkFactory = client.pkFactory; fs_client.open(function(err, fs_client) { fs_client.dropDatabase(function(err, done) { var gridStore = new GridStore(fs_client, "test_gs_unlink_as_array", "w"); gridStore.open(function(err, gridStore) { gridStore.write("hello, world!", function(err, gridStore) { gridStore.close(function(err, result) { fs_client.collection('fs.files', function(err, collection) { collection.count(function(err, count) { test.equal(1, count); }) }); fs_client.collection('fs.chunks', function(err, collection) { collection.count(function(err, count) { test.equal(1, count); // Unlink the file GridStore.unlink(fs_client, ['test_gs_unlink_as_array'], function(err, gridStore) { fs_client.collection('fs.files', function(err, collection) { collection.count(function(err, count) { test.equal(0, count); }) }); fs_client.collection('fs.chunks', function(err, collection) { collection.count(function(err, count) { test.equal(0, count); finished_test({test_gs_unlink_as_array:'ok'}); fs_client.close(); }) }); }); }) }); }); }); }); }); }); }, test_gs_append : function() { var fs_client = new Db('integration_tests_12', new Server("127.0.0.1", 27017, {auto_reconnect: false})); fs_client.bson_deserializer = client.bson_deserializer; fs_client.bson_serializer = client.bson_serializer; fs_client.pkFactory = client.pkFactory; fs_client.open(function(err, fs_client) { fs_client.dropDatabase(function(err, done) { var gridStore = new GridStore(fs_client, "test_gs_append", "w"); gridStore.open(function(err, gridStore) { gridStore.write("hello, world!", function(err, gridStore) { gridStore.close(function(err, result) { var gridStore2 = new GridStore(fs_client, "test_gs_append", "w+"); gridStore2.open(function(err, gridStore) { gridStore.write(" how are you?", function(err, gridStore) { gridStore.close(function(err, result) { fs_client.collection('fs.chunks', function(err, collection) { collection.count(function(err, count) { test.equal(1, count); GridStore.read(fs_client, 'test_gs_append', function(err, data) { test.equal("hello, world! how are you?", data); finished_test({test_gs_append:'ok'}); fs_client.close(); }); }); }); }); }); }); }); }); }); }); }); }, test_gs_rewind_and_truncate_on_write : function() { var gridStore = new GridStore(client, "test_gs_rewind_and_truncate_on_write", "w"); gridStore.open(function(err, gridStore) { gridStore.write("hello, world!", function(err, gridStore) { gridStore.close(function(err, result) { var gridStore2 = new GridStore(client, "test_gs_rewind_and_truncate_on_write", "w"); gridStore2.open(function(err, gridStore) { gridStore.write('some text is inserted here', function(err, gridStore) { gridStore.rewind(function(err, gridStore) { gridStore.write('abc', function(err, gridStore) { gridStore.close(function(err, result) { GridStore.read(client, 'test_gs_rewind_and_truncate_on_write', function(err, data) { test.equal("abc", data); finished_test({test_gs_rewind_and_truncate_on_write:'ok'}); }); }); }); }); }); }); }); }); }); }, test_gs_tell : function() { var gridStore = new GridStore(client, "test_gs_tell", "w"); gridStore.open(function(err, gridStore) { gridStore.write("hello, world!", function(err, gridStore) { gridStore.close(function(err, result) { var gridStore2 = new GridStore(client, "test_gs_tell", "r"); gridStore2.open(function(err, gridStore) { gridStore.read(5, function(err, data) { test.equal("hello", data); gridStore.tell(function(err, position) { test.equal(5, position); finished_test({test_gs_tell:'ok'}); }) }); }); }); }); }); }, test_gs_save_empty_file : function() { var fs_client = new Db('integration_tests_13', new Server("127.0.0.1", 27017, {auto_reconnect: false})); fs_client.bson_deserializer = client.bson_deserializer; fs_client.bson_serializer = client.bson_serializer; fs_client.pkFactory = client.pkFactory; fs_client.open(function(err, fs_client) { fs_client.dropDatabase(function(err, done) { var gridStore = new GridStore(fs_client, "test_gs_save_empty_file", "w"); gridStore.open(function(err, gridStore) { gridStore.write("", function(err, gridStore) { gridStore.close(function(err, result) { fs_client.collection('fs.files', function(err, collection) { collection.count(function(err, count) { test.equal(1, count); }); }); fs_client.collection('fs.chunks', function(err, collection) { collection.count(function(err, count) { test.equal(0, count); finished_test({test_gs_save_empty_file:'ok'}); fs_client.close(); }); }); }); }); }); }); }); }, test_gs_empty_file_eof : function() { var gridStore = new GridStore(client, 'test_gs_empty_file_eof', "w"); gridStore.open(function(err, gridStore) { gridStore.close(function(err, gridStore) { var gridStore2 = new GridStore(client, 'test_gs_empty_file_eof', "r"); gridStore2.open(function(err, gridStore) { test.equal(true, gridStore.eof()); finished_test({test_gs_empty_file_eof:'ok'}); }) }); }); }, test_gs_cannot_change_chunk_size_on_read : function() { var gridStore = new GridStore(client, "test_gs_cannot_change_chunk_size_on_read", "w"); gridStore.open(function(err, gridStore) { gridStore.write("hello, world!", function(err, gridStore) { gridStore.close(function(err, result) { var gridStore2 = new GridStore(client, "test_gs_cannot_change_chunk_size_on_read", "r"); gridStore2.open(function(err, gridStore) { gridStore.chunkSize = 42; test.equal(Chunk.DEFAULT_CHUNK_SIZE, gridStore.chunkSize); finished_test({test_gs_cannot_change_chunk_size_on_read:'ok'}); }); }); }); }); }, test_gs_cannot_change_chunk_size_after_data_written : function() { var gridStore = new GridStore(client, "test_gs_cannot_change_chunk_size_after_data_written", "w"); gridStore.open(function(err, gridStore) { gridStore.write("hello, world!", function(err, gridStore) { gridStore.chunkSize = 42; test.equal(Chunk.DEFAULT_CHUNK_SIZE, gridStore.chunkSize); finished_test({test_gs_cannot_change_chunk_size_after_data_written:'ok'}); }); }); }, // checks if 8 bit values will be preserved in gridstore test_gs_check_high_bits : function() { var gridStore = new GridStore(client, "test_gs_check_high_bits", "w"); var data = new Buffer(255); for(var i=0; i<255; i++){ data[i] = i; } gridStore.open(function(err, gridStore) { gridStore.write(data, function(err, gridStore) { gridStore.close(function(err, result) { // Assert that we have overwriten the data GridStore.read(client, 'test_gs_check_high_bits', function(err, fileData) { // change testvalue into a string like "0,1,2,...,255" test.equal(Array.prototype.join.call(data), Array.prototype.join.call(new Buffer(fileData, "binary"))); finished_test({test_gs_check_high_bits:'ok'}); }); }); }); }); }, test_change_chunk_size : function() { var gridStore = new GridStore(client, "test_change_chunk_size", "w"); gridStore.open(function(err, gridStore) { gridStore.chunkSize = 42 gridStore.write('foo', function(err, gridStore) { gridStore.close(function(err, result) { var gridStore2 = new GridStore(client, "test_change_chunk_size", "r"); gridStore2.open(function(err, gridStore) { test.equal(42, gridStore.chunkSize); finished_test({test_change_chunk_size:'ok'}); }); }); }); }); }, test_gs_chunk_size_in_option : function() { var gridStore = new GridStore(client, "test_change_chunk_size", "w", {'chunk_size':42}); gridStore.open(function(err, gridStore) { gridStore.write('foo', function(err, gridStore) { gridStore.close(function(err, result) { var gridStore2 = new GridStore(client, "test_change_chunk_size", "r"); gridStore2.open(function(err, gridStore) { test.equal(42, gridStore.chunkSize); finished_test({test_gs_chunk_size_in_option:'ok'}); }); }); }); }); }, test_gs_md5 : function() { var gridStore = new GridStore(client, "new-file", "w"); gridStore.open(function(err, gridStore) { gridStore.write('hello world\n', function(err, gridStore) { gridStore.close(function(err, result) { var gridStore2 = new GridStore(client, "new-file", "r"); gridStore2.open(function(err, gridStore) { test.equal("6f5902ac237024bdd0c176cb93063dc4", gridStore.md5); gridStore.md5 = "can't do this"; test.equal("6f5902ac237024bdd0c176cb93063dc4", gridStore.md5); var gridStore2 = new GridStore(client, "new-file", "w"); gridStore2.open(function(err, gridStore) { gridStore.close(function(err, result) { var gridStore3 = new GridStore(client, "new-file", "r"); gridStore3.open(function(err, gridStore) { test.equal("d41d8cd98f00b204e9800998ecf8427e", gridStore.md5); finished_test({test_gs_chunk_size_in_option:'ok'}); }); }) }) }); }); }); }); }, test_gs_upload_date : function() { var now = new Date(); var originalFileUploadDate = null; var gridStore = new GridStore(client, "test_gs_upload_date", "w"); gridStore.open(function(err, gridStore) { gridStore.write('hello world\n', function(err, gridStore) { gridStore.close(function(err, result) { var gridStore2 = new GridStore(client, "test_gs_upload_date", "r"); gridStore2.open(function(err, gridStore) { test.ok(gridStore.uploadDate != null); originalFileUploadDate = gridStore.uploadDate; gridStore2.close(function(err, result) { var gridStore3 = new GridStore(client, "test_gs_upload_date", "w"); gridStore3.open(function(err, gridStore) { gridStore3.write('new data', function(err, gridStore) { gridStore3.close(function(err, result) { var fileUploadDate = null; var gridStore4 = new GridStore(client, "test_gs_upload_date", "r"); gridStore4.open(function(err, gridStore) { test.equal(originalFileUploadDate.getTime(), gridStore.uploadDate.getTime()); finished_test({test_gs_upload_date:'ok'}); }); }); }); }); }); }); }); }); }); }, test_gs_content_type : function() { var ct = null; var gridStore = new GridStore(client, "test_gs_content_type", "w"); gridStore.open(function(err, gridStore) { gridStore.write('hello world\n', function(err, gridStore) { gridStore.close(function(err, result) { var gridStore2 = new GridStore(client, "test_gs_content_type", "r"); gridStore2.open(function(err, gridStore) { ct = gridStore.contentType; test.equal(GridStore.DEFAULT_CONTENT_TYPE, ct); var gridStore3 = new GridStore(client, "test_gs_content_type", "w+"); gridStore3.open(function(err, gridStore) { gridStore.contentType = "text/html"; gridStore.close(function(err, result) { var gridStore4 = new GridStore(client, "test_gs_content_type", "r"); gridStore4.open(function(err, gridStore) { test.equal("text/html", gridStore.contentType); finished_test({test_gs_content_type:'ok'}); }); }) }); }); }); }); }); }, test_gs_content_type_option : function() { var gridStore = new GridStore(client, "test_gs_content_type_option", "w", {'content_type':'image/jpg'}); gridStore.open(function(err, gridStore) { gridStore.write('hello world\n', function(err, gridStore) { gridStore.close(function(result) { var gridStore2 = new GridStore(client, "test_gs_content_type_option", "r"); gridStore2.open(function(err, gridStore) { test.equal('image/jpg', gridStore.contentType); finished_test({test_gs_content_type_option:'ok'}); }); }); }); }); }, test_gs_unknown_mode : function() { var gridStore = new GridStore(client, "test_gs_unknown_mode", "x"); gridStore.open(function(err, gridStore) { test.ok(err instanceof Error); test.equal("Illegal mode x", err.message); finished_test({test_gs_unknown_mode:'ok'}); }); }, test_gs_metadata : function() { var gridStore = new GridStore(client, "test_gs_metadata", "w", {'content_type':'image/jpg'}); gridStore.open(function(err, gridStore) { gridStore.write('hello world\n', function(err, gridStore) { gridStore.close(function(err, result) { var gridStore2 = new GridStore(client, "test_gs_metadata", "r"); gridStore2.open(function(err, gridStore) { test.equal(null, gridStore.metadata); var gridStore3 = new GridStore(client, "test_gs_metadata", "w+"); gridStore3.open(function(err, gridStore) { gridStore.metadata = {'a':1}; gridStore.close(function(err, result) { var gridStore4 = new GridStore(client, "test_gs_metadata", "r"); gridStore4.open(function(err, gridStore) { test.equal(1, gridStore.metadata.a); finished_test({test_gs_metadata:'ok'}); }); }); }); }); }); }); }); }, test_admin_default_profiling_level : function() { var fs_client = new Db('admin_test_1', new Server("127.0.0.1", 27017, {auto_reconnect: false})); fs_client.bson_deserializer = client.bson_deserializer; fs_client.bson_serializer = client.bson_serializer; fs_client.pkFactory = client.pkFactory; fs_client.open(function(err, fs_client) { fs_client.dropDatabase(function(err, done) { fs_client.collection('test', function(err, collection) { collection.insert({'a':1}, function(err, doc) { fs_client.admin(function(err, adminDb) { adminDb.profilingLevel(function(err, level) { test.equal("off", level); finished_test({test_admin_default_profiling_level:'ok'}); fs_client.close(); }); }); }); }); }); }); }, test_admin_change_profiling_level : function() { var fs_client = new Db('admin_test_2', new Server("127.0.0.1", 27017, {auto_reconnect: false})); fs_client.bson_deserializer = client.bson_deserializer; fs_client.bson_serializer = client.bson_serializer; fs_client.pkFactory = client.pkFactory; fs_client.open(function(err, fs_client) { fs_client.dropDatabase(function(err, done) { fs_client.collection('test', function(err, collection) { collection.insert({'a':1}, function(err, doc) { fs_client.admin(function(err, adminDb) { adminDb.setProfilingLevel('slow_only', function(err, level) { adminDb.profilingLevel(function(err, level) { test.equal('slow_only', level); adminDb.setProfilingLevel('off', function(err, level) { adminDb.profilingLevel(function(err, level) { test.equal('off', level); adminDb.setProfilingLevel('all', function(err, level) { adminDb.profilingLevel(function(err, level) { test.equal('all', level); adminDb.setProfilingLevel('medium', function(err, level) { test.ok(err instanceof Error); test.equal("Error: illegal profiling level value medium", err.message); finished_test({test_admin_change_profiling_level:'ok'}); fs_client.close(); }); }) }); }) }); }) }); }); }); }); }); }); }, test_admin_profiling_info : function() { var fs_client = new Db('admin_test_3', new Server("127.0.0.1", 27017, {auto_reconnect: false})); fs_client.bson_deserializer = client.bson_deserializer; fs_client.bson_serializer = client.bson_serializer; fs_client.pkFactory = client.pkFactory; fs_client.open(function(err, fs_client) { fs_client.dropDatabase(function(err, done) { fs_client.collection('test', function(err, collection) { collection.insert({'a':1}, function(doc) { fs_client.admin(function(err, adminDb) { adminDb.setProfilingLevel('all', function(err, level) { collection.find(function(err, cursor) { cursor.toArray(function(err, items) { adminDb.setProfilingLevel('off', function(err, level) { adminDb.profilingInfo(function(err, infos) { test.ok(infos.constructor == Array); test.ok(infos.length >= 1); test.ok(infos[0].ts.constructor == Date); test.ok(infos[0].info.constructor == String); test.ok(infos[0].millis.constructor == Number); finished_test({test_admin_profiling_info:'ok'}); fs_client.close(); }); }); }); }); }); }); }); }); }); }); }, test_admin_validate_collection : function() { var fs_client = new Db('admin_test_4', new Server("127.0.0.1", 27017, {auto_reconnect: false})); fs_client.bson_deserializer = client.bson_deserializer; fs_client.bson_serializer = client.bson_serializer; fs_client.pkFactory = client.pkFactory; fs_client.open(function(err, fs_client) { fs_client.dropDatabase(function(err, done) { fs_client.collection('test', function(err, collection) { collection.insert({'a':1}, function(err, doc) { fs_client.admin(function(err, adminDb) { adminDb.validateCollection('test', function(err, doc) { test.ok(doc.result != null); test.ok(doc.result.match(/firstExtent/) != null); finished_test({test_admin_validate_collection:'ok'}); fs_client.close(); }); }); }); }); }); }); }, test_custom_primary_key_generator : function() { // Custom factory (need to provide a 12 byte array); CustomPKFactory = function() {} CustomPKFactory.prototype = new Object(); CustomPKFactory.createPk = function() { return new client.bson_serializer.ObjectID("aaaaaaaaaaaa"); } var p_client = new Db('integration_tests_20', new Server("127.0.0.1", 27017, {}), {'pk':CustomPKFactory}); p_client.bson_deserializer = client.bson_deserializer; p_client.bson_serializer = client.bson_serializer; p_client.open(function(err, p_client) { p_client.dropDatabase(function(err, done) { p_client.createCollection('test_custom_key', function(err, collection) { collection.insert({'a':1}, function(err, doc) { collection.find({'_id':new client.bson_serializer.ObjectID("aaaaaaaaaaaa")}, function(err, cursor) { cursor.toArray(function(err, items) { test.equal(1, items.length); finished_test({test_custom_primary_key_generator:'ok'}); p_client.close(); }); }); }); }); }); }); }, // Mapreduce tests functions test_map_reduce_functions : function() { client.createCollection('test_map_reduce_functions', function(err, collection) { collection.insert([{'user_id':1}, {'user_id':2}]); // String functions var map = function() { emit(this.user_id, 1); }; var reduce = function(k,vals) { return 1; }; collection.mapReduce(map, reduce, function(err, collection) { collection.findOne({'_id':1}, function(err, result) { test.equal(1, result.value); }); collection.findOne({'_id':2}, function(err, result) { test.equal(1, result.value); finished_test({test_map_reduce_functions:'ok'}); }); }); }); }, //map/reduce inline option test test_map_reduce_functions_inline : function() { client.createCollection('test_map_reduce_functions_inline', function(err, collection) { collection.insert([{'user_id':1}, {'user_id':2}]); // String functions var map = function() { emit(this.user_id, 1); }; var reduce = function(k,vals) { return 1; }; collection.mapReduce(map, reduce, {out : {inline: 1}}, function(err, results) { test.equal(2, results.length); finished_test({test_map_reduce_functions_inline:'ok'}); }); }); }, // Mapreduce different test test_map_reduce_functions_scope : function() { client.createCollection('test_map_reduce_functions_scope', function(err, collection) { collection.insert([{'user_id':1, 'timestamp':new Date()}, {'user_id':2, 'timestamp':new Date()}]); var map = function(){ emit(test(this.timestamp.getYear()), 1); } var reduce = function(k, v){ count = 0; for(i = 0; i < v.length; i++) { count += v[i]; } return count; } var t = function(val){ return val+1; } collection.mapReduce(map, reduce, {scope:{test:new client.bson_serializer.Code(t.toString())}}, function(err, collection) { collection.find(function(err, cursor) { cursor.toArray(function(err, results) { test.equal(2, results[0].value) finished_test({test_map_reduce_functions_scope:'ok'}); }) }) }); }); }, // Mapreduce tests test_map_reduce : function() { client.createCollection('test_map_reduce', function(err, collection) { collection.insert([{'user_id':1}, {'user_id':2}]); // String functions var map = "function() { emit(this.user_id, 1); }"; var reduce = "function(k,vals) { return 1; }"; collection.mapReduce(map, reduce, function(err, collection) { collection.findOne({'_id':1}, function(err, result) { test.equal(1, result.value); }); collection.findOne({'_id':2}, function(err, result) { test.equal(1, result.value); finished_test({test_map_reduce:'ok'}); }); }); }); }, test_map_reduce_with_functions_as_arguments : function() { client.createCollection('test_map_reduce_with_functions_as_arguments', function(err, collection) { collection.insert([{'user_id':1}, {'user_id':2}]); // String functions var map = function() { emit(this.user_id, 1); }; var reduce = function(k,vals) { return 1; }; collection.mapReduce(map, reduce, function(err, collection) { collection.findOne({'_id':1}, function(err, result) { test.equal(1, result.value); }); collection.findOne({'_id':2}, function(err, result) { test.equal(1, result.value); finished_test({test_map_reduce_with_functions_as_arguments:'ok'}); }); }); }); }, test_map_reduce_with_code_objects : function() { client.createCollection('test_map_reduce_with_code_objects', function(err, collection) { collection.insert([{'user_id':1}, {'user_id':2}]); // String functions var map = new client.bson_serializer.Code("function() { emit(this.user_id, 1); }"); var reduce = new client.bson_serializer.Code("function(k,vals) { return 1; }"); collection.mapReduce(map, reduce, function(err, collection) { collection.findOne({'_id':1}, function(err, result) { test.equal(1, result.value); }); collection.findOne({'_id':2}, function(err, result) { test.equal(1, result.value); finished_test({test_map_reduce_with_code_objects:'ok'}); }); }); }); }, test_map_reduce_with_options : function() { client.createCollection('test_map_reduce_with_options', function(err, collection) { collection.insert([{'user_id':1}, {'user_id':2}, {'user_id':3}]); // String functions var map = new client.bson_serializer.Code("function() { emit(this.user_id, 1); }"); var reduce = new client.bson_serializer.Code("function(k,vals) { return 1; }"); collection.mapReduce(map, reduce, {'query': {'user_id':{'$gt':1}}}, function(err, collection) { collection.count(function(err, count) { test.equal(2, count); collection.findOne({'_id':2}, function(err, result) { test.equal(1, result.value); }); collection.findOne({'_id':3}, function(err, result) { test.equal(1, result.value); finished_test({test_map_reduce_with_options:'ok'}); }); }); }); }); }, test_map_reduce_error : function() { client.createCollection('test_map_reduce_error', function(err, collection) { collection.insert([{'user_id':1}, {'user_id':2}, {'user_id':3}]); // String functions var map = new client.bson_serializer.Code("function() { emit(this.user_id, 1); }"); var reduce = new client.bson_serializer.Code("function(k,vals) { throw 'error'; }"); collection.mapReduce(map, reduce, {'query': {'user_id':{'$gt':1}}}, function(err, collection) { test.ok(err != null); finished_test({test_map_reduce_error:'ok'}); }); }); }, test_drop_indexes : function() { client.createCollection('test_drop_indexes', function(err, collection) { collection.insert({a:1}, function(err, ids) { // Create an index on the collection client.createIndex(collection.collectionName, 'a', function(err, indexName) { test.equal("a_1", indexName); // Drop all the indexes collection.dropIndexes(function(err, result) { test.equal(true, result); collection.indexInformation(function(err, result) { test.ok(result['a_1'] == null); finished_test({test_drop_indexes:'ok'}); }) }) }); }) }); }, test_add_and_remove_user : function() { var user_name = 'spongebob2'; var password = 'password'; var p_client = new Db('integration_tests_', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {}); p_client.bson_deserializer = client.bson_deserializer; p_client.bson_serializer = client.bson_serializer; p_client.pkFactory = client.pkFactory; p_client.open(function(err, automatic_connect_client) { p_client.authenticate('admin', 'admin', function(err, replies) { test.ok(err instanceof Error); // Add a user p_client.addUser(user_name, password, function(err, result) { p_client.authenticate(user_name, password, function(err, replies) { test.ok(replies); // Remove the user and try to authenticate again p_client.removeUser(user_name, function(err, result) { p_client.authenticate(user_name, password, function(err, replies) { test.ok(err instanceof Error); finished_test({test_add_and_remove_user:'ok'}); p_client.close(); }); }); }); }); }); }); }, test_distinct_queries : function() { client.createCollection('test_distinct_queries', function(err, collection) { collection.insert([{'a':0, 'b':{'c':'a'}}, {'a':1, 'b':{'c':'b'}}, {'a':1, 'b':{'c':'c'}}, {'a':2, 'b':{'c':'a'}}, {'a':3}, {'a':3}], function(err, ids) { collection.distinct('a', function(err, docs) { test.deepEqual([0, 1, 2, 3], docs.sort()); }); collection.distinct('b.c', function(err, docs) { test.deepEqual(['a', 'b', 'c'], docs.sort()); finished_test({test_distinct_queries:'ok'}); }); }) }); }, test_all_serialization_types : function() { client.createCollection('test_all_serialization_types', function(err, collection) { var date = new Date(); var oid = new client.bson_serializer.ObjectID(); var string = 'binstring' var bin = new client.bson_serializer.Binary() for(var index = 0; index < string.length; index++) { bin.put(string.charAt(index)) } var motherOfAllDocuments = { 'string': 'hello', 'array': [1,2,3], 'hash': {'a':1, 'b':2}, 'date': date, 'oid': oid, 'binary': bin, 'int': 42, 'float': 33.3333, 'regexp': /regexp/, 'boolean': true, 'long': date.getTime(), 'where': new client.bson_serializer.Code('this.a > i', {i:1}), 'dbref': new client.bson_serializer.DBRef('namespace', oid, 'integration_tests_') } collection.insert(motherOfAllDocuments, function(err, docs) { collection.findOne(function(err, doc) { // // Assert correct deserialization of the values test.equal(motherOfAllDocuments.string, doc.string); test.deepEqual(motherOfAllDocuments.array, doc.array); test.equal(motherOfAllDocuments.hash.a, doc.hash.a); test.equal(motherOfAllDocuments.hash.b, doc.hash.b); test.equal(date.getTime(), doc.long); test.equal(date.toString(), doc.date.toString()); test.equal(date.getTime(), doc.date.getTime()); test.equal(motherOfAllDocuments.oid.toHexString(), doc.oid.toHexString()); test.equal(motherOfAllDocuments.binary.value(), doc.binary.value()); test.equal(motherOfAllDocuments.int, doc.int); test.equal(motherOfAllDocuments.long, doc.long); test.equal(motherOfAllDocuments.float, doc.float); test.equal(motherOfAllDocuments.regexp.toString(), doc.regexp.toString()); test.equal(motherOfAllDocuments.boolean, doc.boolean); test.equal(motherOfAllDocuments.where.code, doc.where.code); test.equal(motherOfAllDocuments.where.scope['i'], doc.where.scope.i); test.equal(motherOfAllDocuments.dbref.namespace, doc.dbref.namespace); test.equal(motherOfAllDocuments.dbref.oid.toHexString(), doc.dbref.oid.toHexString()); test.equal(motherOfAllDocuments.dbref.db, doc.dbref.db); finished_test({test_all_serialization_types:'ok'}); }) }); }); }, test_should_correctly_retrieve_one_record : function() { var p_client = new Db('integration_tests_', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {}); p_client.bson_deserializer = client.bson_deserializer; p_client.bson_serializer = client.bson_serializer; p_client.pkFactory = client.pkFactory; p_client.open(function(err, p_client) { client.createCollection('test_should_correctly_retrieve_one_record', function(err, collection) { collection.insert({'a':0}); p_client.collection('test_should_correctly_retrieve_one_record', function(err, usercollection) { usercollection.findOne({'a': 0}, function(err, result) { finished_test({test_should_correctly_retrieve_one_record:'ok'}); p_client.close(); }); }); }); }); }, test_should_correctly_save_unicode_containing_document : function() { var doc = {statuses_count: 1687 , created_at: 'Mon Oct 22 14:55:08 +0000 2007' , description: 'NodeJS hacker, Cofounder of Debuggable, CakePHP core alumnus' , favourites_count: 6 , profile_sidebar_fill_color: 'EADEAA' , screen_name: 'felixge' , status: { created_at: 'Fri Mar 12 08:59:44 +0000 2010' , in_reply_to_screen_name: null , truncated: false , in_reply_to_user_id: null , source: '<a href="http://www.atebits.com/" rel="nofollow">Tweetie</a>' , favorited: false , in_reply_to_status_id: null , id: 10364119169 , text: '#berlin #snow = #fail : (' } , contributors_enabled: false , following: null , geo_enabled: false , time_zone: 'Eastern Time (US & Canada)' , profile_sidebar_border_color: 'D9B17E' , url: 'http://debuggable.com' , verified: false , location: 'Berlin' , profile_text_color: '333333' , notifications: null , profile_background_image_url: 'http://s.twimg.com/a/1268354287/images/themes/theme8/bg.gif' , protected: false , profile_link_color: '9D582E' , followers_count: 840 , name: 'Felix Geisend\u00f6rfer' , profile_background_tile: false , id: 9599342 , lang: 'en' , utc_offset: -18000 , friends_count: 450 , profile_background_color: '8B542B' , profile_image_url: 'http://a3.twimg.com/profile_images/107142257/passbild-square_normal.jpg' }; client.createCollection('test_should_correctly_save_unicode_containing_document', function(err, collection) { doc['_id'] = 'felixge'; collection.save(doc, function(err, doc) { collection.findOne(function(err, doc) { test.equal('felixge', doc._id); finished_test({test_should_correctly_save_unicode_containing_document:'ok'}); }); }); }); }, test_should_deserialize_large_integrated_array : function() { client.createCollection('test_should_deserialize_large_integrated_array', function(err, collection) { var doc = {'a':0, 'b':['tmp1', 'tmp2', 'tmp3', 'tmp4', 'tmp5', 'tmp6', 'tmp7', 'tmp8', 'tmp9', 'tmp10', 'tmp11', 'tmp12', 'tmp13', 'tmp14', 'tmp15', 'tmp16'] }; // Insert the collection collection.insert(doc); // Fetch and check the collection collection.findOne({'a': 0}, function(err, result) { test.deepEqual(doc.a, result.a); test.deepEqual(doc.b, result.b); finished_test({test_should_deserialize_large_integrated_array:'ok'}); }); }); }, test_find_one_error_handling : function() { client.createCollection('test_find_one_error_handling', function(err, collection) { // Try to fetch an object using a totally invalid and wrong hex string... what we're interested in here // is the error handling of the findOne Method try { collection.findOne({"_id":client.bson_serializer.ObjectID.createFromHexString('5e9bd59248305adf18ebc15703a1')}, function(err, result) {}); } catch (err) { finished_test({test_find_one_error_handling:'ok'}); } }); }, // test_force_binary_error : function() { // client.createCollection('test_force_binary_error', function(err, collection) { // // Try to fetch an object using a totally invalid and wrong hex string... what we're interested in here // // is the error handling of the findOne Method // var result= ""; // var hexString = "5e9bd59248305adf18ebc15703a1"; // for(var index=0 ; index < hexString.length; index+=2) { // var string= hexString.substr(index, 2); // var number= parseInt(string, 16); // result+= BinaryParser.fromByte(number); // } // // // Generate a illegal ID // var id = client.bson_serializer.ObjectID.createFromHexString('5e9bd59248305adf18ebc157'); // id.id = result; // // // Execute with error // collection.findOne({"_id": id}, function(err, result) { // // test.equal(undefined, result) // test.ok(err != null) // finished_test({test_force_binary_error:'ok'}); // }); // }); // }, test_gs_weird_bug : function() { var gridStore = new GridStore(client, "test_gs_weird_bug", "w"); var data = fs.readFileSync("./integration/test_gs_weird_bug.png", 'binary'); gridStore.open(function(err, gridStore) { gridStore.write(data, function(err, gridStore) { gridStore.close(function(err, result) { // Assert that we have overwriten the data GridStore.read(client, 'test_gs_weird_bug', function(err, fileData) { test.equal(data.length, fileData.length); finished_test({test_gs_weird_bug:'ok'}); }); }); }); }); }, test_gs_read_stream : function() { var gridStoreR = new GridStore(client, "test_gs_read_stream", "r"); var gridStoreW = new GridStore(client, "test_gs_read_stream", "w"); var data = fs.readFileSync("./integration/test_gs_weird_bug.png", 'binary'); var readLen = 0; var gotEnd = 0; gridStoreW.open(function(err, gs) { gs.write(data, function(err, gs) { gs.close(function(err, result) { gridStoreR.open(function(err, gs) { var stream = gs.stream(true); stream.on("data", function(chunk) { readLen += chunk.length; }); stream.on("end", function() { ++gotEnd; }); stream.on("close", function() { test.equal(data.length, readLen); test.equal(1, gotEnd); finished_test({test_gs_read_stream:'ok'}); }); }); }); }); }); }, test_gs_writing_file: function() { var gridStore = new GridStore(client, 'test_gs_writing_file', 'w'); var fileSize = fs.statSync('./integration/test_gs_weird_bug.png').size; gridStore.open(function(err, gridStore) { gridStore.writeFile('./integration/test_gs_weird_bug.png', function(err, gridStore) { GridStore.read(client, 'test_gs_writing_file', function(err, fileData) { test.equal(fileSize, fileData.length); finished_test({test_gs_writing_file: 'ok'}); }); }); }); }, test_gs_working_field_read : function() { var gridStore = new GridStore(client, "test_gs_working_field_read", "w"); var data = fs.readFileSync("./integration/test_gs_working_field_read.pdf", 'binary'); gridStore.open(function(err, gridStore) { gridStore.write(data, function(err, gridStore) { gridStore.close(function(err, result) { // Assert that we have overwriten the data GridStore.read(client, 'test_gs_working_field_read', function(err, fileData) { test.equal(data.length, fileData.length); finished_test({test_gs_working_field_read:'ok'}); }); }); }); }); }, // Test field select with options test_field_select_with_options : function() { client.createCollection('test_field_select_with_options', function(err, r) { var collection = client.collection('test_field_select_with_options', function(err, collection) { var docCount = 25, docs = []; // Insert some test documents while(docCount--) docs.push({a:docCount, b:docCount}); collection.insert(docs, function(err,retDocs){ docs = retDocs; }); collection.find({},{ 'a' : 1},{ limit : 3, sort : [['a',-1]] },function(err,cursor){ cursor.toArray(function(err,documents){ test.equal(3,documents.length); documents.forEach(function(doc,idx){ test.equal(undefined,doc.b); // making sure field select works test.equal((24-idx),doc.a); // checking limit sort object with field select }); }); }); collection.find({},{},10,3,function(err,cursor){ cursor.toArray(function(err,documents){ test.equal(3,documents.length); documents.forEach(function(doc,idx){ test.equal(doc.a,doc.b); // making sure empty field select returns properly test.equal((14-idx),doc.a); // checking skip and limit in args }); finished_test({test_field_select_with_options:'ok'}); }); }); }); }); }, // Test findAndModify a document test_find_and_modify_a_document : function() { client.createCollection('test_find_and_modify_a_document', function(err, collection) { // Test return new document on change collection.insert({'a':1, 'b':2}, function(err, doc) { // Let's modify the document in place collection.findAndModify({'a':1}, [['a', 1]], {'$set':{'b':3}}, {'new': true}, function(err, updated_doc) { test.equal(1, updated_doc.a); test.equal(3, updated_doc.b); }) }); // Test return old document on change collection.insert({'a':2, 'b':2}, function(err, doc) { // Let's modify the document in place collection.findAndModify({'a':2}, [['a', 1]], {'$set':{'b':3}}, function(err, updated_doc) { test.equal(2, updated_doc.a); test.equal(2, updated_doc.b); }) }); // Test remove object on change collection.insert({'a':3, 'b':2}, function(err, doc) { // Let's modify the document in place collection.findAndModify({'a':3}, [], {'$set':{'b':3}}, {'new': true, remove: true}, function(err, updated_doc) { test.equal(3, updated_doc.a); test.equal(2, updated_doc.b); }) }); // Let's upsert! collection.findAndModify({'a':4}, [], {'$set':{'b':3}}, {'new': true, upsert: true}, function(err, updated_doc) { test.equal(4, updated_doc.a); test.equal(3, updated_doc.b); }); // Test selecting a subset of fields collection.insert({a: 100, b: 101}, function (err, ids) { collection.findAndModify({'a': 100}, [], {'$set': {'b': 5}}, {'new': true, fields: {b: 1}}, function (err, updated_doc) { test.equal(2, Object.keys(updated_doc).length); test.equal(ids[0]['_id'].toHexString(), updated_doc._id.toHexString()); test.equal(5, updated_doc.b); test.equal("undefined", typeof updated_doc.a); finished_test({test_find_and_modify_a_document:'ok'}); }); }); }); }, // test_pair : function() { // var p_client = new Db('integration_tests_21', new ServerPair(new Server("127.0.0.1", 27017, {}), new Server("127.0.0.1", 27018, {})), {}); // p_client.open(function(err, p_client) { // p_client.dropDatabase(function(err, done) { // test.ok(p_client.masterConnection != null); // test.equal(2, p_client.connections.length); // // // Check both server running // test.equal(true, p_client.serverConfig.leftServer.connected); // test.equal(true, p_client.serverConfig.rightServer.connected); // // test.ok(p_client.serverConfig.leftServer.master); // test.equal(false, p_client.serverConfig.rightServer.master); // // p_client.createCollection('test_collection', function(err, collection) { // collection.insert({'a':1}, function(err, doc) { // collection.find(function(err, cursor) { // cursor.toArray(function(err, items) { // test.equal(1, items.length); // // finished_test({test_pair:'ok'}); // p_client.close(); // }); // }); // }); // }); // }); // }); // }, // // test_cluster : function() { // var p_client = new Db('integration_tests_22', new ServerCluster([new Server("127.0.0.1", 27017, {}), new Server("127.0.0.1", 27018, {})]), {}); // p_client.open(function(err, p_client) { // p_client.dropDatabase(function(err, done) { // test.ok(p_client.masterConnection != null); // test.equal(2, p_client.connections.length); // // test.equal(true, p_client.serverConfig.servers[0].master); // test.equal(false, p_client.serverConfig.servers[1].master); // // p_client.createCollection('test_collection', function(err, collection) { // collection.insert({'a':1}, function(err, doc) { // collection.find(function(err, cursor) { // cursor.toArray(function(err, items) { // test.equal(1, items.length); // // finished_test({test_cluster:'ok'}); // p_client.close(); // }); // }); // }); // }); // }); // }); // }, // // test_slave_connection :function() { // var p_client = new Db('integration_tests_23', new Server("127.0.0.1", 27018, {})); // p_client.open(function(err, p_client) { // test.equal(null, err); // finished_test({test_slave_connection:'ok'}); // p_client.close(); // }); // }, test_ensure_index : function() { client.createCollection('test_ensure_index', function(err, collection) { // Create an index on the collection client.ensureIndex(collection.collectionName, 'a', function(err, indexName) { test.equal("a_1", indexName); // Let's fetch the index information client.indexInformation(collection.collectionName, function(err, collectionInfo) { test.ok(collectionInfo['_id_'] != null); test.equal('_id', collectionInfo['_id_'][0][0]); test.ok(collectionInfo['a_1'] != null); test.deepEqual([["a", 1]], collectionInfo['a_1']); client.ensureIndex(collection.collectionName, 'a', function(err, indexName) { test.equal("a_1", indexName); // Let's fetch the index information client.indexInformation(collection.collectionName, function(err, collectionInfo) { test.ok(collectionInfo['_id_'] != null); test.equal('_id', collectionInfo['_id_'][0][0]); test.ok(collectionInfo['a_1'] != null); test.deepEqual([["a", 1]], collectionInfo['a_1']); // Let's close the db finished_test({test_ensure_index:'ok'}); }); }); }); }); }) }, test_insert_and_update_with_new_script_context: function() { var db = new Db('test-db', new Server('localhost', 27017, {auto_reconnect: true}, {})); db.bson_deserializer = client.bson_deserializer; db.bson_serializer = client.bson_serializer; db.pkFactory = client.pkFactory; db.open(function(err, db) { //convience curried handler for functions of type 'a -> (err, result) function getResult(callback){ return function(error, result) { test.ok(error == null); callback(result); } }; db.collection('users', getResult(function(user_collection){ user_collection.remove(function(err, result) { //first, create a user object var newUser = { name : 'Test Account', settings : {} }; user_collection.insert([newUser], getResult(function(users){ var user = users[0]; var scriptCode = "settings.block = []; settings.block.push('test');"; var context = { settings : { thisOneWorks : "somestring" } }; Script.runInNewContext(scriptCode, context, "testScript"); //now create update command and issue it var updateCommand = { $set : context }; user_collection.update({_id : user._id}, updateCommand, null, getResult(function(updateCommand) { // Fetch the object and check that the changes are persisted user_collection.findOne({_id : user._id}, function(err, doc) { test.ok(err == null); test.equal("Test Account", doc.name); test.equal("somestring", doc.settings.thisOneWorks); test.equal("test", doc.settings.block[0]); // Let's close the db finished_test({test_insert_and_update_with_new_script_context:'ok'}); db.close(); }); }) ); })); }); })); }); }, test_all_serialization_types_new_context : function() { client.createCollection('test_all_serialization_types_new_context', function(err, collection) { var date = new Date(); var scriptCode = "var string = 'binstring'\n" + "var bin = new mongo.Binary()\n" + "for(var index = 0; index < string.length; index++) {\n" + " bin.put(string.charAt(index))\n" + "}\n" + "motherOfAllDocuments['string'] = 'hello';" + "motherOfAllDocuments['array'] = [1,2,3];" + "motherOfAllDocuments['hash'] = {'a':1, 'b':2};" + "motherOfAllDocuments['date'] = date;" + "motherOfAllDocuments['oid'] = new mongo.ObjectID();" + "motherOfAllDocuments['binary'] = bin;" + "motherOfAllDocuments['int'] = 42;" + "motherOfAllDocuments['float'] = 33.3333;" + "motherOfAllDocuments['regexp'] = /regexp/;" + "motherOfAllDocuments['boolean'] = true;" + "motherOfAllDocuments['long'] = motherOfAllDocuments['date'].getTime();" + "motherOfAllDocuments['where'] = new mongo.Code('this.a > i', {i:1});" + "motherOfAllDocuments['dbref'] = new mongo.DBRef('namespace', motherOfAllDocuments['oid'], 'integration_tests_');"; var context = { motherOfAllDocuments : {}, mongo:client.bson_serializer, date:date}; // Execute function in context Script.runInNewContext(scriptCode, context, "testScript"); // sys.puts(sys.inspect(context.motherOfAllDocuments)) var motherOfAllDocuments = context.motherOfAllDocuments; collection.insert(context.motherOfAllDocuments, function(err, docs) { collection.findOne(function(err, doc) { // Assert correct deserialization of the values test.equal(motherOfAllDocuments.string, doc.string); test.deepEqual(motherOfAllDocuments.array, doc.array); test.equal(motherOfAllDocuments.hash.a, doc.hash.a); test.equal(motherOfAllDocuments.hash.b, doc.hash.b); test.equal(date.getTime(), doc.long); test.equal(date.toString(), doc.date.toString()); test.equal(date.getTime(), doc.date.getTime()); test.equal(motherOfAllDocuments.oid.toHexString(), doc.oid.toHexString()); test.equal(motherOfAllDocuments.binary.value, doc.binary.value); test.equal(motherOfAllDocuments.int, doc.int); test.equal(motherOfAllDocuments.long, doc.long); test.equal(motherOfAllDocuments.float, doc.float); test.equal(motherOfAllDocuments.regexp.toString(), doc.regexp.toString()); test.equal(motherOfAllDocuments.boolean, doc.boolean); test.equal(motherOfAllDocuments.where.code, doc.where.code); test.equal(motherOfAllDocuments.where.scope['i'], doc.where.scope.i); test.equal(motherOfAllDocuments.dbref.namespace, doc.dbref.namespace); test.equal(motherOfAllDocuments.dbref.oid.toHexString(), doc.dbref.oid.toHexString()); test.equal(motherOfAllDocuments.dbref.db, doc.dbref.db); finished_test({test_all_serialization_types_new_context:'ok'}); }) }); }); }, test_should_correctly_do_upsert : function() { client.createCollection('test_should_correctly_do_upsert', function(err, collection) { var id = new client.bson_serializer.ObjectID(null) var doc = {_id:id, a:1}; collection.update({"_id":id}, doc, {upsert:true}, function(err, result) { test.equal(null, err); test.equal(null, result); collection.findOne({"_id":id}, function(err, doc) { test.equal(1, doc.a); }); }); id = new client.bson_serializer.ObjectID(null) doc = {_id:id, a:2}; collection.update({"_id":id}, doc, {safe:true, upsert:true}, function(err, result) { test.equal(null, err); test.equal(1, result); collection.findOne({"_id":id}, function(err, doc) { test.equal(2, doc.a); }); }); collection.update({"_id":id}, doc, {safe:true, upsert:true}, function(err, result) { test.equal(null, err); test.equal(1, result); collection.findOne({"_id":id}, function(err, doc) { test.equal(2, doc.a); finished_test({test_should_correctly_do_upsert:'ok'}); }); }); }); }, test_should_correctly_do_update_with_no_docs_found : function() { client.createCollection('test_should_correctly_do_update_with_no_docs', function(err, collection) { var id = new client.bson_serializer.ObjectID(null) var doc = {_id:id, a:1}; collection.update({"_id":id}, doc, {safe:true}, function(err, numberofupdateddocs) { test.equal(null, err); test.equal(0, numberofupdateddocs); finished_test({test_should_correctly_do_update_with_no_docs_found:'ok'}); }); }); }, test_should_execute_insert_update_delete_safe_mode : function() { client.createCollection('test_should_execute_insert_update_delete_safe_mode', function(err, collection) { test.ok(collection instanceof Collection); test.equal('test_should_execute_insert_update_delete_safe_mode', collection.collectionName); collection.insert({i:1}, {safe:true}, function(err, ids) { test.equal(1, ids.length); test.ok(ids[0]._id.toHexString().length == 24); // Update the record collection.update({i:1}, {"$set":{i:2}}, {safe:true}, function(err, result) { test.equal(null, err); test.equal(1, result); // Remove safely collection.remove({}, {safe:true}, function(err, result) { test.equal(null, err); finished_test({test_should_execute_insert_update_delete_safe_mode:'ok'}); }); }); }); }); }, test_streaming_function_with_limit_for_fetching : function() { var docs = [] for(var i = 0; i < 3000; i++) { docs.push({'a':i}) } client.createCollection('test_streaming_function_with_limit_for_fetching', function(err, collection) { test.ok(collection instanceof Collection); collection.insertAll(docs, function(err, ids) { collection.find({}, function(err, cursor) { // Execute find on all the documents var stream = cursor.streamRecords({fetchSize:1000}); var callsToEnd = 0; stream.addListener('end', function() { finished_test({test_streaming_function_with_limit_for_fetching:'ok'}); }); var callsToData = 0; stream.addListener('data',function(data){ callsToData += 1; test.ok(callsToData <= 3000); }); }); }); }); }, test_to_json_for_long : function() { client.createCollection('test_to_json_for_long', function(err, collection) { test.ok(collection instanceof Collection); // collection.insertAll([{value: client.bson_serializer.Long.fromNumber(32222432)}], function(err, ids) { collection.insertAll([{value: client.bson_serializer.Long.fromNumber(32222432)}], function(err, ids) { collection.findOne({}, function(err, item) { test.equal("32222432", item.value.toJSON()) finished_test({test_to_json_for_long:'ok'}); }); }); }); }, test_failed_connection_caught : function() { var fs_client = new Db('admin_test_4', new Server("127.0.0.1", 27117, {auto_reconnect: false})); fs_client.bson_deserializer = client.bson_deserializer; fs_client.bson_serializer = client.bson_serializer; fs_client.pkFactory = client.pkFactory; fs_client.open(function(err, fs_client) { test.ok(err != null) finished_test({test_failed_connection_caught:'ok'}); }) }, test_insert_and_update_no_callback : function() { client.createCollection('test_insert_and_update_no_callback', function(err, collection) { // Insert the update collection.insert({i:1}, {safe:true}) // Update the record collection.update({i:1}, {"$set":{i:2}}, {safe:true}) // Locate document collection.findOne({}, function(err, item) { test.equal(2, item.i) finished_test({test_insert_and_update_no_callback:'ok'}); }); }) }, test_insert_and_query_timestamp : function() { client.createCollection('test_insert_and_query_timestamp', function(err, collection) { // Insert the update collection.insert({i:client.bson_serializer.Timestamp.fromNumber(100), j:client.bson_serializer.Long.fromNumber(200)}, {safe:true}) // Locate document collection.findOne({}, function(err, item) { test.equal(100, item.i.toNumber()) test.equal(200, item.j.toNumber()) finished_test({test_insert_and_query_timestamp:'ok'}); }); }) }, test_insert_and_query_undefined : function() { client.createCollection('test_insert_and_query_undefined', function(err, collection) { // Insert the update collection.insert({i:undefined}, {safe:true}) // Locate document collection.findOne({}, function(err, item) { test.equal(null, item.i) finished_test({test_insert_and_query_undefined:'ok'}); }); }) }, test_nativedbref_json_crash : function() { var dbref = new client.bson_serializer.DBRef("foo", client.bson_serializer.ObjectID.createFromHexString("fc24a04d4560531f00000000"), null); JSON.stringify(dbref); finished_test({test_nativedbref_json_crash:'ok'}); }, test_safe_insert : function() { var fixtures = [{ name: "empty", array: [], bool: false, dict: {}, float: 0.0, string: "" }, { name: "not empty", array: [1], bool: true, dict: {x: "y"}, float: 1.0, string: "something" }, { name: "simple nested", array: [1, [2, [3]]], bool: true, dict: {x: "y", array: [1,2,3,4], dict: {x: "y", array: [1,2,3,4]}}, float: 1.5, string: "something simply nested" }]; client.createCollection('test_safe_insert', function(err, collection) { for(var i = 0; i < fixtures.length; i++) { collection.insert(fixtures[i], {safe:true}) } collection.count(function(err, count) { test.equal(3, count); collection.find().toArray(function(err, docs) { test.equal(3, docs.length) }); }); collection.find({}, {}, function(err, cursor) { var counter = 0; cursor.each(function(err, doc) { if(doc == null) { test.equal(3, counter); finished_test({test_safe_insert:'ok'}); } else { counter = counter + 1; } }); }); }) }, test_regex_serialization : function() { // Serialized regexes contain extra trailing chars. Sometimes these trailing chars contain / which makes // the original regex invalid, and leads to segmentation fault. client.createCollection('test_regex_serialization', function(err, collection) { collection.insert({keywords: ["test", "segmentation", "fault", "regex", "serialization", "native"]}, {safe:true}); var count = 20, run = function(i) { // search by regex collection.findOne({keywords: {$all: [/ser/, /test/, /seg/, /fault/, /nat/]}}, function(err, item) { test.equal(6, item.keywords.length); if (i === 0) { finished_test({test_regex_serialization:'ok'}); } }); }; // loop a few times to catch the / in trailing chars case while (count--) { run(count); } }); }, test_should_throw_error_if_serializing_function : function() { client.createCollection('test_should_throw_error_if_serializing_function', function(err, collection) { // Insert the update collection.insert({i:1, z:function() { return 1} }, {safe:true}, function(err, result) { collection.findOne({_id:result[0]._id}, function(err, object) { test.equal(null, object.z); test.equal(1, object.i); finished_test({test_should_throw_error_if_serializing_function:'ok'}); }) }) }) }, multiple_save_test : function() { client.createCollection("multiple_save_test", function(err, collection) { //insert new user collection.save({ name: 'amit', text: 'some text' }) collection.find({}, {name: 1}).limit(1).toArray(function(err, users){ user = users[0] if(err) { throw new Error(err) } else if(user) { user.pants = 'worn' collection.save(user, {safe:true}, function(err, result){ test.equal(null, err); test.equal(1, result); finished_test({multiple_save_test:'ok'}); }) } }); }); }, save_error_on_save_test : function() { var db = new Db('test-save_error_on_save_test-db', new Server('localhost', 27017, {auto_reconnect: true})); db.bson_deserializer = client.bson_deserializer; db.bson_serializer = client.bson_serializer; db.pkFactory = client.pkFactory; db.open(function(err, db) { db.createCollection("save_error_on_save_test", function(err, collection) { // Create unique index for username collection.createIndex([['username', 1]], true, function(err, result) { //insert new user collection.save({ email: 'email@email.com', encrypted_password: 'password', friends: [ '4db96b973d01205364000006', '4db94a1948a683a176000001', '4dc77b24c5ba38be14000002' ], location: [ 72.4930088, 23.0431957 ], name: 'Amit Kumar', password_salt: 'salty', profile_fields: [], username: 'amit' }, function(err, doc){ }); collection.find({}).limit(1).toArray(function(err, users){ test.equal(null, err); user = users[0] user.friends.splice(1,1) collection.save(user, function(err, doc){ test.equal(null, err); // Update again collection.update({_id:new client.bson_serializer.ObjectID(user._id.toString())}, {friends:user.friends}, {upsert:true, safe:true}, function(err, result) { test.equal(null, err); test.equal(1, result); finished_test({save_error_on_save_test:'ok'}); db.close(); }); }); }); }) }); }); }, remove_with_no_callback_bug_test : function() { client.collection("remove_with_no_callback_bug_test", function(err, collection) { collection.save({a:1}, {safe:true}, function(){ collection.save({b:1}, {safe:true}, function(){ collection.save({c:1}, {safe:true}, function(){ collection.remove({a:1}) // Let's perform a count collection.count(function(err, count) { test.equal(null, err); test.equal(2, count); finished_test({remove_with_no_callback_bug_test:'ok'}); }); }); }); }); }); }, }; /******************************************************************************************************* Setup For Running Tests *******************************************************************************************************/ var client_tests = {}; var type = process.argv[2]; if(process.argv[3]){ var test_arg = process.argv[3]; if(test_arg == 'all') client_tests = all_tests; else { test_arg.split(',').forEach(function(aTest){ if(all_tests[aTest]) client_tests[aTest] = all_tests[aTest]; }); } } else client_tests = all_tests; var client_tests_keys = []; for(key in client_tests) client_tests_keys.push(key); // Set up the client connection var client = new Db('integration_tests_', new Server("127.0.0.1", 27017, {}), {}); // Use native deserializer if(type == "native") { var BSON = require("../external-libs/bson/bson"); debug("========= Integration tests running Native BSON Parser == ") client.bson_deserializer = BSON; client.bson_serializer = BSON; client.pkFactory = BSON.ObjectID; } else { var BSONJS = require('../lib/mongodb/bson/bson'); debug("========= Integration tests running Pure JS BSON Parser == ") client.bson_deserializer = BSONJS; client.bson_serializer = BSONJS; client.pkFactory = BSONJS.ObjectID; } client.open(function(err, client) { // Do cleanup of the db client.dropDatabase(function() { // Run all the tests run_tests(); // Start the timer that checks that all the tests have finished or failed ensure_tests_finished(); }); }); function ensure_tests_finished() { var intervalId = setInterval(function() { if(client_tests_keys.length == 0) { // Print out the result debug("= Final Checks ========================================================="); // Stop interval timer and close db connection clearInterval(intervalId); // Ensure we don't have any more cursors hanging about client.cursorInfo(function(err, cursorInfo) { debug(inspect(cursorInfo)); debug(""); client.close(); }); } }, 100); }; // All the finished client tests var finished_tests = []; function run_tests() { // Run first test client_tests[client_tests_keys[0]](); } function finished_test(test_object) { for(var name in test_object) { debug("= executing test: " + name + " [" + test_object[name] + "]"); } finished_tests.push(test_object); client_tests_keys.shift(); // Execute next test if(client_tests_keys.length > 0) client_tests[client_tests_keys[0]](); } function randOrd() { return (Math.round(Math.random()) - 0.5); } /** Helper Utilities for the testing **/ function locate_collection_by_name(collectionName, collections) { var foundObject = null; collections.forEach(function(collection) { if(collection.collectionName == collectionName) foundObject = collection; }); return foundObject; }
var hospitales = angular.module("hospitales", []); var actual = {}; hospitales.controller('listado', function($scope, $http) { $scope.datos = []; setInterval(function() { if (document.getElementById("search") !== document.activeElement) { $scope.borrar = false; } }, 100); if (typeof(data)!="undefined") { $scope.datos = data; localStorage["DATOS"] = JSON.stringify(data); }else if (typeof(localStorage["DATOS"]) != "undefined") { $scope.datos = JSON.parse(localStorage["DATOS"]); } $scope.panelsh = false; $scope.panelp = true; $scope.panelm = false; $scope.actualselect = false; if (localStorage["colortext"] === undefined) { $scope.colortext="white"; localStorage["colortext"]="white"; } else { $scope.colortext=localStorage["colortext"]; }; if (localStorage["colorfondo"] === undefined) { $scope.colorfondo="black"; localStorage["colorfondo"]="black"; } else { $scope.colorfondo=localStorage["colorfondo"]; }; $scope.actual = ""; $scope.cambiarhospital = function(x) { if (actual!=x) { actual = x; $scope.servicios = x.servicio; $scope.horarios = x.horarios; $scope.actual = x.name; hospital_actual = x.name; lat = parseFloat(x.latitud); lng = parseFloat(x.longitud); change_position = true; $scope.actualselect = true; } }; $scope.changecolortext = function() { localStorage["colortext"]=$scope.colortext; }; $scope.changecolorfondo = function() { localStorage["colorfondo"]=$scope.colorfondo; }; $scope.tomarfoto = function() { var oSerializer = new XMLSerializer(); localStorage["mapa"]=oSerializer.serializeToString(document.getElementById("Mapa")); Materialize.toast('Foto Tomada', 3000, 'rounded') }; $scope.cargarfoto = function() { if (localStorage["mapa"] !== undefined) { document.getElementById("Mapa").innerHTML = localStorage["mapa"]; first_time = true; Materialize.toast('Foto Cargada', 3000, 'rounded') }else { Materialize.toast('No possees una ultima foto guardada', 3000, 'rounded') } }; $scope.recargarelmapa = function() { first_time = true; recargal(); }; $scope.changetag = function(x) { if (x==1) { $scope.panelp = true; $scope.panelsh = false; $scope.panelm = false; $scope.lax = false; } else if (x==2) { $scope.panelp = false; $scope.panelsh = false; $scope.panelm = true; $scope.lax = false; } else if (x==3) { $scope.panelp = false; $scope.panelsh = true; $scope.panelm = false; if ($scope.actualselect) { $scope.lax = false; }else{ $scope.lax = true; } } }; document.getElementById("colorfondos").value = $scope.colorfondo; document.getElementById("colortexts").value = $scope.colortext; });
var Commander = require("../../lib/command"); var commands = require("../../lib/commands"); var commander = new Commander(commands); module.exports = { run: function(command, config, callback) { commander.run(command, config, function(err) { if (err != 0) { if (typeof err == "number") { err = new Error("Unknown exit code: " + err); } return callback(err); } callback(); }); } };
'use strict'; var request = require('request'); module.exports = function (grunt) { // show elapsed time at the end require('time-grunt')(grunt); // load all grunt tasks require('load-grunt-tasks')(grunt); var reloadPort = 35731, files; grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), develop: { server: { file: 'app.js' } }, watch: { options: { nospawn: true, livereload: reloadPort }, js: { files: [ 'app.js', 'app/**/*.js', 'config/*.js' ], tasks: ['develop', 'delayed-livereload'] }, views: { files: [ 'app/views/*.jade', 'app/views/**/*.jade' ], options: { livereload: reloadPort } } } }); grunt.config.requires('watch.js.files'); files = grunt.config('watch.js.files'); files = grunt.file.expand(files); grunt.registerTask('delayed-livereload', 'Live reload after the node server has restarted.', function () { var done = this.async(); setTimeout(function () { request.get('http://localhost:' + reloadPort + '/changed?files=' + files.join(','), function(err, res) { var reloaded = !err && res.statusCode === 200; if (reloaded) grunt.log.ok('Delayed live reload successful.'); else grunt.log.error('Unable to make a delayed live reload.'); done(reloaded); }); }, 500); }); grunt.registerTask('default', ['develop', 'watch']); };
'use strict'; let datafire = require('datafire'); let openapi = require('./openapi.json'); let aws = require('aws-sdk'); const INTEGRATION_ID = 'amazonaws_waf'; const SDK_ID = 'WAF'; let integ = module.exports = new datafire.Integration({ id: INTEGRATION_ID, title: openapi.info.title, description: openapi.info.description, logo: openapi.info['x-logo'], }); integ.security[INTEGRATION_ID]= { integration: INTEGRATION_ID, fields: { accessKeyId: "", secretAccessKey: "", region: "AWS region (if applicable)", } } function maybeCamelCase(str) { return str.replace(/_(\w)/g, (match, char) => char.toUpperCase()) } // We use this instance to make sure each action is available in the SDK at startup. let dummyInstance = new aws[SDK_ID]({version: openapi.version, endpoint: 'foo'}); for (let path in openapi.paths) { for (let method in openapi.paths[path]) { if (method === 'parameters') continue; let op = openapi.paths[path][method]; let actionID = op.operationId; actionID = actionID.replace(/\d\d\d\d_\d\d_\d\d$/, ''); if (actionID.indexOf('_') !== -1) { actionID = actionID.split('_')[1]; } let functionID = actionID.charAt(0).toLowerCase() + actionID.substring(1); if (!dummyInstance[functionID]) { console.error("AWS SDK " + SDK_ID + ": Function " + functionID + " not found"); console.log(method, path, op.operationId, actionID); continue; } let inputParam = (op.parameters || []).filter(p => p.in === 'body')[0] || {}; let response = (op.responses || {})[200] || {}; let inputSchema = { type: 'object', properties: {}, }; if (inputParam.schema) inputSchema.allOf = [inputParam.schema]; (op.parameters || []).forEach(p => { if (p.name !== 'Action' && p.name !== 'Version' && p.name !== 'body' && !p.name.startsWith('X-')) { inputSchema.properties[maybeCamelCase(p.name)] = {type: p.type}; if (p.required) { inputSchema.required = inputSchema.required || []; inputSchema.required.push(p.name); } } }) function getSchema(schema) { if (!schema) return; return Object.assign({definitions: openapi.definitions}, schema); } integ.addAction(actionID, new datafire.Action({ inputSchema: getSchema(inputSchema), outputSchema: getSchema(response.schema), handler: (input, context) => { let lib = new aws[SDK_ID](Object.assign({ version: openapi.info.version, }, context.accounts[INTEGRATION_ID])); return lib[functionID](input).promise() .then(data => { return JSON.parse(JSON.stringify(data)); }) } })); } }
'use strict'; angular.module('mgcrea.ngStrap.typeahead', ['mgcrea.ngStrap.tooltip', 'mgcrea.ngStrap.helpers.parseOptions']) .provider('$typeahead', function() { var defaults = this.defaults = { animation: 'am-fade', prefixClass: 'typeahead', prefixEvent: '$typeahead', placement: 'bottom-left', template: 'typeahead/typeahead.tpl.html', trigger: 'focus', container: false, keyboard: true, html: false, delay: 0, minLength: 1, filter: 'filter', limit: 6, autoSelect: false, comparator: '', trimValue: true }; this.$get = function($window, $rootScope, $tooltip, $timeout) { var bodyEl = angular.element($window.document.body); function TypeaheadFactory(element, controller, config) { var $typeahead = {}; // Common vars var options = angular.extend({}, defaults, config); $typeahead = $tooltip(element, options); var parentScope = config.scope; var scope = $typeahead.$scope; scope.$resetMatches = function(){ scope.$matches = []; scope.$activeIndex = options.autoSelect ? 0 : -1; // If set to 0, the first match will be highlighted }; scope.$resetMatches(); scope.$activate = function(index) { scope.$$postDigest(function() { $typeahead.activate(index); }); }; scope.$select = function(index, evt) { scope.$$postDigest(function() { $typeahead.select(index); }); }; scope.$isVisible = function() { return $typeahead.$isVisible(); }; // Public methods $typeahead.update = function(matches) { scope.$matches = matches; if(scope.$activeIndex >= matches.length) { scope.$activeIndex = options.autoSelect ? 0: -1; } // When the placement is not one of the bottom placements, re-calc the positioning // so the results render correctly. if (/^(bottom|bottom-left|bottom-right)$/.test(options.placement)) return; // wrap in a $timeout so the results are updated // before repositioning $timeout($typeahead.$applyPlacement); }; $typeahead.activate = function(index) { scope.$activeIndex = index; }; $typeahead.select = function(index) { if(index === -1) return; var value = scope.$matches[index].value; // console.log('$setViewValue', value); controller.$setViewValue(value); controller.$render(); scope.$resetMatches(); if(parentScope) parentScope.$digest(); // Emit event scope.$emit(options.prefixEvent + '.select', value, index, $typeahead); }; // Protected methods $typeahead.$isVisible = function() { if(!options.minLength || !controller) { return !!scope.$matches.length; } // minLength support return scope.$matches.length && angular.isString(controller.$viewValue) && controller.$viewValue.length >= options.minLength; }; $typeahead.$getIndex = function(value) { var l = scope.$matches.length, i = l; if(!l) return; for(i = l; i--;) { if(scope.$matches[i].value === value) break; } if(i < 0) return; return i; }; $typeahead.$onMouseDown = function(evt) { // Prevent blur on mousedown evt.preventDefault(); evt.stopPropagation(); }; $typeahead.$onKeyDown = function(evt) { if(!/(38|40|13)/.test(evt.keyCode)) return; // Let ngSubmit pass if the typeahead tip is hidden or no option is selected if($typeahead.$isVisible() && !(evt.keyCode === 13 && scope.$activeIndex === -1)) { evt.preventDefault(); evt.stopPropagation(); } // Select with enter if(evt.keyCode === 13 && scope.$matches.length) { $typeahead.select(scope.$activeIndex); } // Navigate with keyboard else if(evt.keyCode === 38 && scope.$activeIndex > 0) scope.$activeIndex--; else if(evt.keyCode === 40 && scope.$activeIndex < scope.$matches.length - 1) scope.$activeIndex++; else if(angular.isUndefined(scope.$activeIndex)) scope.$activeIndex = 0; scope.$digest(); }; // Overrides var show = $typeahead.show; $typeahead.show = function() { show(); // use timeout to hookup the events to prevent // event bubbling from being processed imediately. $timeout(function() { $typeahead.$element.on('mousedown', $typeahead.$onMouseDown); if(options.keyboard) { element.on('keydown', $typeahead.$onKeyDown); } }, 0, false); }; var hide = $typeahead.hide; $typeahead.hide = function() { $typeahead.$element.off('mousedown', $typeahead.$onMouseDown); if(options.keyboard) { element.off('keydown', $typeahead.$onKeyDown); } if(!options.autoSelect) $typeahead.activate(-1); hide(); }; return $typeahead; } TypeaheadFactory.defaults = defaults; return TypeaheadFactory; }; }) .directive('bsTypeahead', function($window, $parse, $q, $typeahead, $parseOptions) { var defaults = $typeahead.defaults; return { restrict: 'EAC', require: 'ngModel', link: function postLink(scope, element, attr, controller) { // Directive options var options = {scope: scope}; angular.forEach(['placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'template', 'filter', 'limit', 'minLength', 'watchOptions', 'selectMode', 'autoSelect', 'comparator', 'id', 'prefixEvent', 'prefixClass'], function(key) { if(angular.isDefined(attr[key])) options[key] = attr[key]; }); // use string regex match boolean attr falsy values, leave truthy values be var falseValueRegExp = /^(false|0|)$/i; angular.forEach(['html', 'container', 'trimValue'], function(key) { if(angular.isDefined(attr[key]) && falseValueRegExp.test(attr[key])) options[key] = false; }); // Disable browser autocompletion element.attr('autocomplete' ,'off'); // Build proper bsOptions var filter = options.filter || defaults.filter; var limit = options.limit || defaults.limit; var comparator = options.comparator || defaults.comparator; var bsOptions = attr.bsOptions; if(filter) bsOptions += ' | ' + filter + ':$viewValue'; if (comparator) bsOptions += ':' + comparator; if(limit) bsOptions += ' | limitTo:' + limit; var parsedOptions = $parseOptions(bsOptions); // Initialize typeahead var typeahead = $typeahead(element, controller, options); // Watch options on demand if(options.watchOptions) { // Watch bsOptions values before filtering for changes, drop function calls var watchedOptions = parsedOptions.$match[7].replace(/\|.+/, '').replace(/\(.*\)/g, '').trim(); scope.$watchCollection(watchedOptions, function (newValue, oldValue) { // console.warn('scope.$watch(%s)', watchedOptions, newValue, oldValue); parsedOptions.valuesFn(scope, controller).then(function (values) { typeahead.update(values); controller.$render(); }); }); } // Watch model for changes scope.$watch(attr.ngModel, function(newValue, oldValue) { // console.warn('$watch', element.attr('ng-model'), newValue); scope.$modelValue = newValue; // Publish modelValue on scope for custom templates parsedOptions.valuesFn(scope, controller) .then(function(values) { // Prevent input with no future prospect if selectMode is truthy // @TODO test selectMode if(options.selectMode && !values.length && newValue.length > 0) { controller.$setViewValue(controller.$viewValue.substring(0, controller.$viewValue.length - 1)); return; } if(values.length > limit) values = values.slice(0, limit); var isVisible = typeahead.$isVisible(); isVisible && typeahead.update(values); // Do not re-queue an update if a correct value has been selected if(values.length === 1 && values[0].value === newValue) return; !isVisible && typeahead.update(values); // Queue a new rendering that will leverage collection loading controller.$render(); }); }); // modelValue -> $formatters -> viewValue controller.$formatters.push(function(modelValue) { // console.warn('$formatter("%s"): modelValue=%o (%o)', element.attr('ng-model'), modelValue, typeof modelValue); var displayValue = parsedOptions.displayValue(modelValue); return displayValue === undefined ? '' : displayValue; }); // Model rendering in view controller.$render = function () { // console.warn('$render', element.attr('ng-model'), 'controller.$modelValue', typeof controller.$modelValue, controller.$modelValue, 'controller.$viewValue', typeof controller.$viewValue, controller.$viewValue); if(controller.$isEmpty(controller.$viewValue)) return element.val(''); var index = typeahead.$getIndex(controller.$modelValue); var selected = angular.isDefined(index) ? typeahead.$scope.$matches[index].label : controller.$viewValue; selected = angular.isObject(selected) ? parsedOptions.displayValue(selected) : selected; var value = selected ? selected.toString().replace(/<(?:.|\n)*?>/gm, '') : ''; element.val(options.trimValue === false ? value : value.trim()); }; // Garbage collection scope.$on('$destroy', function() { if (typeahead) typeahead.destroy(); options = null; typeahead = null; }); } }; });
$(function() { $('#login-form-link').click(function(e) { $("#login-form").delay(100).fadeIn(100); $("#register-form").fadeOut(100); $('#register-form-link').removeClass('active'); $(this).addClass('active'); e.preventDefault(); }); $('#register-form-link').click(function(e) { $("#register-form").delay(100).fadeIn(100); $("#login-form").fadeOut(100); $('#login-form-link').removeClass('active'); $(this).addClass('active'); e.preventDefault(); }); });
version https://git-lfs.github.com/spec/v1 oid sha256:9a2b0ef6b89bfc8deac4fad55d1ada8eff51d738c48f927b5755410c1f970078 size 41394
version https://git-lfs.github.com/spec/v1 oid sha256:f19893d23985aa11bf3aef0411ed7506c6214bed1bd2bcef825ccc78c113290c size 14731
/** * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'a11yhelp', 'th', { title: 'Accessibility Instructions', // MISSING contents: 'Help Contents. To close this dialog press ESC.', // MISSING legend: [ { name: 'ทั่วไป', items: [ { name: 'แถบเครื่องมือสำหรับเครื่องมือช่วยพิมพ์', legend: 'Press ${toolbarFocus} to navigate to the toolbar. Move to the next and previous toolbar group with TAB and SHIFT+TAB. Move to the next and previous toolbar button with RIGHT ARROW or LEFT ARROW. Press SPACE or ENTER to activate the toolbar button.' // MISSING }, { name: 'Editor Dialog', // MISSING legend: 'Inside a dialog, press TAB to navigate to the next dialog element, press SHIFT+TAB to move to the previous dialog element, press ENTER to submit the dialog, press ESC to cancel the dialog. When a dialog has multiple tabs, the tab list can be reached either with ALT+F10 or with TAB as part of the dialog tabbing order. With tab list focused, move to the next and previous tab with RIGHT and LEFT ARROW, respectively.' // MISSING }, { name: 'Editor Context Menu', // MISSING legend: 'Press ${contextMenu} or APPLICATION KEY to open context-menu. Then move to next menu option with TAB or DOWN ARROW. Move to previous option with SHIFT+TAB or UP ARROW. Press SPACE or ENTER to select the menu option. Open sub-menu of current option with SPACE or ENTER or RIGHT ARROW. Go back to parent menu item with ESC or LEFT ARROW. Close context menu with ESC.' // MISSING }, { name: 'Editor List Box', // MISSING legend: 'Inside a list-box, move to next list item with TAB OR DOWN ARROW. Move to previous list item with SHIFT+TAB or UP ARROW. Press SPACE or ENTER to select the list option. Press ESC to close the list-box.' // MISSING }, { name: 'Editor Element Path Bar', // MISSING legend: 'Press ${elementsPathFocus} to navigate to the elements path bar. Move to next element button with TAB or RIGHT ARROW. Move to previous button with SHIFT+TAB or LEFT ARROW. Press SPACE or ENTER to select the element in editor.' // MISSING } ] }, { name: 'คำสั่ง', items: [ { name: 'เลิกทำคำสั่ง', legend: 'วาง ${undo}' }, { name: 'คำสั่งสำหรับทำซ้ำ', legend: 'วาง ${redo}' }, { name: 'คำสั่งสำหรับตัวหนา', legend: 'วาง ${bold}' }, { name: 'คำสั่งสำหรับตัวเอียง', legend: 'วาง ${italic}' }, { name: 'คำสั่งสำหรับขีดเส้นใต้', legend: 'วาง ${underline}' }, { name: 'คำสั่งสำหรับลิงก์', legend: 'วาง ${link}' }, { name: ' Toolbar Collapse command', // MISSING legend: 'Press ${toolbarCollapse}' // MISSING }, { name: ' Access previous focus space command', // MISSING legend: 'Press ${accessPreviousSpace} to access the closest unreachable focus space before the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces.' // MISSING }, { name: ' Access next focus space command', // MISSING legend: 'Press ${accessNextSpace} to access the closest unreachable focus space after the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces.' // MISSING }, { name: ' Accessibility Help', // MISSING legend: 'Press ${a11yHelp}' // MISSING }, { name: ' Paste as plain text', // MISSING legend: 'Press ${pastetext}', // MISSING legendEdge: 'Press ${pastetext}, followed by ${paste}' // MISSING } ] } ], tab: 'Tab', // MISSING pause: 'Pause', // MISSING capslock: 'Caps Lock', // MISSING escape: 'Escape', // MISSING pageUp: 'Page Up', // MISSING pageDown: 'Page Down', // MISSING leftArrow: 'Left Arrow', // MISSING upArrow: 'Up Arrow', // MISSING rightArrow: 'Right Arrow', // MISSING downArrow: 'Down Arrow', // MISSING insert: 'Insert', // MISSING leftWindowKey: 'Left Windows key', // MISSING rightWindowKey: 'Right Windows key', // MISSING selectKey: 'Select key', // MISSING numpad0: 'Numpad 0', // MISSING numpad1: 'Numpad 1', // MISSING numpad2: 'Numpad 2', // MISSING numpad3: 'Numpad 3', // MISSING numpad4: 'Numpad 4', // MISSING numpad5: 'Numpad 5', // MISSING numpad6: 'Numpad 6', // MISSING numpad7: 'Numpad 7', // MISSING numpad8: 'Numpad 8', // MISSING numpad9: 'Numpad 9', // MISSING multiply: 'Multiply', // MISSING add: 'Add', // MISSING subtract: 'Subtract', // MISSING decimalPoint: 'Decimal Point', // MISSING divide: 'Divide', // MISSING f1: 'F1', // MISSING f2: 'F2', // MISSING f3: 'F3', // MISSING f4: 'F4', // MISSING f5: 'F5', // MISSING f6: 'F6', // MISSING f7: 'F7', // MISSING f8: 'F8', // MISSING f9: 'F9', // MISSING f10: 'F10', // MISSING f11: 'F11', // MISSING f12: 'F12', // MISSING numLock: 'Num Lock', // MISSING scrollLock: 'Scroll Lock', // MISSING semiColon: 'Semicolon', // MISSING equalSign: 'Equal Sign', // MISSING comma: 'Comma', // MISSING dash: 'Dash', // MISSING period: 'Period', // MISSING forwardSlash: 'Forward Slash', // MISSING graveAccent: 'Grave Accent', // MISSING openBracket: 'Open Bracket', // MISSING backSlash: 'Backslash', // MISSING closeBracket: 'Close Bracket', // MISSING singleQuote: 'Single Quote' // MISSING } );
import { isElement } from "lodash"; const setData = (type, data) => { switch (type) { case "Element": return document.getElementById(data); //document.getElementById(data); case "String": return data; default: try { return JSON.parse(data); } catch (e) { return null; } } }; export const checker = (type, dataAttr) => { const checks = { Array: Array.isArray, Boolean: d => typeof d === "boolean", Element: d => d instanceof Element, Number: d => typeof d === "number", String: d => typeof d === "string" }; if (!checks.hasOwnProperty(type)) return false; const data = setData(type, dataAttr); const check = checks[type]; return check(data); }; const checkAttributes = attrs => attrs.reduce((ds, attr) => { if (ds) return true; if (!attr.nodeName) return ds; return attr.nodeName.match(/data/) ? true : false; }, false); export default checks => el => { let keys, valid, chKeys; if (!el && !el.attributes) return false; const attrs = [...el.attributes]; if (!checkAttributes(attrs)) return false; keys = Object.keys(el.dataset); chKeys = Object.keys(checks); valid = chKeys.reduce((test, ch) => { if (!test) return false; return keys.includes(ch); }, true); if (!valid) return valid; return Object.entries(checks).reduce((val, [k, v]) => { if (!val) return val; return checker(v, el.dataset[k]); }, true); };
/* */ var makeString = require("./helper/makeString"); module.exports = function strLeft(str, sep) { str = makeString(str); sep = makeString(sep); var pos = !sep ? -1 : str.indexOf(sep); return ~pos ? str.slice(0, pos) : str; };
class BrewTimerDialog { constructor(el, recipeId) { this.el = el; this.recipeId = recipeId; this.notify = new Notify(); this.startEl = this.el.find(".brew-timer-start"); this.pauseEl = this.el.find(".brew-timer-pause"); this.resetEl = this.el.find(".brew-timer-reset"); this.expandEl = this.el.find(".brew-timer-expand"); this.stepForwardEl = this.el.find(".brew-timer-step-forward"); this.stepBackwardEl = this.el.find(".brew-timer-step-backward"); this.sounds = null; this.el .on('shown.bs.modal', this.setupDialog.bind(this)) .on('hidden.bs.modal', this.cancelDialog.bind(this)); this.toggleTimer = this.toggleTimer.bind(this); this.resetTimer = this.resetTimer.bind(this); this.toggleExpand = this.toggleExpand.bind(this); this.toggleCountdown = this.toggleCountdown.bind(this); this.stepForward = this.stepForward.bind(this); this.stepBackward = this.stepBackward.bind(this); this.onFullscreenChange = this.onFullscreenChange.bind(this); this.keyPressed = this.keyPressed.bind(this); } setupDialog() { this.setupSounds(); this.setupTimer(); this.startEl.on("click", this.toggleTimer); this.pauseEl.on("click", this.toggleTimer); this.resetEl.on("click", this.resetTimer); this.expandEl.on("click", this.toggleExpand); this.stepForwardEl.on("click", this.stepForward); this.stepBackwardEl.on("click", this.stepBackward); this.el.on("click", ".timer-time", this.toggleCountdown); $(document).on("fullscreenchange", this.onFullscreenChange); $(window).on("keypress", this.keyPressed); this.tag('open'); } cancelDialog() { this.tag('close'); this.startEl.off("click", this.toggleTimer); this.pauseEl.off("click", this.toggleTimer); this.resetEl.off("click", this.resetTimer); this.expandEl.off("click", this.toggleExpand); this.stepForwardEl.off("click", this.stepForward); this.stepBackwardEl.off("click", this.stepBackward); this.el.off("click", ".timer-time", this.toggleCountdown); $(document).off("fullscreenchange", this.onFullscreenChange); $(window).off("keypress", this.keyPressed); } setupTimer() { if (!this.timer) { this.stepType = this.el.data("stepType"); this.steps = this.el.data("brewtimerSteps"); this.createTimer(this.steps, this.stepType); } } setupSounds() { if (this.sounds) { return; } this.sounds = {}; ["step", "done"].forEach((sound_type) => { this.sounds[sound_type] = new Map(); window.audio_assets[sound_type].forEach((path, key) => { this.sounds[sound_type].set(key, new Howl({ src: [path] })); }); }); } playSound(sound_type) { this.getRandomItem(this.sounds[sound_type]).play(); } getRandomItem(iterable) { const randomIndex = Math.floor(Math.random() * iterable.size); return iterable.get(Array.from(iterable.keys())[randomIndex]); } createTimer(steps, stepType) { this.timer = new BrewTimer(this.el.find('.timer-content'), steps, stepType); this.timer.addEventListener("brewtimer.done", (event) => { this.togglePlayButton(); }); this.timer.addEventListener("brewtimer.step", (event) => { if (this.timer.currentStep > 0) { this.playSound("step"); this.notify.send(I18n["brewtimer"]["notification"]["step"] + this.timer.getCurrentStep()["name"]); } }); this.timer.addEventListener("brewtimer.done", (event) => { this.playSound("done"); this.notify.send(I18n["brewtimer"]["notification"]["done"][this.timer.stepType], "done"); }); // Update modal if content changes this.el.modal('handleUpdate'); this.timer.addEventListener("brewtimer.update", (event) => { this.el.modal('handleUpdate'); }); } keyPressed(ev) { if (this.el.is(":hidden")) { return; } if ((ev.keyCode === 0) || (ev.keyCode === 32)) { this.toggleTimer(); } return false; } togglePlayButton() { this.startEl.toggleClass("hidden"); this.pauseEl.toggleClass("hidden"); } resetTimer() { if (this.timer) { this.timer.reset(); this.togglePlayButton(); } return false; } toggleTimer() { this.notify.requestPermission(); if (this.timer) { if (this.timer.running) { this.tag('pause'); } else { this.tag('play'); } this.timer.toggle(); this.togglePlayButton(); } return false; } toggleExpand() { this.openFullscreen(this.el.find(".timer-content").get(0)); } openFullscreen(el) { if (el.requestFullscreen) { el.requestFullscreen(); } else { this.expandEl.find("i").toggleClass("fa-expand fa-compress"); } } onFullscreenChange(event) { if (document.fullscreenElement) { this.el.addClass("brewtimer-fullscreen"); } else { this.el.removeClass("brewtimer-fullscreen"); } } stepForward() { if (this.timer.running) { this.timer.nextStep(); } } stepBackward() { if (this.timer.running) { this.timer.previousStep(); } } toggleCountdown() { this.timer.toggleCountDown(); } tag(event_name) { if (window["gtag"]) { gtag('event', event_name, { 'event_category': 'BrewTimer', 'event_label': this.stepType, 'value': this.recipeId }); } } } (typeof exports !== 'undefined' && exports !== null ? exports : this).BrewTimerDialog = BrewTimerDialog;
version https://git-lfs.github.com/spec/v1 oid sha256:4de0b070810ee2426ad8217356f1347d97e741e934a45bc31ea107f04eaf450b size 5528
/* * AngularJs Fullcalendar Wrapper for the JQuery FullCalendar * API @ http://arshaw.com/fullcalendar/ * * Angular Calendar Directive that takes in the [eventSources] nested array object as the ng-model and watches it deeply changes. * Can also take in multiple event urls as a source object(s) and feed the events per view. * The calendar will watch any eventSource array and update itself when a change is made. * */ angular.module('ui.calendar', []) .constant('uiCalendarConfig', {calendars: {}}) .controller('uiCalendarCtrl', ['$scope', '$locale', function( $scope, $locale){ var sources = $scope.eventSources, extraEventSignature = $scope.calendarWatchEvent ? $scope.calendarWatchEvent : angular.noop, wrapFunctionWithScopeApply = function(functionToWrap){ return function(){ // This may happen outside of angular context, so create one if outside. if ($scope.$root.$$phase) { return functionToWrap.apply(this, arguments); } else { var args = arguments; var self = this; return $scope.$root.$apply(function(){ return functionToWrap.apply(self, args); }); } }; }; var eventSerialId = 1; // @return {String} fingerprint of the event object and its properties this.eventFingerprint = function(e) { if (!e._id) { e._id = eventSerialId++; } var extraSignature = extraEventSignature({event: e}) || ''; var start = moment.isMoment(e.start) ? e.start.unix() : (e.start ? moment(e.start).unix() : ''); var end = moment.isMoment(e.end) ? e.end.unix() : (e.end ? moment(e.end).unix() : ''); // This extracts all the information we need from the event. http://jsperf.com/angular-calendar-events-fingerprint/3 return "" + e._id + (e.id || '') + (e.title || '') + (e.url || '') + start + end + (e.allDay || '') + (e.className || '') + extraSignature; }; var sourceSerialId = 1, sourceEventsSerialId = 1; // @return {String} fingerprint of the source object and its events array this.sourceFingerprint = function(source) { var fp = '' + (source.__id || (source.__id = sourceSerialId++)), events = angular.isObject(source) && source.events; if (events) { fp = fp + '-' + (events.__id || (events.__id = sourceEventsSerialId++)); } return fp; }; // @return {Array} all events from all sources this.allEvents = function() { // do sources.map(&:events).flatten(), but we don't have flatten var arraySources = []; for (var i = 0, srcLen = sources.length; i < srcLen; i++) { var source = sources[i]; if (angular.isArray(source)) { // event source as array arraySources.push(source); } else if(angular.isObject(source) && angular.isArray(source.events)){ // event source as object, ie extended form var extEvent = {}; for(var key in source){ if(key !== '_id' && key !== 'events'){ extEvent[key] = source[key]; } } for(var eI = 0;eI < source.events.length;eI++){ angular.extend(source.events[eI],extEvent); } arraySources.push(source.events); } } return Array.prototype.concat.apply([], arraySources); }; // Track changes in array of objects by assigning id tokens to each element and watching the scope for changes in the tokens // @param {Array|Function} arraySource array of objects to watch // @param tokenFn {Function} that returns the token for a given object // @return {Object} // subscribe: function(scope, function(newTokens, oldTokens)) // called when source has changed. return false to prevent individual callbacks from firing // onAdded/Removed/Changed: // when set to a callback, called each item where a respective change is detected this.changeWatcher = function(arraySource, tokenFn) { var self; var getTokens = function() { var array = angular.isFunction(arraySource) ? arraySource() : arraySource; var result = [], token, el; for (var i = 0, n = array.length; i < n; i++) { el = array[i]; token = tokenFn(el); map[token] = el; result.push(token); } return result; }; // @param {Array} a // @param {Array} b // @return {Array} elements in that are in a but not in b // @example // subtractAsSets([6, 100, 4, 5], [4, 5, 7]) // [6, 100] var subtractAsSets = function(a, b) { var result = [], inB = {}, i, n; for (i = 0, n = b.length; i < n; i++) { inB[b[i]] = true; } for (i = 0, n = a.length; i < n; i++) { if (!inB[a[i]]) { result.push(a[i]); } } return result; }; // Map objects to tokens and vice-versa var map = {}; // Compare newTokens to oldTokens and call onAdded, onRemoved, and onChanged handlers for each affected event respectively. var applyChanges = function(newTokens, oldTokens) { var i, n, el, token; var replacedTokens = {}; var removedTokens = subtractAsSets(oldTokens, newTokens); for (i = 0, n = removedTokens.length; i < n; i++) { var removedToken = removedTokens[i]; el = map[removedToken]; delete map[removedToken]; var newToken = tokenFn(el); // if the element wasn't removed but simply got a new token, its old token will be different from the current one if (newToken === removedToken) { self.onRemoved(el); } else { replacedTokens[newToken] = removedToken; self.onChanged(el); } } var addedTokens = subtractAsSets(newTokens, oldTokens); for (i = 0, n = addedTokens.length; i < n; i++) { token = addedTokens[i]; el = map[token]; if (!replacedTokens[token]) { self.onAdded(el); } } }; return self = { subscribe: function(scope, onArrayChanged) { scope.$watch(getTokens, function(newTokens, oldTokens) { var notify = !(onArrayChanged && onArrayChanged(newTokens, oldTokens) === false); if (notify) { applyChanges(newTokens, oldTokens); } }, true); }, onAdded: angular.noop, onChanged: angular.noop, onRemoved: angular.noop }; }; this.getFullCalendarConfig = function(calendarSettings, uiCalendarConfig){ var config = {}; angular.extend(config, uiCalendarConfig); angular.extend(config, calendarSettings); angular.forEach(config, function(value,key){ if (typeof value === 'function'){ config[key] = wrapFunctionWithScopeApply(config[key]); } }); return config; }; this.getLocaleConfig = function(fullCalendarConfig) { if (!fullCalendarConfig.lang || fullCalendarConfig.useNgLocale) { // Configure to use locale names by default var tValues = function(data) { // convert {0: "Jan", 1: "Feb", ...} to ["Jan", "Feb", ...] var r, k; r = []; for (k in data) { r[k] = data[k]; } return r; }; var dtf = $locale.DATETIME_FORMATS; return { monthNames: tValues(dtf.MONTH), monthNamesShort: tValues(dtf.SHORTMONTH), dayNames: tValues(dtf.DAY), dayNamesShort: tValues(dtf.SHORTDAY) }; } return {}; }; }]) .directive('uiCalendar', ['uiCalendarConfig', function(uiCalendarConfig) { return { restrict: 'A', scope: {eventSources:'=ngModel',calendarWatchEvent: '&'}, controller: 'uiCalendarCtrl', link: function(scope, elm, attrs, controller) { var sources = scope.eventSources, sourcesChanged = false, calendar, eventSourcesWatcher = controller.changeWatcher(sources, controller.sourceFingerprint), eventsWatcher = controller.changeWatcher(controller.allEvents, controller.eventFingerprint), options = null; function getOptions(){ var calendarSettings = attrs.uiCalendar ? scope.$parent.$eval(attrs.uiCalendar) : {}, fullCalendarConfig; fullCalendarConfig = controller.getFullCalendarConfig(calendarSettings, uiCalendarConfig); var localeFullCalendarConfig = controller.getLocaleConfig(fullCalendarConfig); angular.extend(localeFullCalendarConfig, fullCalendarConfig); options = { eventSources: sources, eventRender: function(event, element) { element.find('.fc-title').append("<br/>" + event.description); } }; angular.extend(options, localeFullCalendarConfig); //remove calendars from options options.calendars = null; var options2 = {}; for(var o in options){ if(o !== 'eventSources'){ options2[o] = options[o]; } } return JSON.stringify(options2); } scope.destroyCalendar = function(){ if(calendar && calendar.fullCalendar){ calendar.fullCalendar('destroy'); } if(attrs.calendar) { calendar = uiCalendarConfig.calendars[attrs.calendar] = $(elm).html(''); } else { calendar = $(elm).html(''); } }; scope.initCalendar = function(){ if (!calendar) { calendar = angular.element(elm).html(''); } calendar.fullCalendar(options); if(attrs.calendar) { uiCalendarConfig.calendars[attrs.calendar] = calendar; } }; scope.$on('$destroy', function() { scope.destroyCalendar(); }); eventSourcesWatcher.onAdded = function(source) { if (calendar && calendar.fullCalendar) { calendar.fullCalendar(options); if (attrs.calendar) { uiCalendarConfig.calendars[attrs.calendar] = calendar; } calendar.fullCalendar('addEventSource', source); sourcesChanged = true; } }; eventSourcesWatcher.onRemoved = function(source) { if (calendar && calendar.fullCalendar) { calendar.fullCalendar('removeEventSource', source); sourcesChanged = true; } }; eventSourcesWatcher.onChanged = function() { if (calendar && calendar.fullCalendar) { calendar.fullCalendar('refetchEvents'); sourcesChanged = true; } }; eventsWatcher.onAdded = function(event) { if (calendar && calendar.fullCalendar) { calendar.fullCalendar('renderEvent', event, (event.stick ? true : false)); } }; eventsWatcher.onRemoved = function(event) { if (calendar && calendar.fullCalendar) { calendar.fullCalendar('removeEvents', event._id); } }; eventsWatcher.onChanged = function(event) { if (calendar && calendar.fullCalendar) { var clientEvents = calendar.fullCalendar('clientEvents', event._id); for (var i = 0; i < clientEvents.length; i++) { var clientEvent = clientEvents[i]; clientEvent = angular.extend(clientEvent, event); calendar.fullCalendar('updateEvent', clientEvent); } } }; eventSourcesWatcher.subscribe(scope); eventsWatcher.subscribe(scope, function() { if (sourcesChanged === true) { sourcesChanged = false; // return false to prevent onAdded/Removed/Changed handlers from firing in this case return false; } }); scope.$watch(getOptions, function(newValue, oldValue) { if(newValue !== oldValue) { scope.destroyCalendar(); scope.initCalendar(); } else if((newValue && angular.isUndefined(calendar))) { scope.initCalendar(); } }); } }; }]);
var query = run.require('src/parse'); QUnit.test('Simple.', function(assert) { var template = "test.#test:id[test].{{test}}"; assert.deepEqual(query.parse(template), [ [ // test{{test2test}} {type: '_', name: [{constant: 'test'}]} ],[ // *** {type: '#', name: [{constant: 'test'}]}, {type: ':', name: [{constant: 'id'}], prop: [{constant: 'test'}]} ],[ // test:id[test={{test}}] {type: '_', name: [{breakets: 'test'}]} ]]); }); QUnit.test('Check Template AST.', function(assert) { var template = "test{{test2test}}.***.test:id[test={{test}}].[test]"; assert.deepEqual(query.parse(template), [ [ // test{{test2test}} {type: '_', name: [{constant: 'test'},{breakets: 'test2test'}]} ],[ // *** {type: '_', name: [{wildcard: 3}]} ],[ // test:id[test={{test}}] {type: '_', name: [{constant: 'test'}]}, {type: ':', name: [{constant: 'id'}], prop: [{constant: 'test'}], assert: '=', value: [{breakets: 'test'}]}, ],[ // [test] {type: '[', prop: [{constant: 'test'}]} ]]); });
var dkindred; (function (dkindred) { var layout; (function (layout) { 'use strict'; angular .module('dkindred.layout', ['dhSimpleGD']); })(layout = dkindred.layout || (dkindred.layout = {})); })(dkindred || (dkindred = {}));
/** * Extends the target object with properties from another object. */ module.exports.extend = function(target, object) { var property, src, copy; for (property in object) { if (target[property] === undefined) { copy = object[property]; if (typeof copy === object) { target[property] = extend(target[property] || {}, copy) } else if (copy !== undefined) { target[property] = copy; } } } return target; }
'use strict'; var argv = require('minimist')(process.argv.slice(2), { alias: { 'var': 'variable', 'V': 'variable', 'h': 'help', 'v': 'version' }, string: ['_'], boolean: ['help', 'version'] }); if (argv.version) { console.log(require('./package.json').version); } else if (argv.help || argv._.length === 0) { var sumUp = require('sum-up'); var yellow = require('chalk').yellow; var pkg = require('./package.json'); console.log([ sumUp(pkg), '', 'Usage: ' + pkg.name + ' <url1> <url2> [<url3> ...] --variable <variable>', '', yellow('--variable, --var, -V') + ' Specify a required global variable', '', 'Options:', yellow('--no-min, ') + ' Do not minify output', yellow('--help, -h') + ' Print usage information', yellow('--version, -v') + ' Print version', '' ].join('\n')); } else if (argv._.length < 2) { process.stderr.write('More than 2 URLs required.\n', function() { process.exit(1); }); } else if (argv.variable === undefined || argv.variable === true) { process.stderr.write('--variable <variable> required.\n', function() { process.exit(1); }); } else { console.log(require('./')(argv.variable, argv._, {min: argv.min})); }
var app = angular.module("app", ['jtt_footballdata']); app.controller('controller', ['$scope', 'footballdataFactory', function($scope, footballdataFactory) { var apiKey = 'e42cb6a6ecc949c8897e06d284a55e05'; footballdataFactory.getSeasons({ season: '2015', apiKey: apiKey, }).then(function(_data){ console.info("getSeasons", _data); }); footballdataFactory.getSeason({ id: '426', apiKey: apiKey, }).then(function(_data){ console.info("getSeason", _data); }); footballdataFactory.getFixtures({ apiKey: apiKey, }).then(function(_data){ console.info("getFixtures", _data); }); footballdataFactory.getFixture({ id: 155048, apiKey: apiKey, }).then(function(_data){ console.info("getFixture", _data); }); footballdataFactory.getFixturesByTeam({ id: 5, apiKey: apiKey, }).then(function(_data){ console.info("getFixturesByTeam", _data); }); footballdataFactory.getTeam({ id: 5, apiKey: apiKey, }).then(function(_data){ console.info("getTeam", _data); }); footballdataFactory.getPlayersByTeam({ id: 5, apiKey: apiKey, }).then(function(_data){ console.info("getPlayersByTeam", _data); }); footballdataFactory.getTeamsBySeason({ id: 424, apiKey: apiKey, }).then(function(_data){ console.info("getTeamsBySeason", _data); }); footballdataFactory.getLeagueTableBySeason({ id: 426, matchday: 10, apiKey: apiKey, }).then(function(_data){ console.info("getLeagueTableBySeason", _data); }); footballdataFactory.getFixturesBySeason({ id: 426, matchday: 10, apiKey: apiKey, }).then(function(_data){ console.info("getFixturesBySeason", _data); }); }]);
'use strict'; /* jshint ignore:start */ /** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ /* jshint ignore:end */ var _ = require('lodash'); /* jshint ignore:line */ var Domain = require('../base/Domain'); /* jshint ignore:line */ var V1 = require('./accounts/V1'); /* jshint ignore:line */ /* jshint ignore:start */ /** * Initialize accounts domain * * @constructor Twilio.Accounts * * @property {Twilio.Accounts.V1} v1 - v1 version * @property {Twilio.Accounts.V1.AuthTokenPromotionList} authTokenPromotion - * authTokenPromotion resource * @property {Twilio.Accounts.V1.CredentialList} credentials - credentials resource * @property {Twilio.Accounts.V1.SecondaryAuthTokenList} secondaryAuthToken - * secondaryAuthToken resource * * @param {Twilio} twilio - The twilio client */ /* jshint ignore:end */ function Accounts(twilio) { Domain.prototype.constructor.call(this, twilio, 'https://accounts.twilio.com'); // Versions this._v1 = undefined; } _.extend(Accounts.prototype, Domain.prototype); Accounts.prototype.constructor = Accounts; Object.defineProperty(Accounts.prototype, 'v1', { get: function() { this._v1 = this._v1 || new V1(this); return this._v1; } }); Object.defineProperty(Accounts.prototype, 'authTokenPromotion', { get: function() { return this.v1.authTokenPromotion; } }); Object.defineProperty(Accounts.prototype, 'credentials', { get: function() { return this.v1.credentials; } }); Object.defineProperty(Accounts.prototype, 'secondaryAuthToken', { get: function() { return this.v1.secondaryAuthToken; } }); module.exports = Accounts;
version https://git-lfs.github.com/spec/v1 oid sha256:5154464848b09225d55b45925abc699decd28931e96e58e6b34a7b5191720aa2 size 53542
define([ './demo.tpl.html' ], function (template) { // @ngInject function demoState ($stateProvider, $urlRouterProvider) { $stateProvider.state('rb-radio-control', { url: '/rb-radio-control', controller: 'demo-rb-radio-control-ctrl as demoCtrl', template: template }); } return demoState; });
/** @constructor */ ScalaJS.c.scala_collection_MapLike$$anon$1 = (function() { ScalaJS.c.scala_collection_AbstractIterator.call(this); this.iter$2 = null }); ScalaJS.c.scala_collection_MapLike$$anon$1.prototype = new ScalaJS.inheritable.scala_collection_AbstractIterator(); ScalaJS.c.scala_collection_MapLike$$anon$1.prototype.constructor = ScalaJS.c.scala_collection_MapLike$$anon$1; ScalaJS.c.scala_collection_MapLike$$anon$1.prototype.iter__p2__Lscala_collection_Iterator = (function() { return this.iter$2 }); ScalaJS.c.scala_collection_MapLike$$anon$1.prototype.hasNext__Z = (function() { return this.iter__p2__Lscala_collection_Iterator().hasNext__Z() }); ScalaJS.c.scala_collection_MapLike$$anon$1.prototype.next__O = (function() { return ScalaJS.as.scala_Tuple2(this.iter__p2__Lscala_collection_Iterator().next__O()).$$und1__O() }); ScalaJS.c.scala_collection_MapLike$$anon$1.prototype.init___Lscala_collection_MapLike = (function($$outer) { ScalaJS.c.scala_collection_AbstractIterator.prototype.init___.call(this); this.iter$2 = $$outer.iterator__Lscala_collection_Iterator(); return this }); /** @constructor */ ScalaJS.inheritable.scala_collection_MapLike$$anon$1 = (function() { /*<skip>*/ }); ScalaJS.inheritable.scala_collection_MapLike$$anon$1.prototype = ScalaJS.c.scala_collection_MapLike$$anon$1.prototype; ScalaJS.is.scala_collection_MapLike$$anon$1 = (function(obj) { return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_collection_MapLike$$anon$1))) }); ScalaJS.as.scala_collection_MapLike$$anon$1 = (function(obj) { if ((ScalaJS.is.scala_collection_MapLike$$anon$1(obj) || (obj === null))) { return obj } else { ScalaJS.throwClassCastException(obj, "scala.collection.MapLike$$anon$1") } }); ScalaJS.isArrayOf.scala_collection_MapLike$$anon$1 = (function(obj, depth) { return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_collection_MapLike$$anon$1))) }); ScalaJS.asArrayOf.scala_collection_MapLike$$anon$1 = (function(obj, depth) { if ((ScalaJS.isArrayOf.scala_collection_MapLike$$anon$1(obj, depth) || (obj === null))) { return obj } else { ScalaJS.throwArrayCastException(obj, "Lscala.collection.MapLike$$anon$1;", depth) } }); ScalaJS.data.scala_collection_MapLike$$anon$1 = new ScalaJS.ClassTypeData({ scala_collection_MapLike$$anon$1: 0 }, false, "scala.collection.MapLike$$anon$1", ScalaJS.data.scala_collection_AbstractIterator, { scala_collection_MapLike$$anon$1: 1, scala_collection_AbstractIterator: 1, scala_collection_Iterator: 1, scala_collection_TraversableOnce: 1, scala_collection_GenTraversableOnce: 1, java_lang_Object: 1 }); ScalaJS.c.scala_collection_MapLike$$anon$1.prototype.$classData = ScalaJS.data.scala_collection_MapLike$$anon$1; //@ sourceMappingURL=MapLike$$anon$1.js.map
var breadcrumbs=[['-1',"",""],['2',"SOLUTION-WIDE PROPERTIES Reference","topic_0000000000000C16.html"],['2267',"Tlece.Recruitment.Models.RecruitmentPlanning Namespace","topic_0000000000000692.html"],['2390',"InterviewerDto Class","topic_00000000000007F8.html"],['2391',"Properties","topic_00000000000007F8_props--.html"],['2394',"LastName Property","topic_00000000000007FB.html"]];
/** * @author goliatone * @url https://github.com/goliatone/gpub * @copyright (c) 2013 goliatone * @license MIT * @title Gpub: Simple pub/sub * @overview Gpub is an Event Dispatcher library. Or pub/sub. * @module Gpub */ /*global define:true*/ /* jshint strict: false */ define('gpub', function($) { //////////////////////////////////////////////////////// /// PRIVATE METHODS //////////////////////////////////////////////////////// var _publish = function(list, args, options){ var event, i, l; //Invoke callbacks. We need length on each iter //cose it could change, off. // args = _slice.call(arguments, 1); //var o; for(i = 0, l = list.length; i < l; i++){ event = list[i]; if(!event) continue; console.log('event', event); //We want to have a dif. options object //for each callback; options.event = event; options.target = event.target;//shortcut to access target. // o = $.extend({},options); if(event.callback.apply(event.scope, args) === false) break; // if(!event.callback.apply(event.scope, a)) break; } }; var _mixin = function(target, source){ if(typeof target === 'function') target = target.prototype; //TODO: Should we do Gpub.methods = ['on', 'off', 'emit', 'emits'];? Object.keys(source).forEach(function(method){ target[method] = source[method]; }); return target; }; var _slice = [].slice; //////////////////////////////////////////////////////// /// CONSTRUCTOR //////////////////////////////////////////////////////// /** * Gpub is a simple pub sub library. * @class Gpub * @constructor */ var Gpub = function(){}; //////////////////////////////////////////////////////// /// PUBLIC METHODS //////////////////////////////////////////////////////// /** * Register an event listener. * @param {String} topic String indicating the event type * @param {Function} callback Callback to handle event topics. * @param {Object} scope We can dynamically change the scope of * the handler. * @param {Object} options Options object that will be sent with the * event to all handler callbacks. * @return {this} */ Gpub.prototype.on = function(topic, callback, scope, options){ //Create _callbacks, unless we have it var topics = this.callbacks(topic); //Create an array for the given topic key, unless we have it, //then append the callback to the array // topic.push(callback); var event = {}; event.topic = topic; event.callback = callback; event.scope = scope || this; event.target = this; // event.options = options || {};//_merge((options || {}),{target:this}); console.log('on', event); topics.push(event); return this; }; /** * Checks to see if the provided topic has * registered listeners and thus triggering * and event. * @param {String} topic Event type. * @return {this} */ Gpub.prototype.emits = function(topic){ return this.callbacks().hasOwnProperty(topic) && this.callbacks(topic).length > 0; }; /** * Triggers an event so all registered listeners * for the `topic` will be notified. * Optionally, we can send along an options object. * * @param {String} topic Event type. * @param {Object} options Options object, sent along * in the event to all listeners * registered with `topic`. * @return {this} */ Gpub.prototype.emit = function(topic, options){ //Turn args obj into real array var args = _slice.call(arguments, 1); //get the first arg, topic name options = options || {}; //include the options into the arguments, making sure that we //send it along if we just created it here. args.push(options); var list, calls, all; //return if no callback if(!(calls = this.callbacks())) return this; //get listeners, if none and no global handlers, return. if(!(list = calls[topic]) && !calls['all']) return this; //if global handlers, append to list. //if((all = calls['all'])) list = (list || []).concat(all); if((all = calls['all'])) _publish.call(this, all, _slice.call(arguments, 0), options); // if((all = calls['all'])) _publish.call(this, all, [topic].concat(args)); if(list) _publish.call(this,list, args, options); return this; }; /** * Unregisters the given `callback` from `topic` * events. * If called without arguments, it will remove all * listeners. * TODO: If we pass `topic` but no `callback` should we * remove all listeners of `topic`? * * @param {String} topic Event type. * @param {Function} callback Listener we want to remove. * @return {this} */ Gpub.prototype.off = function(topic, callback/*, scope*/){ var list, calls, i, l; //TODO: Should we make a different Gpub::stop() method? if(!topic && !callback) this._callbacks = {}; if(!(calls = this.callbacks())) return this; if(!(list = calls[topic])) return this; for(i = 0, l = list.length; i < l; i++){ if(list[i].callback === callback) list.splice(i,1); } return this; }; /** * Returns all registered listeners for * a given `topic`. * If called without `topic` will return all * callbacks. * * Used internally. * * @param {String} topic Event type. * @return {Object|Array} * @private */ Gpub.prototype.callbacks = function(topic){ this._callbacks = this._callbacks || {}; if(!topic) return this._callbacks; return this._callbacks[topic] || (this._callbacks[topic] = []); }; //////////////////////////////////////////////////////// /// STATIC METHODS //////////////////////////////////////////////////////// /** * Observable mixin. It will add `Gpub` methods * to the given `target`. * If we provide a `constructor` it will extend * it's prototype. * * ```javascript * var Model = function(){}; * Gpub.observable(Model); * var user = new Model(); * user.on('something', function(){console.log('Hola!')}); * user.emit('something'); * ``` * * @param {Object|Function} target * @return {Object|Function} Returns the given object. */ Gpub.observable = function(target){ return _mixin(target || {}, Gpub.prototype); }; /** * It will create methods in `src` to register * handlers for all passed events. * * If we pass: * var Model = function(){}; * var events = ['change', 'sync']; * Gpub.delegable(Model.prototype, events); * var user = new Model(); * user.onsync(function(e){console.log('sync\'d', e)}); * user.onchange(function(e){console.log('changed', e)}); * user.emit('change').emit('sync'); * * By default, methods generated will be in the form * of **on**+**event**. * We can pass in a custom method name generator. * * If the passed in `src` object is not an instance * of `Gpub` it will be augmented with the mixin. * * @param {Object} src Object to extend * with methods. * @param {Array|String} events Events for which we want to * generate delegate methods. * @param {Function} eventBuilder Function to generate the delegate * method name. * @param {String} glue If we pass in a string, this * will be used to split into different * event types. * @return {Object} Returns passed in object. */ Gpub.delegable = function(src, events, eventBuilder, glue){ //TODO: DRY, make check all methods!! if(!('on' in src) || !('emit' in src)) this.observable(src); eventBuilder || (eventBuilder = function(e){ return 'on'+e;}); if(typeof events === 'string') events = events.split(glue || ' '); var method, bind = typeof src === 'function'; events.forEach(function(event){ method = function(handler){ if(!handler) return this; this.on(event, handler); return this; }; if(bind) method.bind(src); src[eventBuilder(event)] = method; }); return src; }; /** * It will monkey patch the given `src` setter * method so that it triggers a `change` and `change:<key>` * event on update. The event object carries the old value * and the current value, plus the updated property name. * * It's a quick way to generate a bindable model. * * ```javascript * var Model = function(){this.data={}}; * Model.prototype.set = function(key, value) { * this.data[key] = value; * return this; * }; * Model.prototype.get = function(key, def){ * return this.data[key] || def; * }; * Gpub.bindable(Model.prototype, 'set', 'get'); * ``` * If we don't specify a `set` or `get` value, then * `set` and `get` will be used by default. * * @param {Object} src Object to be augmented. * @param {String} set Name of `set` method in `src` * @param {String} get Name of `get` method in `src` * @param {Boolean} bind Should we bind the generated method? * @return {Object} Returns the passed in object. */ Gpub.bindable = function(src, set, get, bind){ // var bind = (typeof src === 'function'); // src = bind ? src.prototype : src; //TODO: DRY, make check all methods!! if(!('on' in src) || !('emit' in src)) this.observable(src); var _set = src[set || 'set'], _get = src[get || 'get']; var method = function(key, value){ var old = _get.call(this, key), out = _set.call(this, key, value), //TODO: _buildEvent({old:old, value:value, target:this}); evt = {old:old, value:value, property:key}; if (this.emits('change')) this.emit('change', evt); if (this.emits('change:' + key)) this.emit('change:'+key, evt); return out; }; if(bind) method.bind(src); src[set] = method; return src; }; //////////////////////////////////////////////////////// /// LEGACY METHODS: This will be removed soon. //////////////////////////////////////////////////////// /* * This is so that we can keep backwards compatibility * with old API. It will be removed soon! */ /**@deprecated*/ Gpub.prototype.publish = Gpub.prototype.emit; /**@deprecated*/ Gpub.prototype.subscribe = Gpub.prototype.on; /**@deprecated*/ Gpub.prototype.unsubscribe = Gpub.prototype.off; /**@deprecated*/ Gpub.prototype.subscribers = Gpub.prototype.emits; return Gpub; });
/** * @class Wando.ColorField * 对 Ext.form.field.Picker 的拓展,一个可用的拾色器组件。<br /> * 该组建用于grid下的columns的editor之后,其后必须添加renderer函数,其格式如下面的例子 * # Example usage * @example * * var grid = Ext.create('Ext.grid.Panel', { * title: 'Simpsons', * store: store, * columns: [ * { text: 'Name', dataIndex: 'name', field: 'textfield' }, * { text: 'Email', dataIndex: 'email', flex:1 }, * { text: 'Phone', dataIndex: 'phone', * editor: Ext.create('Wando.ColorField', { * renderer: function(value, cellmeta, record, rowIndex, columnIndex) { * if (value !== undefined){ * var color = "#" + value; * cellmeta.style = 'background-color: ' + color + '; color: ' + color * } * return value; * } * }), * } * ], * selType: 'cellmodel', * plugins: [ * Ext.create('Ext.grid.plugin.CellEditing', { * clicksToEdit: 1 * }) * ], * height: 200, * width: 400, * }); * */ Ext.define('Wando.ColorField', { extend:'Ext.form.field.Picker', alias:'widget.colorfield', requires:['Ext.picker.Color'], triggerCls:'x-form-color-trigger', createPicker:function () { var me = this; return Ext.create('Ext.picker.Color', { pickerField:me, renderTo:document.body, floating:true, hidden:true, focusOnShow:true, listeners:{ select:function (picker, selColor) { me.setValue(selColor); me.setFieldStyle('background:#' + selColor); picker.hide(); } } }); } });
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1 = require('@angular/core'); var router_1 = require('@angular/router'); var dashboard_component_1 = require('./dashboard.component'); var heroes_component_1 = require('./heroes.component'); var hero_detail_component_1 = require('./hero-detail.component'); var routes = [ { path: '', redirectTo: '/dashboard', pathMatch: 'full' }, { path: 'dashboard', component: dashboard_component_1.DashboardComponent }, { path: 'detail/:id', component: hero_detail_component_1.HeroDetailComponent }, { path: 'heroes', component: heroes_component_1.HeroesComponent } ]; var AppRoutingModule = (function () { function AppRoutingModule() { } AppRoutingModule = __decorate([ core_1.NgModule({ imports: [router_1.RouterModule.forRoot(routes)], exports: [router_1.RouterModule] }), __metadata('design:paramtypes', []) ], AppRoutingModule); return AppRoutingModule; }()); exports.AppRoutingModule = AppRoutingModule; //# sourceMappingURL=app-RoutingModule.js.map
var fs = require('fs'); var md5 = require('MD5'); var defaultOptions = { "path": "/opt/tlks.io/.cache", "ttl": 3600000 }; module.exports = function cache(options) { 'use strict'; options = options || defaultOptions; return function(req, res, next) { // Check if the user is logged var url = req.url; if (req.session.user === undefined) { var fileName = md5(url); var filePath = options.path + "/" + fileName; // check if a cached copy exists fs.exists(filePath, function(exists) { if (exists) { // check if the if the file is older than the TTL fs.stat(filePath, function(err, stats) { var now = new Date(); var diff = now - stats.mtime; if (diff < options.ttl) { console.log('Serving from caché', url, fileName); res.setHeader("Content-Type", "text/html"); fs.createReadStream(filePath).pipe(res); } else { console.log("Old cache file", url, fileName); next(); } }); } else { console.log("Not cached", url); next(); } }); } else { // serve cache only to registered users console.log("User session - not cached", url); next(); } }; };
/* global process */ var bower = require('bower'); var fs = require('fs'); var Vinyl = require('vinyl'); var PluginError = require('plugin-error'); var colors = require('ansi-colors'); var fancyLog = require('fancy-log'); var path = require('path'); var through = require('through2'); var walk = require('walk'); var inquirer = require('inquirer'); var toString = {}.toString, enablePrompt, cmd; var PLUGIN_NAME = 'gulp-bower', DEFAULT_VERBOSITY = 2, DEFAULT_CMD = 'install', DEFAULT_DIRECTORY = './bower_components', DEFAULT_INTERACTIVE = false; /* * Verbosity levels: * 0: No output * 1: Error output * 2: All output */ var log = { verbosity: DEFAULT_VERBOSITY, info: function (s) { if (this.verbosity > 1) { log.output(s); } }, error: function (s) { if (this.verbosity > 0) { log.output(colors.red(s)); } }, output: function (s) { fancyLog.info(s); } }; /** * Gulp bower plugin * * @param {(object | string)} opts options object or directory string, see opts.directory * @param {string} opts.cmd bower command (default: install) * @param {string} opts.cwd current working directory (default: process.cwd()) * @param {string} opts.directory bower components directory (default: .bowerrc config or 'bower_components') * @param {boolean} opts.interactive enable prompting from bower (default: false) * @param {number} opts.verbosity set logging level from 0 (no output) to 2 for info (default: 2) */ function gulpBower(opts, cmdArguments) { opts = parseOptions(opts); log.info('Using cwd: ' + opts.cwd); log.info('Using bower dir: ' + opts.directory); cmdArguments = createCmdArguments(cmdArguments, opts); var bowerCommand = getBowerCommand(cmd); var stream = through.obj(function (file, enc, callback) { this.push(file); callback(); }); bowerCommand.apply(bower.commands, cmdArguments) .on('log', function (result) { log.info(['bower', colors.cyan(result.id), result.message].join(' ')); }) .on('prompt', function (prompts, callback) { if (enablePrompt === true) { inquirer.prompt(prompts, callback); } else { var error = 'Can\'t resolve suitable dependency version.'; log.error(error); log.error('Set option { interactive: true } to select.'); throw new PluginError(PLUGIN_NAME, error); } }) .on('error', function (error) { stream.emit('error', new PluginError(PLUGIN_NAME, error)); stream.emit('end'); }) .on('end', function () { writeStreamToFs(opts, stream); }); return stream; } /** * Parse plugin options * * @param {object | string} opts options object or directory string */ function parseOptions(opts) { opts = opts || {}; if (toString.call(opts) === '[object String]') { opts = { directory: opts }; } opts.cwd = opts.cwd || process.cwd(); log.verbosity = toString.call(opts.verbosity) === '[object Number]' ? opts.verbosity : DEFAULT_VERBOSITY; delete (opts.verbosity); cmd = opts.cmd || DEFAULT_CMD; delete (opts.cmd); // enable bower prompting but ignore the actual prompt if interactive == false enablePrompt = opts.interactive || DEFAULT_INTERACTIVE; opts.interactive = true; if (!opts.directory) { opts.directory = getDirectoryFromBowerRc(opts.cwd) || DEFAULT_DIRECTORY; } return opts; } /** * Detect .bowerrc file and read directory from file * * @param {string} cwd current working directory * @returns {string} found directory or empty string */ function getDirectoryFromBowerRc(cwd) { var bowerrc = path.join(cwd, '.bowerrc'); if (!fs.existsSync(bowerrc)) { return ''; } var bower_config = {}; try { bower_config = JSON.parse(fs.readFileSync(bowerrc)); } catch (err) { return ''; } return bower_config.directory; } /** * Create command arguments * * @param {any} cmdArguments * @param {object} opts options object */ function createCmdArguments(cmdArguments, opts) { if (toString.call(cmdArguments) !== '[object Array]') { cmdArguments = []; } if (toString.call(cmdArguments[0]) !== '[object Array]') { cmdArguments[0] = []; } cmdArguments[1] = cmdArguments[1] || {}; cmdArguments[2] = opts; return cmdArguments; } /** * Get bower command instance * * @param {string} cmd bower commands, e.g. 'install' | 'update' | 'cache clean' etc. * @returns {object} bower instance initialised with commands */ function getBowerCommand(cmd) { // bower has some commands that are provided in a nested object structure, e.g. `bower cache clean`. var bowerCommand; // clean up the command given, to avoid unnecessary errors cmd = cmd.trim(); var nestedCommand = cmd.split(' '); if (nestedCommand.length > 1) { // To enable that kind of nested commands, we try to resolve those commands, before passing them to bower. for (var commandPos = 0; commandPos < nestedCommand.length; commandPos++) { if (bowerCommand) { // when the root command is already there, walk into the depth. bowerCommand = bowerCommand[nestedCommand[commandPos]]; } else { // the first time we look for the "root" commands available in bower bowerCommand = bower.commands[nestedCommand[commandPos]]; } } } else { // if the command isn't nested, just go ahead as usual bowerCommand = bower.commands[cmd]; } // try to give a good error description to the user when a bad command was passed if (bowerCommand === undefined) { throw new PluginError(PLUGIN_NAME, 'The command \'' + cmd + '\' is not available in the bower commands'); } return bowerCommand; } /** * Write stream to filesystem * * @param {object} opts options object * @param {object} stream file stream */ function writeStreamToFs(opts, stream) { var baseDir = path.join(opts.cwd, opts.directory); var walker = walk.walk(baseDir); walker.on('errors', function (root, stats, next) { stream.emit('error', new PluginError(PLUGIN_NAME, stats.error)); next(); }); walker.on('directory', function (root, stats, next) { next(); }); walker.on('file', function (root, stats, next) { var filePath = path.resolve(root, stats.name); fs.readFile(filePath, function (error, data) { if (error) { stream.emit('error', new PluginError(PLUGIN_NAME, error)); } else { stream.write(new Vinyl({ path: path.relative(baseDir, filePath), contents: data })); } next(); }); }); walker.on('end', function () { stream.emit('end'); stream.emit('finish'); }); } module.exports = gulpBower;
import Pipe from '../classes/Pipe'; export function generateGrid(size,startPipeNum,endPipeNum){ let array2d = []; for(x = 0; x < size; x++){ var innerArray = []; for(y = 0; y < size; y++){ var pipe = new Pipe(x,y,Math.floor((Math.random()*4)),Math.floor((Math.random()*3))); innerArray.push(pipe); } array2d.push(innerArray); } var i = 0; while(i < startPipeNum){ var randomX = Math.floor((Math.random()*array2d.length)); var randomY = Math.floor((Math.random()*array2d[randomX].length)); if(array2d[randomX][randomY].spriteNum!=4){ var direction = checkSides(randomX,randomY,array2d); var pipe = new Pipe(randomX,randomY,4,direction,true); array2d[randomX][randomY] = pipe; i++; } } i = 0; while(i < endPipeNum){ var randomX = Math.floor((Math.random()*array2d.length)); var randomY = Math.floor((Math.random()*array2d[randomX].length)); if(array2d[randomX][randomY].spriteNum!=4){ var direction = checkSides(randomX,randomY,array2d); var pipe = new Pipe(randomX,randomY,4,direction,false); array2d[randomX][randomY] = pipe; i++; } } return array2d; } function checkSides(randomX,randomY,array2d){ var direction; if(randomX==0){ if(randomY==0){ direction = Math.floor((Math.random()*2)); } else if (randomY==(array2d[randomX].length-1)){ switch (Math.floor((Math.random()*2))){ case 0:{ direction = 3; break; } case 1:{ direction = 0; break; } } } else { switch (Math.floor((Math.random()*3))){ case 0:{ direction = 3; break; } case 1:{ direction = 0; break; } case 2:{ direction = 1; break; } } } } else if (randomX == array2d.length-1){ if(randomY==0){ switch (Math.floor((Math.random()*2))){ case 0:{ direction = 2; break; } case 1:{ direction = 1; break; } } } else if (randomY==(array2d[randomX].length-1)){ switch (Math.floor((Math.random()*2))){ case 0:{ direction = 3; break; } case 1:{ direction = 2; break; } } } else { switch (Math.floor((Math.random()*3))){ case 0:{ direction = 3; break; } case 1:{ direction = 2; break; } case 2:{ direction = 1; break; } } } } else if(randomY==0){ direction = (Math.floor((Math.random()*3))); } else if (randomY==(array2d[randomX].length-1)){ switch (Math.floor((Math.random()*3))){ case 0:{ direction = 0; break; } case 1:{ direction = 2; break; } case 2:{ direction = 3; break; } } } else { direction = (Math.floor((Math.random()*4))); } return direction; } export function loadImages(){ let image1 = require('../res/1.png'); let image2 = require('../res/2.png'); let image3 = require('../res/3.png'); let image4 = require('../res/4.png'); let image5 = require('../res/5.png'); let image1_2 = require('../res/11.png'); let image2_2 = require('../res/22.png'); let image3_2 = require('../res/33.png'); let image4_2 = require('../res/44.png'); let image5_2 = require('../res/55.png'); let images = { img1: image1, img1_2: image1_2, img2: image2, img2_2: image2_2, img3: image3, img3_2: image3_2, img4: image4, img4_2: image4_2, img5: image5, img5_2: image5_2 } return images; }
import { resolve } from 'path' import { withTempDirectory } from 'source/node/fs/Directory.js' import { run } from 'source/node/run.js' const { info = console.log } = globalThis const runFuncWithExposeGC = async (...funcList) => withTempDirectory( async (pathTemp) => run([ process.execPath, '--expose-gc', // allow `global.gc()` call '--max-old-space-size=32', // limit max memory usage for faster OOM '--eval', `(${funcList.reduce((o, func) => `(${func})(global.gc, ${o})`, 'undefined')})` ], { maxBuffer: 8 * 1024 * 1024, cwd: pathTemp, // generate OOM report under temp path quiet: !__DEV__ }).promise.catch((error) => error), resolve(__dirname, 'temp-gitignore/') ) const createTestFunc = (expectExitCode = 0, ...funcList) => async () => { const { code, signal, stdoutPromise, stderrPromise } = await runFuncWithExposeGC(...funcList) !__DEV__ && info(`STDOUT:\n${await stdoutPromise}\n\nSTDERR:\n${await stderrPromise}`) info(`test done, exit code: ${code}, signal: ${signal}`) if (code === expectExitCode) return info(`STDOUT:\n${await stdoutPromise}\n\nSTDERR:\n${await stderrPromise}`) throw new Error(`exitCode: ${code}, expectExitCode: ${expectExitCode}`) } const commonFunc = (triggerGC) => { const setTimeoutAsync = (wait = 0) => new Promise((resolve) => setTimeout(resolve, wait)) const formatMemory = (value) => `${String(value).padStart(10, ' ')}B` const markMemory = async () => { triggerGC() await setTimeoutAsync(10) triggerGC() const { heapUsed, heapTotal, rss, external } = process.memoryUsage() __DEV__ && console.log([ `heapUsed: ${formatMemory(heapUsed)}`, `heapTotal: ${formatMemory(heapTotal)}`, `rss: ${formatMemory(rss)}`, `external: ${formatMemory(external)}` ].join(' ')) return heapUsed // For the test we only care pure JS Object size } const appendPromiseAdder = (promise, count = 0) => { let index = 0 while (index++ !== count) promise = promise.then((result) => (result + 1)) return promise } const dropOutstandingValue = (valueList, dropCount) => { valueList = [ ...valueList ] while (dropCount !== 0) { dropCount-- let min = Infinity let minIndex = 0 let max = -Infinity let maxIndex = 0 let sum = 0 valueList.forEach((value, index) => { if (value < min) [ min, minIndex ] = [ value, index ] if (value > max) [ max, maxIndex ] = [ value, index ] sum += value }) const avg = sum / valueList.length const dropIndex = (Math.abs(avg - min) > Math.abs(avg - max)) ? minIndex : maxIndex valueList.splice(dropIndex, 1) } return valueList } const verifyPrediction = (prediction = '0±0', value = 0, message) => { if (prediction === 'SKIP') return const [ valueExpect, valueOffset ] = prediction.split('±').map(Number) if (Math.abs(value - valueExpect) > valueOffset) throw new Error(`${message || 'prediction failed'}: expect ${prediction}, but get ${value}`) } const runSubjectPredictionTest = async ({ testKeepRound, testDropRound, testSubjectCount, title, predictionAvg, funcCreateSubject }) => { console.log(`[TEST] ${title} `.padEnd(64, '=')) // setup const resultList = [] let testRound = 0 while (testRound !== (testKeepRound + testDropRound)) { // pre-fill resultList resultList[ testRound ] = 0 testRound++ } testRound = 0 while (testRound !== (testKeepRound + testDropRound)) { // console.log(` #${testRound}`) const subjectList = [] subjectList.length = testSubjectCount // sort of pre-fill subjectList const heapUsedBefore = await markMemory(` [BEFORE] subjectList: ${subjectList.length}`) // fill subject let index = 0 while (index !== testSubjectCount) { subjectList[ index ] = await funcCreateSubject(index) index++ } const heapUsedAfter = await markMemory(` [AFTER] subjectList: ${subjectList.length}`) const headUsedDiff = heapUsedAfter - heapUsedBefore console.log(` #${String(testRound).padStart(3, '0')} headUsedDiff: ${formatMemory(headUsedDiff)}, perSubject: ${formatMemory((headUsedDiff / subjectList.length).toFixed(2))}`) resultList[ testRound ] = headUsedDiff testRound++ } const mainResultList = dropOutstandingValue(resultList, testDropRound) // drop some outstanding value // console.log({ resultList, mainResultList }) const resultAvg = mainResultList.reduce((o, v) => o + v, 0) / mainResultList.length console.log([ `[RESULT] ${title} (${testDropRound} dropped) `.padEnd(64, '-'), `- avgHeadUsedDiff: ${formatMemory(resultAvg.toFixed(2))}`, `- avgPerSubject: ${formatMemory((resultAvg / testSubjectCount).toFixed(2))}` ].join('\n')) verifyPrediction(predictionAvg, resultAvg / testSubjectCount, title) } const runSubjectPredictionTestConfig = async ({ testConfigName, testKeepRound, testDropRound, testSubjectCount, testList }) => { console.log(`[main] testConfigName: ${testConfigName}, testList: ${testList.length}`) for (const [ title, predictionAvg, funcCreateSubject ] of testList) { await runSubjectPredictionTest({ testKeepRound, testDropRound, testSubjectCount, title, predictionAvg, funcCreateSubject }).catch((error) => { console.error('[main] error:', error) process.exit(1) }) } console.log('[main] done') } return { setTimeoutAsync, formatMemory, markMemory, appendPromiseAdder, dropOutstandingValue, verifyPrediction, runSubjectPredictionTest, runSubjectPredictionTestConfig } } export { runFuncWithExposeGC, createTestFunc, commonFunc }
const path = require('path'); const webpack = require('webpack'); const chalk = require('chalk'); const ora = require('ora'); const getAllConfig = require('./config.script'); const configs = getAllConfig(); /** * 打印出错误对象 * @param {Error} e - 错误对象 */ function logError(e) { console.log(e); } /** * 转化字节数为 KB * @param {Number} byte - 字节数 * @return {Number} - KB */ function getSize(byte) { return `${(byte / 1024).toFixed(1)}kb`; } /** * 通过 webpack api 构建组件 * @param {Object} config - webpack 配置 * @return {Promise} - 通过 promise 返回构建结果 */ function buildLib(config) { return new Promise((resolve, reject) => { const spinner = ora().start(); webpack(config, (err, stats) => { // 处理配置错误 if (err) { spinner.stop(); return reject(err); } // 处理编译错误 if (stats.hasErrors()) { spinner.stop(); return reject(stats.toJson().errors); } const info = stats.toJson({ modules: false, children: false, chunks: false, chunkModules: false, entrypoints: false, }); const libPath = path.relative(process.cwd(), path.join(info.outputPath, info.assetsByChunkName.main)); const text = `${libPath} ${chalk.green(getSize(info.assets[0].size))}`; spinner.succeed(`${chalk.cyan('[构建]')} ${chalk.yellow('组件')} : ${text}`); resolve(); }); }); } /** * 启动函数 */ function build() { let index = 0; const total = configs.length; const next = () => { buildLib(configs[index]) .then(() => { index++; if (index < total) { next(); } }) .catch(logError); }; next(); } // let's begging build();
var Class = require('igneousjs/class'); var console = process.console; var Result = Class.extend({ constructor: function (opts) { opts = opts || {}; this.args = opts.args; this.value = opts.value; this.createdDate = opts.createdDate || new Date(); } }); module.exports = Result;
'use strict'; exports.__esModule = true; var _Mesh2 = require('./Mesh'); var _Mesh3 = _interopRequireDefault(_Mesh2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * The Plane allows you to draw a texture across several points and them manipulate these points * *```js * for (let i = 0; i < 20; i++) { * points.push(new PIXI.Point(i * 50, 0)); * }; * let Plane = new PIXI.Plane(PIXI.Texture.fromImage("snake.png"), points); * ``` * * @class * @extends PIXI.mesh.Mesh * @memberof PIXI.mesh * */ var Plane = function (_Mesh) { _inherits(Plane, _Mesh); /** * @param {PIXI.Texture} texture - The texture to use on the Plane. * @param {number} verticesX - The number of vertices in the x-axis * @param {number} verticesY - The number of vertices in the y-axis */ function Plane(texture, verticesX, verticesY) { _classCallCheck(this, Plane); /** * Tracker for if the Plane is ready to be drawn. Needed because Mesh ctor can * call _onTextureUpdated which could call refresh too early. * * @member {boolean} * @private */ var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); _this._ready = true; _this.verticesX = verticesX || 10; _this.verticesY = verticesY || 10; _this.drawMode = _Mesh3.default.DRAW_MODES.TRIANGLES; _this.refresh(); return _this; } /** * Refreshes plane coordinates * */ Plane.prototype._refresh = function _refresh() { var texture = this._texture; var total = this.verticesX * this.verticesY; var verts = []; var colors = []; var uvs = []; var indices = []; var segmentsX = this.verticesX - 1; var segmentsY = this.verticesY - 1; var sizeX = texture.width / segmentsX; var sizeY = texture.height / segmentsY; for (var i = 0; i < total; i++) { var x = i % this.verticesX; var y = i / this.verticesX | 0; verts.push(x * sizeX, y * sizeY); uvs.push(x / segmentsX, y / segmentsY); } // cons var totalSub = segmentsX * segmentsY; for (var _i = 0; _i < totalSub; _i++) { var xpos = _i % segmentsX; var ypos = _i / segmentsX | 0; var value = ypos * this.verticesX + xpos; var value2 = ypos * this.verticesX + xpos + 1; var value3 = (ypos + 1) * this.verticesX + xpos; var value4 = (ypos + 1) * this.verticesX + xpos + 1; indices.push(value, value2, value3); indices.push(value2, value4, value3); } // console.log(indices) this.vertices = new Float32Array(verts); this.uvs = new Float32Array(uvs); this.colors = new Float32Array(colors); this.indices = new Uint16Array(indices); this.indexDirty = true; this.multiplyUvs(); }; /** * Clear texture UVs when new texture is set * * @private */ Plane.prototype._onTextureUpdate = function _onTextureUpdate() { _Mesh3.default.prototype._onTextureUpdate.call(this); // wait for the Plane ctor to finish before calling refresh if (this._ready) { this.refresh(); } }; return Plane; }(_Mesh3.default); exports.default = Plane; //# sourceMappingURL=Plane.js.map
function initMap() { var image = { url: 'https://cdn2.iconfinder.com/data/icons/IconsLandVistaMapMarkersIconsDemo/256/MapMarker_Flag_Azure.png', scaledSize: new google.maps.Size(50, 50), origin: new google.maps.Point(0, 0), anchor: new google.maps.Point(30, 50) } var map = new google.maps.Map(document.getElementById('map'), { zoom: 7, center: {lat: 58.0490916, lng: 26.5021351}, scrollwheel: false, navigationControl: false, mapTypeControl: false, scaleControl: false, draggable: false, zoomControl: false, disableDoubleClickZoom: true, streetViewControl: false, }); var marker = new google.maps.Marker({ position: {lat: 57.72281, lng: 27.048186}, map: map, icon: image, title: 'Haanja staadion' }); var marker = new google.maps.Marker({ position: {lat: 58.0490916, lng: 26.5021351}, map: map, icon: image, title: 'Tehvandi staadion' }); }
/** * @file reactionRolesGroup command * @author Sankarsan Kampa (a.k.a k3rn31p4nic) * @license GPL-3.0 */ exports.exec = async (Bastion, message, args) => { let reactionRolesGroupModels = await Bastion.database.models.reactionRolesGroup.findAll({ fields: [ 'messageID' ], where: { guildID: message.guild.id } }); if (!args.roles) { let reactionRolesGroups = reactionRolesGroupModels.map(model => model.dataValues.messageID); if (args.remove) { if (reactionRolesGroups.includes(args.remove)) { await Bastion.database.models.reactionRolesGroup.destroy({ where: { messageID: args.remove, guildID: message.guild.id } }); return message.channel.send({ embed: { color: Bastion.colors.RED, title: 'Reaction Roles Group Removed', description: `The Reaction Roles Group associated with the message ${args.remove} has been successfully removed.` } }).catch(e => { Bastion.log.error(e); }); } } if (!reactionRolesGroups.length) { return Bastion.emit('commandUsage', message, this.help); } return await message.channel.send({ embed: { color: Bastion.colors.BLUE, title: 'Reaction Roles Groups', description: reactionRolesGroups.map((group, index) => `${index + 1}. ${group}`).join('\n') } }).catch(e => { Bastion.log.error(e); }); } if (reactionRolesGroupModels && reactionRolesGroupModels.length === 2) { return Bastion.emit('error', '', 'You can\'t have more than 2 Reaction Roles Group, for now. Delete any previous Group of Reaction Roles to add new ones.', message.channel); } let roleModels = await Bastion.database.models.role.findAll({ attributes: [ 'roleID', 'emoji' ], where: { guildID: message.guild.id, emoji: { [Bastion.database.Op.not]: null } } }); let reactionRolesIDs = roleModels.map(model => model.dataValues.roleID); args.roles = args.roles.filter(role => message.guild.roles.has(role)); if (!args.roles.length) { return Bastion.emit('error', '', Bastion.i18n.error(message.guild.language, 'roleNotFound'), message.channel); } let unassignedRoleEmojis = args.roles.some(role => !reactionRolesIDs.includes(role)); if (unassignedRoleEmojis) { return Bastion.emit('error', '', 'Some roles doesn\'t have any assigned emojis. Please assign emojis to roles before you use them for reaction roles.', message.channel); } let body; if (args.body && args.body.length) { body = args.body.join(' '); } else { let reactionRoles = roleModels.filter(model => args.roles.includes(model.dataValues.roleID)); reactionRoles = reactionRoles.map(model => `${decodeURIComponent(model.dataValues.emoji)} - **${message.guild.roles.get(model.dataValues.roleID).name}** / ${model.dataValues.roleID}`); body = reactionRoles.join('\n'); } let reactionRolesMessage = await message.channel.send({ embed: { color: Bastion.colors.BLUE, title: args.title && args.title.length ? args.title.join(' ') : 'Reaction Roles', description: body, footer: { text: `${args.exclusive ? 'Mutually Exclusive' : ''} Reaction Roles • React with the emoji to get the corresponding role.` } } }); await reactionRolesMessage.pin().catch(() => {}); await Bastion.database.models.reactionRolesGroup.upsert({ messageID: reactionRolesMessage.id, channelID: reactionRolesMessage.channel.id, guildID: reactionRolesMessage.guild.id, reactionRoles: args.roles, mutuallyExclusive: args.exclusive }, { where: { messageID: reactionRolesMessage.id, channelID: reactionRolesMessage.channel.id, guildID: reactionRolesMessage.guild.id }, fields: [ 'messageID', 'channelID', 'guildID', 'reactionRoles', 'mutuallyExclusive' ] }); let reactionRolesEmojis = roleModels.filter(model => args.roles.includes(model.dataValues.roleID)).map(model => model.dataValues.emoji); for (let emoji of reactionRolesEmojis) { await reactionRolesMessage.react(emoji); } }; exports.config = { aliases: [ 'reactionRoles' ], enabled: true, argsDefinitions: [ { name: 'roles', type: String, multiple: true, defaultOption: true }, { name: 'title', type: String, alias: 't', multiple: true }, { name: 'body', type: String, alias: 'b', multiple: true }, { name: 'exclusive', type: Boolean, alias: 'e', defaultValue: false }, { name: 'remove', type: String, alias: 'r' } ] }; exports.help = { name: 'reactionRolesGroup', description: 'Creates a group of Reaction Roles and sends a message to which users can react to self assign roles to themselves and vice versa.', botPermission: '', userTextPermission: 'MANAGE_GUILD', userVoicePermission: '', usage: 'reactionRolesGroup [ ROLE_ID_1 ROLE_ID_2 ... ] [ -t Message Title ] [ -b Message Body ] [ --exclusive ] [ --remove MESSAGE_ID ]', example: [ 'reactionRolesGroup', 'reactionRolesGroup 219101083619902983 2494130541574845651 -t Self Assign -b React to Get Role', 'reactionRolesGroup 219101083619902983 2494130541574845651 --exclusive' ] };
import JodaTransform from './joda'; import { Instant } from 'ember-joda'; export default class InstantTransform extends JodaTransform { static JodaClass = Instant; }
var clone = function clone(obj) { var copy; if (obj === null || obj === undefined || typeof obj != "object") {// Handles boolean, number, string, null and undefined copy = obj; } else if (obj instanceof Date) {// Handle Date copy = new Date(); copy.setTime(obj.getTime()); } else if (obj instanceof Array) {// Handle Array copy = []; for (var i = 0, len = obj.length; i < len; i++) { copy[i] = clone(obj[i]); } } else if (obj instanceof Object) {// Handle Object copy = {}; for ( var attr in obj) { if (obj.hasOwnProperty(attr)) { copy[attr] = clone(obj[attr]); } } } else if (obj instanceof Function) {// Handle Functions copy = obj; } else { throw new Error("Unable to copy obj! Its type isn't supported."); } return copy; }; Object.freeze(clone) exports.clone = clone;
var assert = require('assert'); const parser = require('../src/index'); const { createFileHelper } = require('../src/test/helpers'); describe('module', function() { let ast = null; before(function(done) { const fileHelper = createFileHelper('./mock/module.js'); fileHelper.readFileAsync((err, data) => { ast = parser.parse(data); done(); }) }); describe('import', function() { it('import from', function(done) { assert.equal('ImportDeclaration', ast.body[0].type); assert.equal(1, ast.body[0].specifiers.length); assert.equal('ImportedDefaultBinding', ast.body[0].specifiers[0].type); assert.equal('Identifier', ast.body[0].specifiers[0].local.type); assert.equal('react', ast.body[0].specifiers[0].local.name); assert.equal('Literal', ast.body[0].source.type); assert.equal('React', ast.body[0].source.value); done(); }); it('import', function(done) { assert.equal('ImportDeclaration', ast.body[1].type); assert.equal(0, ast.body[1].specifiers.length); assert.equal('Literal', ast.body[1].source.type); assert.equal('module', ast.body[1].source.value); done(); }); it('import *', function(done) { assert.equal('ImportDeclaration', ast.body[2].type); assert.equal(1, ast.body[2].specifiers.length); assert.equal('ImportNamespaceBinding', ast.body[2].specifiers[0].type); assert.equal('Identifier', ast.body[2].specifiers[0].local.type); assert.equal('fun', ast.body[2].specifiers[0].local.name); assert.equal('Literal', ast.body[2].source.type); assert.equal('foo', ast.body[2].source.value); done(); }); it('import { a, b, c }', function(done) { assert.equal('ImportDeclaration', ast.body[3].type); assert.equal(3, ast.body[3].specifiers.length); assert.equal('ImportSpecifier', ast.body[3].specifiers[0].type); assert.equal('Identifier', ast.body[3].specifiers[0].local.type); assert.equal('a', ast.body[3].specifiers[0].local.name); assert.equal('ImportSpecifier', ast.body[3].specifiers[1].type); assert.equal('Identifier', ast.body[3].specifiers[1].local.type); assert.equal('b', ast.body[3].specifiers[1].local.name); assert.equal('ImportSpecifier', ast.body[3].specifiers[2].type); assert.equal('Identifier', ast.body[3].specifiers[2].local.type); assert.equal('c', ast.body[3].specifiers[2].local.name); assert.equal('Literal', ast.body[3].source.type); assert.equal('foo', ast.body[3].source.value); done(); }); it('import c, { a, b }', function(done) { assert.equal('ImportDeclaration', ast.body[4].type); assert.equal(3, ast.body[4].specifiers.length); assert.equal('ImportedDefaultBinding', ast.body[4].specifiers[0].type); assert.equal('Identifier', ast.body[4].specifiers[0].local.type); assert.equal('c', ast.body[4].specifiers[0].local.name); assert.equal('ImportSpecifier', ast.body[4].specifiers[1].type); assert.equal('Identifier', ast.body[4].specifiers[1].local.type); assert.equal('a', ast.body[4].specifiers[1].local.name); assert.equal('ImportSpecifier', ast.body[4].specifiers[2].type); assert.equal('Identifier', ast.body[4].specifiers[2].local.type); assert.equal('b', ast.body[4].specifiers[2].local.name); assert.equal('Literal', ast.body[4].source.type); assert.equal('foo', ast.body[4].source.value); done(); }); it('import { a as A }', function(done) { assert.equal('ImportDeclaration', ast.body[5].type); assert.equal(1, ast.body[5].specifiers.length); assert.equal('ImportSpecifier', ast.body[5].specifiers[0].type); assert.equal('Identifier', ast.body[5].specifiers[0].local.type); assert.equal('A', ast.body[5].specifiers[0].local.name); assert.equal('Identifier', ast.body[5].specifiers[0].imported.type); assert.equal('a', ast.body[5].specifiers[0].imported.name); assert.equal('Literal', ast.body[5].source.type); assert.equal('foo', ast.body[5].source.value); done(); }); it('import c, * as fun', function(done) { assert.equal('ImportDeclaration', ast.body[6].type); assert.equal(2, ast.body[6].specifiers.length); assert.equal('ImportedDefaultBinding', ast.body[6].specifiers[0].type); assert.equal('Identifier', ast.body[6].specifiers[0].local.type); assert.equal('c', ast.body[6].specifiers[0].local.name); assert.equal('ImportNamespaceBinding', ast.body[6].specifiers[1].type); assert.equal('Identifier', ast.body[6].specifiers[1].local.type); assert.equal('Literal', ast.body[6].source.type); assert.equal('foo', ast.body[6].source.value); done(); }); }); describe('export', function() { it('export declaration', function(done) { assert.equal('ExportNamedDeclaration', ast.body[7].type); assert.equal('LexicalDeclaration', ast.body[7].declaration.type); assert.equal(1, ast.body[7].declaration.declarations.length); assert.equal('const', ast.body[7].declaration.kind); assert.equal('VariableDeclarator', ast.body[7].declaration.declarations[0].type); assert.equal('Identifier', ast.body[7].declaration.declarations[0].id.type); assert.equal('A', ast.body[7].declaration.declarations[0].id.name); done(); }); it('export all declaration', function(done) { assert.equal('ExportAllDeclaration', ast.body[8].type); assert.equal('Literal', ast.body[8].source.type); assert.equal('foo', ast.body[8].source.value); done(); }); it('export specifier', function(done) { assert.equal('ExportNamedDeclaration', ast.body[9].type); assert.equal(2, ast.body[9].specifiers.length); assert.equal('ExportSpecifier', ast.body[9].specifiers[0].type); assert.equal('Identifier', ast.body[9].specifiers[0].exported.type); assert.equal('A', ast.body[9].specifiers[0].exported.name); assert.equal('ExportSpecifier', ast.body[9].specifiers[1].type); assert.equal('Identifier', ast.body[9].specifiers[1].exported.type); assert.equal('B', ast.body[9].specifiers[1].exported.name); done(); }); it('export specifier', function(done) { assert.equal('ExportNamedDeclaration', ast.body[9].type); assert.equal(2, ast.body[9].specifiers.length); assert.equal('ExportSpecifier', ast.body[9].specifiers[0].type); assert.equal('Identifier', ast.body[9].specifiers[0].exported.type); assert.equal('A', ast.body[9].specifiers[0].exported.name); assert.equal('ExportSpecifier', ast.body[9].specifiers[1].type); assert.equal('Identifier', ast.body[9].specifiers[1].exported.type); assert.equal('B', ast.body[9].specifiers[1].exported.name); done(); }); it('export default', function(done) { assert.equal('ExportDefaultDeclaration', ast.body[10].type); assert.equal('Identifier', ast.body[10].declaration.type); assert.equal('A', ast.body[10].declaration.name); done(); }); it('export default function', function(done) { assert.equal('ExportDefaultDeclaration', ast.body[11].type); assert.equal('FunctionDeclaration', ast.body[11].declaration.type); assert.equal(null, ast.body[11].declaration.id); assert.equal(0, ast.body[11].declaration.params.length); assert.equal('FunctionDeclaration', ast.body[11].declaration.type); assert.equal('BlockStatement', ast.body[11].declaration.body.type); assert.equal(0, ast.body[11].declaration.body.body.length); done(); }); it('export default assignment expression', function(done) { assert.equal('ExportDefaultDeclaration', ast.body[12].type); assert.equal('MultiplicativeExpression', ast.body[12].declaration.type); assert.equal('*', ast.body[12].declaration.operator); assert.equal('Identifier', ast.body[12].declaration.left.type); assert.equal('a', ast.body[12].declaration.left.name); assert.equal('Identifier', ast.body[12].declaration.right.type); assert.equal('b', ast.body[12].declaration.right.name); done(); }); }); });
import React from 'react'; import { HourlyWeather } from './HourlyWeather'; export const SevenHours = props => { const hourlyArray = props.weatherData.hourly_forecast.splice(0, 7); return ( <div className="hourly-weather"> {hourlyArray.map((hour, i) => <HourlyWeather weatherData={hour} index={i} key={i} />)} </div> ); };
require('colors'); var _ = require('lodash'), config = require('../config/config'); var noOperation = function(){}; var consoleLog = config.logging ? console.log.bind(console) : noOperation; var logger = { log: function() { var args = _.toArray(arguments) .map(function(arg) { if (typeof arg === 'object') { var string = JSON.stringify(arg, null, 2); return string.cyan; } else { arg += ''; return arg.cyan; } }); consoleLog.apply(console, args); }, error: function() { var args = _.toArray(arguments) .map(function(arg) { arg = arg.stack || arg; var name = arg.name || '[ERROR]'; var log = name.yellow + ' ' + arg.cyan; return log; }); consoleLog.apply(console, args); } }; module.exports = logger;
/*: * @plugindesc 坦克大战小游戏 * @author Mandarava(鳗驼螺) * * @help * 本插件针对的教程地址:http://www.jianshu.com/p/ddfa12f1acc9 * */ var Scene_Boot_start = Scene_Boot.prototype.start; /** * 使游戏在运行时直接进入坦克大战游戏的标题画面,如果要使用NPC打开坦克大战小游戏,请将下面的 * 重写`Scene_Boot.prototype.start`方法的代码注释掉,在你的MV地图中添加NPC,并调用脚本: * `SceneManager.goto(Scene_TankWarTitle)` 即可。 */ Scene_Boot.prototype.start = function () { Scene_Base.prototype.start.call(this); SoundManager.preloadImportantSounds(); if (DataManager.isBattleTest()) { DataManager.setupBattleTest(); SceneManager.goto(Scene_Battle); } else if (DataManager.isEventTest()) { DataManager.setupEventTest(); SceneManager.goto(Scene_Map); } else { this.checkPlayerLocation(); DataManager.setupNewGame(); SceneManager.goto(Scene_TankWarTitle);//MV游戏启动时直接进入坦克大战游戏的标题画面 Window_TitleCommand.initCommandPosition(); } this.updateDocumentTitle(); }; //----------------------------------------------------------------------------- /** * 扩展ImageManager,该方法用于从 img/mndtankwar 文件夹中加载指定名称的图片 * @param filename * @param hue */ ImageManager.loadTankwar = function (filename, hue) { return ImageManager.loadBitmap("img/mndtankwar/", filename, hue, false); }; //----------------------------------------------------------------------------- /** * 精灵表(Sprite Sheet)切帧方法 * @param texture 精灵表图片 * @param frameWidth 帧图片的宽度 * @param frameHeight 帧图片的高度 * @returns {Array} 帧信息(帧图片在精灵表图片中的坐标、宽度、高度信息)数组 */ function makeAnimFrames(texture, frameWidth, frameHeight) { var rows=parseInt(texture.height/frameHeight); //包含的帧图片行数 var cols=parseInt(texture.width/frameWidth); //包含的帧图片列数 var animFrames = []; //二维数组,对应于精灵表的各行各列中的每一帧,其每个元素用于存储每行的所有帧信息 for(var row=0;row<rows;row++) { animFrames.push([]);//二维数组的每个元素是一个一维数组 for (var col=0;col<cols;col++) { var frame={ //帧信息,格式如:{x: 0, y: 0, width: 40, height: 40},表示该帧图片在精灵表中的坐标及尺寸信息 x: col * frameWidth, y: row * frameHeight, width: frameWidth, height: frameHeight }; animFrames[row].push(frame);//一维数组的每个元素是一个frame帧信息 } } return animFrames; } //----------------------------------------------------------------------------- /** * 坦克大战游戏标题画面场景 * @constructor */ function Scene_TankWarTitle() { this.initialize.apply(this, arguments); }; Scene_TankWarTitle.prototype = Object.create(Scene_Base.prototype); Scene_TankWarTitle.prototype.constructor = Scene_TankWarTitle; Scene_TankWarTitle.prototype.create = function () { Scene_Base.prototype.create.call(this); this._backgroundSprite=new Sprite(ImageManager.loadTankwar("TitleBack"));//显示背景的精灵 this.addChild(this._backgroundSprite); //将背景加入场景 this._logo=new Sprite(ImageManager.loadTankwar("Logo"));//显示Logo的精灵 this._logo.anchor=new Point(0.5,0.5); //设置锚点到其正中心 this._logo.x=Graphics.boxWidth/2; //设置Logo的x坐标 this._logo.y=Graphics.boxHeight/2; //设置Logo的y坐标 this.addChild(this._logo); }; Scene_TankWarTitle.prototype.update = function () { if(Input.isTriggered('ok') || TouchInput.isTriggered()){//当玩家按下确定键或点击屏幕 SceneManager.goto(Scene_TankWar); //进入游戏主场景:战场场景 } }; //----------------------------------------------------------------------------- /** * 坦克大战游戏结束画面场景 * @constructor */ function Scene_TankWarGameOver() { this.initialize.apply(this, arguments); }; Scene_TankWarGameOver.prototype = Object.create(Scene_Base.prototype); Scene_TankWarGameOver.prototype.constructor = Scene_TankWarGameOver; /** * 用于向本场景传递参数 * @param isWin 是否取得胜利 */ Scene_TankWarGameOver.prototype.prepare = function(isWin) { this._isWin = isWin; }; Scene_TankWarGameOver.prototype.create = function () { Scene_Base.prototype.create.call(this); this._backgroundSprite=new Sprite(ImageManager.loadTankwar("TitleBack"));//显示背景图片的精灵 this.addChild(this._backgroundSprite); var image = ImageManager.loadTankwar(this._isWin ? "YouWin" : "YouLose");//根据输赢加载相应的图片 this._logo=new Sprite(image);//显示输赢logo的精灵 this._logo.anchor=new Point(0.5,0.5); this._logo.x=Graphics.boxWidth/2; this._logo.y=Graphics.boxHeight/2; this.addChild(this._logo); }; Scene_TankWarGameOver.prototype.update = function () { if(Input.isTriggered('ok') || TouchInput.isTriggered()){ SceneManager.goto(Scene_TankWarTitle);//进入标题画面场景 } }; //----------------------------------------------------------------------------- /** * 坦克大战游戏主场景:战场场景 * @constructor */ function Scene_TankWar() { this.initialize.apply(this, arguments); }; Scene_TankWar.prototype = Object.create(Scene_Base.prototype); Scene_TankWar.prototype.constructor = Scene_TankWar; Scene_TankWar.prototype.initialize = function() { Scene_Base.prototype.initialize.call(this); this._isGameOver = false; //游戏是否结束:如果玩家被消灭,或玩家消灭了20辆敌从坦克则游戏结束 this._maxEnemyCount = 20; //打完20个胜利 this._eliminatedEnemy = 0; //当前消灭的敌人数量 this._desireFinishTick = 120; //游戏结束(输或赢)后转到结束画面的时间 this._finishTick = 0; //从结束开始流逝的时间 this._playerSpeed = 2; //玩家坦克的移动速度 this._playerBullets = []; //保存所有由玩家坦克发出的炮弹精灵 this._enemyTanks = []; //保存所有生成的敌人坦克精灵 this._enemyBullets = []; //保存所有由敌人坦克发出的炮弹精灵 this._explodes = []; //保存所有生成的爆炸效果精灵 }; /** * 加载精灵的纹理图片 */ Scene_TankWar.prototype.loadTextures = function () { this._playerTexture=ImageManager.loadTankwar("TankPlayer"); //加载玩家坦克的纹理图片 this._enemyTexture=ImageManager.loadTankwar("TankEnemy"); //加载敌人坦克的纹理图片 this._bulletRedTexture=ImageManager.loadTankwar("BulletRed"); //加载炮弹的纹理图片 this._explodeTexture=ImageManager.loadTankwar("Explode"); //加载爆炸效果的纹理图片 }; /** * 在场景上部y坐标为60的地方随机x位置生成敌人 */ Scene_TankWar.prototype.createEnemy = function () { var tankEnemy = new Sprite_Enemy(this._enemyTexture, 40, 40, 1); //敌人坦克使用精灵表TankEnemy.png,其尺寸160x160,每行4帧图片,每列4帧图片,所以每帧的宽高为40x40 tankEnemy.speed = 2;//设置坦克的行驶速度 tankEnemy.x = 60 + Math.randomInt(Graphics.boxWidth - 120); //设置坦克随机x坐标,这样使每个敌人坦克出生地都不一样 tankEnemy.y = 60; //坦克出生的y坐标始终在60处 tankEnemy.look(Direction.Down); //初始时让敌人坦克面向下 this.addChild(tankEnemy); //将坦克加入到场景 //使用MV中的动画来展示敌人坦克出现时的一个发光传送效果 var animation = $dataAnimations[46]; //根据动画ID获取MV数据库中的动画 tankEnemy.startAnimation(animation, false, 0); //让坦克展示此动画(动画会跟着坦克走) this._enemyTanks.push(tankEnemy); //将敌人坦克对象加入_enemyTanks数组中,以便于后续操作 }; /** * 在指定位置生成爆炸精灵 * @param x 爆炸精灵要显示在的x坐标 * @param y 爆炸精灵要显示在的y坐标 */ Scene_TankWar.prototype.createExplode = function (x, y) { var explode = new Sprite_Explode(this._explodeTexture); //图片Explode.png由8帧组成,只有1行,尺寸为1024128 explode.x = x; explode.y = y; explode.anchor = new Point(0.5, 0.5); explode.scale = new Point(0.7, 0.7); //由于素材比较大,所以可以用scale来缩小精灵到原来的0.7倍 this._explodes.push(explode); //将爆炸对象加入_explodes数组中,以便于后续操作 this.addChild(explode); }; Scene_TankWar.prototype.create = function () { Scene_Base.prototype.create.call(this); this._backgroundSprite = new Sprite(ImageManager.loadTankwar("Background"));//创建背景精灵用于显示背景Background.png图片 this.addChild(this._backgroundSprite); //将背景精灵加入场景 this.loadTextures(); //加载所需的素材 }; Scene_TankWar.prototype.start = function () { Scene_Base.prototype.start.call(this); //播放开始音效 TankWarStart.ogg / TankWarStart.m4a,注意参数格式是一个包含特定属性的对象 AudioManager.playSe({ name:"TankWarStart", //音频文件名 pan:0, //pan值,可能是用于声道均衡的值,参考:https://en.wikipedia.org/wiki/Panning_%28audio%29 pitch:100, //pitch音高值 volume:100 //volume音量值 }); //增加玩家坦克到场景中 this._player=new Sprite_Tank(this._playerTexture, 40, 40, 2);//玩家坦克使用精灵表TankPlayer.png,其尺寸160x160,每行4帧图片,每列4帧图片,所以每帧的宽高为40x40 this._player.speed=0; //坦克的初始速度为0,因为这个坦克是由玩家操控的,一开始玩家未操控时速度就是0,静止的 this._player.x=Graphics.boxWidth/2; //将坦克的x坐标设置在场景的正中间 this._player.y=Graphics.height-this._player.height-20; //坦克的y坐标设置在场景的底部向上20个单位处 this.addChild(this._player); //将坦克加入场景 }; Scene_TankWar.prototype.update = function () { Scene_Base.prototype.update.call(this); //按键检测和处理 if (this._player.state == Tank_State.Live) { this._player.speed = 0; //先取消速度,因为玩家可能没有按任何方向键 if (Input.isPressed("down")) { //按向下键 this._player.look(Direction.Down); //让坦克向下看 this._player.speed = this._playerSpeed; //重置速度 } if (Input.isPressed("left")) { //按向左键 this._player.look(Direction.Left); //让坦克向左看 this._player.speed = this._playerSpeed; } if (Input.isPressed("right")) { //按向右键 this._player.look(Direction.Right); //让坦克向右看 this._player.speed = this._playerSpeed; } if (Input.isPressed("up")) { //按向上键 this._player.look(Direction.Up); //让坦克向上看 this._player.speed = this._playerSpeed; } if (Input.isPressed("control") && this._player.canFire) { //按Ctrl键发射炮弹 var bullet = this._player.fire(this._bulletRedTexture); //玩家坦克开火,得到炮弹对象 this._playerBullets.push(bullet); //将玩家打出的炮弹加入_playerBullets数组中,以便于后续操作 this.addChild(bullet); //将炮弹加入到场景中 } if (this._player.speed != 0) this._player.move();//移动玩家坦克 } //玩家打出的炮弹出界检测,如果炮弹超出画面边界,则将它们从游戏中移除 for (var i = this._playerBullets.length - 1; i >= 0; i--) { this._playerBullets[i].move(); if (this._playerBullets[i].x >= Graphics.boxWidth || this._playerBullets[i].x <= 0 || this._playerBullets[i].y >= Graphics.boxHeight || this._playerBullets[i].y <= 0) { var outBullet = this._playerBullets.splice(i, 1)[0]; //找到一个出界的炮弹 this.removeChild(outBullet); //从画面移除出界的炮弹 } } //玩家炮弹与敌人碰撞检测,如果炮弹与敌人坦克碰撞,炮弹消失,敌人受到1点伤害 for (var i = this._playerBullets.length - 1; i >= 0; i--) { for (var ti = this._enemyTanks.length - 1; ti >= 0; ti--) { if (this._enemyTanks[ti].state != Tank_State.Live) continue; //正在死亡或已经死亡的就不用处理了,也就是炮弹能穿过它们 if (this._playerBullets[i].x >= this._enemyTanks[ti].x - this._enemyTanks[ti].width / 2 && this._playerBullets[i].x <= this._enemyTanks[ti].x + this._enemyTanks[ti].width / 2 && this._playerBullets[i].y >= this._enemyTanks[ti].y - this._enemyTanks[ti].height / 2 && this._playerBullets[i].y <= this._enemyTanks[ti].y + this._enemyTanks[ti].height / 2) { var deadBullet = this._playerBullets.splice(i, 1)[0];//找到一个与敌人坦克碰撞的炮弹 this.removeChild(deadBullet); //将炮弹从场景中移除 this._enemyTanks[ti].hurt(1); //被炮弹击中的敌人坦克受到1点HP伤害 if (this._enemyTanks[ti].hp <= 0) { //检测敌人坦克是否还有hp生命值,如果死亡: this._eliminatedEnemy++; //玩家消灭的敌人数量增加1 this._isGameOver = this._eliminatedEnemy >= this._maxEnemyCount; //如果消灭的敌人数量达到20个,游戏结束 this.createExplode(this._enemyTanks[ti].x, this._enemyTanks[ti].y); //在坦克的位置显示一个爆炸效果 AudioManager.playSe({ //播放一个爆炸音效 Explosion1.ogg / Explosion1.m4a name: "Explosion1", pan: 0, pitch: 100, volume: 100 }); } break; } } } //检测是否有死亡的坦克,将其从场景内移除 for (var i = this._enemyTanks.length - 1; i >= 0; i--) { if (this._enemyTanks[i].state == Tank_State.Dead) { //依次检测每个坦克的状态,看是否死亡 var deadTank = this._enemyTanks.splice(i, 1)[0]; //找到一辆死亡的坦克 this.removeChild(deadTank); //将死亡的坦克从战场移除 } } //创建新的敌人加入战场 if (!this._isGameOver && //未结束游戏时才允许增加敌人 this._eliminatedEnemy + this._enemyTanks.length < this._maxEnemyCount && //被消灭的敌人数量和在场上的敌人数量不足最大值(20辆)时才允许增加敌人 this._enemyTanks.length < 4) { //场上的敌人不足4人时才允许增加敌人 this.createEnemy(); //创建新的敌人并将它加入战场 } //敌人坦克自动开火 if (!this._isGameOver) {//如果游戏未结束才允许敌人开火 for (var i in this._enemyTanks) { if (this._enemyTanks[i].canFire) { //检测坦克是否能开火 var bullet = this._enemyTanks[i].fire(this._bulletRedTexture); //坦克开火,生成一个炮弹对象 this._enemyBullets.push(bullet); //将炮弹对象加入_enemyBullets数组,以便于后续操作 this.addChild(bullet); //将炮弹加入场景 } } } //敌人炮弹出界检测,如果炮弹超出画面边界,则将它们从游戏中移除 for (var i = this._enemyBullets.length - 1; i >= 0; i--) { this._enemyBullets[i].move(); if (this._enemyBullets[i].x >= Graphics.boxWidth || this._enemyBullets[i].x <= 0 || this._enemyBullets[i].y >= Graphics.boxHeight || this._enemyBullets[i].y <= 0) { var outBullet = this._enemyBullets.splice(i, 1)[0]; //找到一个出界的炮弹 this.removeChild(outBullet); //从画面移除出界的炮弹 } } //敌人炮弹与玩家碰撞检测,如果敌人炮弹碰到玩家坦克,炮弹消失,玩家受1点伤害 for (var i = this._enemyBullets.length - 1; i >= 0; i--) { if (this._enemyBullets[i].x >= this._player.x - this._player.width / 2 && this._enemyBullets[i].x <= this._player.x + this._player.width / 2 && this._enemyBullets[i].y >= this._player.y - this._player.height / 2 && this._enemyBullets[i].y <= this._player.y + this._player.height / 2) { var deadBullet = this._enemyBullets.splice(i, 1)[0];//找到一个与玩家坦克碰撞的炮弹 this.removeChild(deadBullet); //将炮弹从场景中移除 this._player.hurt(1); //玩家受到1点HP伤害 if (this._player.hp <= 0) { //检测玩家是否还有hp生命值,如果死亡: this.createExplode(this._player.x, this._player.y); //创建一个爆炸效果 AudioManager.playSe({ //播放一个爆炸音效 Explosion1.ogg / Explosion1.m4a name: "Explosion1", pan: 0, pitch: 100, volume: 100 }); } else { //如果玩家坦克还有hp生命值 AudioManager.playSe({ //播放一个被打击的音效 Shot2.ogg / Shot2.m4a name: "Shot2", pan: 0, pitch: 100, volume: 100 }); } break; } } //检测玩家坦克是否死亡,如果死亡游戏结束 if (!this._isGameOver && this._player.state == Tank_State.Dead) {//如果玩家死亡: this.removeChild(this._player); //将玩家坦克从场景移除 AudioManager.playSe({ //播放失败的音效 TankWarLost.ogg / TankWarLost.m4a name: "TankWarLost", pan: 0, pitch: 100, volume: 100 }); this._isGameOver = true; //将游戏结束设置为true for (var i in this._enemyTanks) {//停止所有敌人坦克的行动 this._enemyTanks[i].isStop = true; } } //爆炸动画更新:爆炸动画有8帧组成,如果爆炸的动画播放完毕就将它们从场景中移除 for (var i = this._explodes.length - 1; i >= 0; i--) { if (this._explodes[i].isFinished) { var explode = this._explodes.splice(i, 1)[0]; this.removeChild(explode); } } //游戏结束检测 if (this._isGameOver) { this._finishTick++; if (this._finishTick >= this._desireFinishTick) { //当流逝时间达到结束游戏需要等待的时间,则转场到游戏结束场景 var isWin = this._player.state == Tank_State.Live; //如果玩家还活着就算胜利(其实这里还有个隐藏条件,就是玩家消灭了20个敌人坦克,因为游戏结束只有二种可能,一是玩家坦克被消灭,二是玩家消灭20辆敌人坦克,所以这里不用再检测该条件) SceneManager.push(Scene_TankWarGameOver); //准备转场到游戏结束场景 SceneManager.prepareNextScene(isWin); //向游戏结束场景传递参数:玩家是否赢了游戏 } } }; //----------------------------------------------------------------------------- /** * 坦克前进方向的“枚举” * @type {{Down: number, Left: number, Right: number, Up: number}} */ var Direction = { Down: 0, //向下 Left: 1, //向左 Right: 2, //向右 Up: 3 //向上 }; //----------------------------------------------------------------------------- /** * 坦克状态的“枚举” * @type {{Live: number, Dying: number, Dead: number}} */ var Tank_State = { Live: 0, //活着 Dying: 1, //死亡中 Dead: 2 //死亡 } //----------------------------------------------------------------------------- /** * 坦克炮弹类 * @constructor */ function Sprite_Bullet() { this.initialize.apply(this, arguments); }; Sprite_Bullet.prototype = Object.create(Sprite_Base.prototype); Sprite_Bullet.prototype.constructor = Sprite_Bullet; Sprite_Bullet.prototype.initialize = function (texture) { Sprite_Base.prototype.initialize.call(this); this.bitmap = texture; //设置炮弹精灵的图片 this.velocity = new Point(0, 0); //炮弹的前进速度 }; /** * 炮弹移动 */ Sprite_Bullet.prototype.move = function () { this.x += this.velocity.x; this.y += this.velocity.y; }; //----------------------------------------------------------------------------- /** * 坦克类 * @constructor */ function Sprite_Tank() { this.initialize.apply(this, arguments); }; Sprite_Tank.prototype = Object.create(Sprite_Base.prototype); Sprite_Tank.prototype.constructor = Sprite_Tank; Sprite_Tank.prototype.initialize = function (texture, frameWidth, frameHeight, hp) { Sprite_Base.prototype.initialize.call(this); this.canFire = true; //能否开火(火炮冷却后才能再次开火) this.speed = 0; //移动速度 this.hp = hp; //HP生命值 this.state = Tank_State.Live; //状态 this._animFrames = makeAnimFrames(texture, frameWidth, frameHeight);//包含了四个方向(向下、向左、向右、向上)的行走动画 this._desireMoveTick = 20; //坦克的移动动画二帧间隔的时间 this._moveTick = 0; //移动动画的当前帧 this._desireFireTick = 30; //坦克开火后二次开火间的间隔时间 this._fireTick = 0; //坦克自上次开火后流逝的时间 this._currentAnimFrameIndex = 0; //移动动画的当前帧 this._desireDieTick = 30; //坦克从死亡到已经死亡所需要的时间 this._dieTick = 0; //死亡开始后流逝的时间 this.anchor = new Point(0.5, 0.5); //设置锚点为其正中心 this.bitmap = texture; //设置其纹理图片 this.look(Direction.Up); //默认面向上 }; /** * 当前动画的帧序列信息数组 */ Object.defineProperty(Sprite_Tank.prototype, 'currentAnimFrames', { get: function() { return this._animFrames[this._direction]; } }); /** * 让坦克面向指定的方向 * @param direction */ Sprite_Tank.prototype.look = function (direction) { if(this._direction != direction) { this._direction = direction; this._currentAnimFrameIndex = 0; this.updateCurrentFrame(); } }; /** * 坦克开火 * @param texture * @returns {Sprite_Bullet} */ Sprite_Tank.prototype.fire = function (texture) { this.canFire=false; //开过火后需要一段时间再开火,所以设置canFire=false var bullet=new Sprite_Bullet(texture); bullet.anchor=new Point(0.5,0.5);//(0.5,1)时设置到底部(左上角为原点) var bulletSpeed=10; switch (this._direction) { case Direction.Down: bullet.rotation = -180 * Math.PI / 180; //由于炮弹的素材是个长方形的,所以要旋转炮弹让长边顺向开火方向 bullet.x=this.x; //将炮弹的初始x位置放到坦克的x位置 bullet.y=this.y+this.height/2; //将炮弹的初始y位置放到坦克的前方(这样就像是从炮筒射击出来的一样) bullet.velocity=new Point(0, bulletSpeed); //根据坦克的面向,设置炮弹的前进方向和速度 break; case Direction.Left: bullet.rotation = -90 * Math.PI / 180; bullet.x=this.x-this.width/2; bullet.y=this.y; bullet.velocity=new Point(-bulletSpeed, 0); break; case Direction.Right: bullet.rotation = 90 * Math.PI / 180; bullet.x=this.x+this.width/2; bullet.y=this.y; bullet.velocity=new Point(bulletSpeed, 0); break; case Direction.Up: bullet.rotation = 0; bullet.x=this.x; bullet.y=this.y-this.height/2; bullet.velocity=new Point(0, -bulletSpeed); break default: break; } AudioManager.playSe({ //播放一个开火音效 TankWarFire.ogg / TankWarFire.m4a name:"TankWarFire", pan:0, pitch:100, volume:100 }); return bullet; }; /** * 移动坦克 */ Sprite_Tank.prototype.move = function () { switch (this._direction){//移动时要根据坦克朝向 case Direction.Down: this.y += this.speed; break; case Direction.Left: this.x -= this.speed; break; case Direction.Right: this.x += this.speed; break; case Direction.Up: this.y -= this.speed; break; } }; /** * 坦克受到伤害 * @param damage 坦克受到的伤害值 */ Sprite_Tank.prototype.hurt = function (damage) { if(this.state == Tank_State.Live) { this.hp = Math.max(0, this.hp - damage); if (this.hp <= 0) { //如果伤害后没有了hp生命值,则: this.canFire = false; //死亡后不允许再开火 this.state = Tank_State.Dying; //坦克开始死亡(坦克从开始死亡到完全死亡有一个很短的时间,用于等待爆炸效果动画) } } }; /** * 更新显示当前的动画帧图片 */ Sprite_Tank.prototype.updateCurrentFrame = function () { var frame=this.currentAnimFrames[this._currentAnimFrameIndex]; //取得当前要绘制的帧图片的帧信息 this.setFrame(frame.x, frame.y, frame.width, frame.height); //绘制指定帧的图片:根据帧信息,找到精灵表中对应帧信息坐标、宽高的帧图片,并绘制到屏幕 }; Sprite_Tank.prototype.update = function () { Sprite_Base.prototype.update.call(this); switch (this.state) { case Tank_State.Live: //如果坦克状态是:活着 this._moveTick++; if (this._moveTick >= this._desireMoveTick) {//当流逝时间到达指定的时间后更新坦克的帧图片(用于展示坦克的行驶动画) this._moveTick = 0; this._currentAnimFrameIndex = this._currentAnimFrameIndex % this.currentAnimFrames.length; this.updateCurrentFrame(); this._currentAnimFrameIndex++; } if (!this.canFire) { //如果坦克当前不能开火 this._fireTick++; if (this._fireTick >= this._desireFireTick) {//当流逝时间到达指定的时间后,重新允许坦克可开火(模拟开火冷却效果) this._fireTick = 0; this.canFire = true; } } break; case Tank_State.Dying: //如果坦克状态是:正在死亡 this._dieTick++; if (this._dieTick >= this._desireDieTick) {//当流逝时间到达指定时间后,“正在死亡”的状态结束,坦克变成“已经死亡” this.state = Tank_State.Dead; } break; case Tank_State.Dead: //如果坦克状态是:已经死亡 break; default: break; } }; //----------------------------------------------------------------------------- /** * 敌人坦克类,继承自坦克类,相对于坦克类,主要是添加了简单AI功能 * @constructor */ function Sprite_Enemy() { this.initialize.apply(this, arguments); }; Sprite_Enemy.prototype = Object.create(Sprite_Tank.prototype); Sprite_Enemy.prototype.constructor = Sprite_Enemy; /** * 改变坦克的前进方向 */ Sprite_Enemy.prototype.changeRoute=function () { this._routeTick=0; this.look(Math.randomInt(4)); this._desireRouteTick=Math.randomInt(40)+100; }; Sprite_Enemy.prototype.initialize = function (texture, frameWidth, frameHeight, hp) { Sprite_Tank.prototype.initialize.apply(this, arguments); this.isStop=false; //是否停止行动 this._desireMoveTick=30; //坦克的移动动画二帧间隔的时间 this._desireFireTick=60; //坦克开火后二次开火间的间隔时间 this._desireRouteTick=100; //坦克每次改变前进路线所需要的时间 this._routeTick=0; //从坦克上次改变前进路线开始流逝的时间 this._desireDieTick = 40; //坦克从死亡到已经死亡所需要的时间 } Sprite_Enemy.prototype.update = function () { Sprite_Tank.prototype.update.call(this); if (this.state == Tank_State.Live && !this.isStop) { //如果坦克还活着,且没有要求停止行动(如果玩家被消灭,所有敌人坦克会被要求停止行动) //检测坦克是否碰上了场景的上、下、左、右边界,如果是,则自动转向(不论上次转向开始后流逝时间是否到达指定时间) if (this.x <= this.width / 2) { this.x = this.width / 2; this.changeRoute(); } if (this.x >= Graphics.boxWidth - this.width / 2) { this.x = Graphics.boxWidth - this.width / 2; this.changeRoute(); } if (this.y <= this.height / 2) { this.y = this.height / 2; this.changeRoute(); } if (this.y >= Graphics.boxHeight - this.height / 2) { this.y = Graphics.boxHeight - this.height / 2; this.changeRoute(); } //当上次转向后流逝的时间到达指定时间后开始转向 this._routeTick++; if (this._routeTick >= this._desireRouteTick) this.changeRoute(); this.move(); } }; //----------------------------------------------------------------------------- /** * 爆炸火球(效果)类 * @constructor */ function Sprite_Explode() { this.initialize.apply(this, arguments); }; Sprite_Explode.prototype = Object.create(Sprite_Base.prototype); Sprite_Explode.prototype.constructor = Sprite_Explode; Sprite_Explode.prototype.initialize = function (texture) { Sprite_Base.prototype.initialize.call(this); this._animFrames = makeAnimFrames(texture, 128, 128)[0]; //爆炸效果使用精灵表Explode.png,其尺寸1024x128,共1行8帧图片,所以每帧的宽高为128x128 this._desireTick = 6; //爆炸动画二帧之间的间隔时间 this._tick = 0; //爆炸动画绘制上一帧之后流逝的时间 this._currentAnimFrameIndex = 0; //当前的动画帧索引 this.isFinished = false; //爆炸动画是否播放完毕(8帧) this.bitmap = texture; //设置精灵的纹理图片 this.updateCurrentFrame(); //更新当前的帧图片 }; /** * 更新显示当前的动画帧图片 */ Sprite_Explode.prototype.updateCurrentFrame = function () { var frame = this._animFrames[this._currentAnimFrameIndex]; this.setFrame(frame.x, frame.y, frame.width, frame.height); }; Sprite_Explode.prototype.update = function () { Sprite_Base.prototype.update.call(this); this._tick++; if(this._currentAnimFrameIndex>=this._animFrames.length-1){ //如果8帧都播放完毕,则: this.isFinished=true; //标记为动画结束 }else { //否则当流逝时间到达指定时间后更新下一帧图片 if (this._tick >= this._desireTick) { this._tick = 0; this.updateCurrentFrame(); this._currentAnimFrameIndex++; } } };
import range from 'lodash-es/range' import {genMap} from '../../../test-fixtures/current-game-states' import {isSettingsValid, settingsValidator} from './settings-validator' import {trans} from '../../utils/translate' /** * Create segment of redux tree for validator to consume * @param {IPlayerMap<string>} names Player names inside a IPlayerMap * @param {number|null} currentRound `state.currentGame.currentRound`, pass in null to stimulate null game/ended game * @returns {Object} Part of redux tree to consume */ function makeTree(names, currentRound = 1) { return { currentGame: {currentRound}, gameSettings: {names} } } test('it should pass for default names', () => { const names = genMap('John', 'Mary', 'Henry', 'Joe') const tree = makeTree(names) const expected = { names: {}, misc: null } const actual = settingsValidator(tree, trans) expect(actual).toEqual(expected) }) test('it should fail if duplicate names exist', () => { const names = genMap('John', 'Mary', 'John', 'Joe') const tree = makeTree(names) const expected = { names: { a: 'Name cannot be repeated', c: 'Name cannot be repeated' }, misc: null } const actual = settingsValidator(tree, trans) expect(actual).toEqual(expected) }) test('it should fail if one of the name is empty', () => { const names = genMap('', 'Mary', 'Henry', 'Joe') const tree = makeTree(names) const expected = { names: { a: 'Name cannot be empty' }, misc: null } const actual = settingsValidator(tree, trans) expect(actual).toEqual(expected) }) test('it should fail if there is no player', () => { const names = {} const tree = makeTree(names) const expected = { names: {}, misc: 'At least 2 players is required for a game' } const actual = settingsValidator(tree, trans) expect(actual).toEqual(expected) }) test('it should fail if there is only 1 player', () => { const names = {'a': 'John'} const tree = makeTree(names) const expected = { names: {}, misc: 'At least 2 players is required for a game' } const actual = settingsValidator(tree, trans) expect(actual).toEqual(expected) }) test('it should fail if there are too many players', () => { const names = range(53).map(i => i + '').reduce((acc, val) => ({...acc, [val]: val}), {}) const tree = makeTree(names) const expected = { names: {}, misc: 'Too many players. Upper limit is 52 players.' } const actual = settingsValidator(tree, trans) expect(actual).toEqual(expected) }) test('it should fail if current round has passed through maximum round', () => { const names = range(10).map(i => i + '').reduce((acc, val) => ({...acc, [val]: val}), {}) const tree = makeTree(names, 7) const expected = { names: {}, misc: 'Impossible to continue the game due to too many players' } const actual = settingsValidator(tree, trans) expect(actual).toEqual(expected) }) test('is valid should pass for default names', () => { const names = genMap('John', 'Mary', 'Henry', 'Joe') const tree = makeTree(names) const expected = true const actual = isSettingsValid(tree, trans) expect(actual).toEqual(expected) }) test('is valid should return false for erroneous data', () => { const names = genMap('', 'Mary', 'Henry', 'Joe') const tree = makeTree(names) const expected = false const actual = isSettingsValid(tree, trans) expect(actual).toEqual(expected) })
import React from 'react'; import Utils from '../utils/utils'; import Mixins from '../utils/mixins'; import __reactComponentSlots from '../runtime-helpers/react-component-slots.js'; import __reactComponentSetProps from '../runtime-helpers/react-component-set-props.js'; class F7SwipeoutActions extends React.Component { constructor(props, context) { super(props, context); } render() { const props = this.props; const { left, right, side, className, id, style } = props; let sideComputed = side; if (!sideComputed) { if (left) sideComputed = 'left'; if (right) sideComputed = 'right'; } const classes = Utils.classNames(className, `swipeout-actions-${sideComputed}`, Mixins.colorClasses(props)); return React.createElement('div', { id: id, style: style, className: classes }, this.slots['default']); } get slots() { return __reactComponentSlots(this.props); } } __reactComponentSetProps(F7SwipeoutActions, Object.assign({ id: [String, Number], left: Boolean, right: Boolean, side: String }, Mixins.colorProps)); F7SwipeoutActions.displayName = 'f7-swipeout-actions'; export default F7SwipeoutActions;
'use strict'; /** * @ngdoc overview * @name wavesApp * @description * # wavesApp * * Main module of the application. */ angular .module('wavesApp', [ 'ngAnimate', 'ngCookies', 'ngMessages', 'ngResource', 'ngRoute', 'ngSanitize', 'ngTouch', 'ui.router', 'puigcerber.capitalize', 'ngHolder', 'pascalprecht.translate', 'LocalStorageModule' ]) .config(function ($stateProvider, $routeProvider) { $routeProvider .otherwise({ redirectTo: '/' }); $stateProvider .state('boot', { url: '/', views: { 'content': { 'templateUrl': 'views/boot.html' } } }) .state('active_screen', { url: '/active_screen', views: { 'top_left_content': { 'template': '<holliday-detail/>' }, 'top_right_content': { 'template': '<forecast-detail/>' }, 'content': { 'templateUrl': 'views/active_screen/main.html' } } }) .state('talking', { url: '/talking', params: { result: null, speechRecognitionNotSupported: false }, views: { 'content': { 'template': '<talking/>' } } }) .state('loading', { url: '/loading', params: { text: null }, views: { 'content': { 'template': '<loading/>' } } }) .state('not_found', { url: '/not_found', params: { response: null }, views: { 'content': { 'template': '<not-found-response/>' } } }) .state('noticias', { url: '/noticias', params: { response: null }, views: { 'content': { 'template': '<news-response/>' } } }) .state('clima', { url: '/clima', params: { response: null }, views: { 'content': { 'template': '<weather-response/>' } } }) .state('farmacias', { url: '/farmacias', params: { response: null }, views: { 'content': { 'template': '<pharmacies-response/>' } } }) /* .state('eventos', { url: '/events', params: { response: null }, views: { 'content': { 'template': '<events-response/>' } } }) .state('feriado', { url: '/next-holliday', params: { response: null }, views: { 'content': { 'template': '<next-holliday-response/>' } } })*/ ; }) .config(function (localStorageServiceProvider) { localStorageServiceProvider.setPrefix('waves'); }); angular .module('wavesApp').run(['$rootScope', 'speechRecognition', '$state', function($rootScope, speechRecognition, $state){ var speechRecognizer; $rootScope.speechResult={}; try{ speechRecognizer = speechRecognition.init( { lang: 'es-AR', continuous: true }, { onfirstresult: function(){ $state.go('talking'); }, onresult: function(result){ $rootScope.$emit("speech:result", result); } } ); speechRecognizer.start(); $rootScope.speechRecognition=speechRecognizer; }catch(e){ //TODO:: Move message to active_screen as thin navbar console.warn({result: e.message, speechRecognitionNotSupported: true}); } $rootScope.$on('$stateChangeStart', function(ev, next, nextParams, from){ if(['loading', 'not_found', 'clima', 'farmacias', 'noticias'].indexOf(next.name)!== -1){ ($rootScope.speechRecognition) && $rootScope.speechRecognition.start(); responseTimeout=$timeout(function() { $state.go('active_screen'); }, 15000); } if(from.name === next.name){ ev.preventDefault(); return false; }else{ if( ( (next.name === "boot") || (next.name === "active_screen") ) && ($rootScope.speechRecognition) && ($rootScope.speechRecognition.isStopped()) ){ try{ ($rootScope.speechRecognition) && $rootScope.speechRecognition.start(); }catch(e){ console.warn(e); } } } }); }]);
//////////////////////////////////////// // isgame-online-lambda // // Copyright (c) 2017 Jonathan Hardison // /controllers/game-checkisvalid.js /////////////////////////////////////// var config = require('../config'); let configInstance = new config(); //game list objects //includes alternate spellings based on alexa interpretation of spoken words. var gamesSupported = require('../games/supportedgames').default; function CheckGameIsValid(gametocheck){ if((gametocheck != null) || (gametocheck != 'undefined')){ var testvalue = gamesSupported[gametocheck]; if(configInstance.debugEnabled == "true"){ console.log("gametocheck: " + gametocheck); console.log("testvalue: " + testvalue); } if(testvalue != null) { return testvalue; } else{ return null; } } else{ return null; } }//end function module.exports = CheckGameIsValid;
const express = require('express'); const router = express.Router(); const path = require('path'); const authenticate = require('../util/auth/authenticateRequest'); router.get('/', authenticate(), function(req, res) { res.sendFile(path.join(__dirname, '../../public/views', 'home.html')); }); module.exports = router;
( function () { var input = new OO.ui.TextInputWidget(), list = new OO.ui.SelectWidget( { items: [ new OO.ui.OptionWidget( { label: 'Item 1', data: 'Item 1' } ), new OO.ui.OptionWidget( { label: 'Item 2', data: 'Item 2' } ), new OO.ui.OptionWidget( { label: 'Item 3', data: 'Item 3' } ) ] } ); input.on( 'enter', function () { list.addItems( [ new OO.ui.OptionWidget( { data: input.getValue(), label: input.getValue() } ) ] ); } ); // eslint-disable-next-line no-jquery/no-global-selector $( '.tutorials-embed-app1' ).append( new OO.ui.FieldsetLayout( { id: 'tutorials-basics1-app1', label: 'Demo #1', items: [ input, list ] } ).$element ); }() );
(function($) { var Alpaca = $.alpaca; Alpaca.Fields.MLUrl2Field = Alpaca.Fields.Url2Field.extend( /** * @lends Alpaca.Fields.Url2Field.prototype */ { constructor: function (container, data, options, schema, view, connector) { var self = this; this.base(container, data, options, schema, view, connector); //this.sf = connector.servicesFramework; //this.dataSource = {}; this.culture = connector.culture; this.defaultCulture = connector.defaultCulture; }, /** * @see Alpaca.Fields.Url2Field#setup */ setup: function() { var self = this; if (this.data && Alpaca.isObject(this.data)) { this.olddata = this.data; } else if (this.data) { this.olddata = {}; this.olddata[this.defaultCulture] = this.data; } this.base(); }, getValue: function () { var val = this.base(val); var self = this; var o = {}; if (this.olddata && Alpaca.isObject(this.olddata)) { $.each(this.olddata, function (key, value) { var v = Alpaca.copyOf(value); if (key != self.culture) { o[key] = v; } }); } if (val != "") { o[self.culture] = val; } if ($.isEmptyObject(o)) { return ""; } return o; }, /** * @see Alpaca.Field#setValue */ setValue: function(val) { if (val === "") { return; } if (!val) { this.base(""); return; } if (Alpaca.isObject(val)) { var v = val[this.culture]; if (!v) { this.base(""); return; } this.base(v); } else { this.base(val); } }, afterRenderControl: function (model, callback) { var self = this; this.base(model, function () { self.handlePostRender2(function () { callback(); }); }); }, handlePostRender2: function (callback) { var self = this; var el = this.getControlEl(); callback(); $(this.control).parent().find('.select2').after('<img src="/images/Flags/' + this.culture + '.gif" class="flag" />'); }, }); Alpaca.registerFieldClass("mlurl2", Alpaca.Fields.MLUrl2Field); })(jQuery);
let AdventurePlayerObject = AdventurePlayerObject || {} let AdventureScreenObject = AdventureScreenObject || {} let AdventureGameObject = AdventureGameObject || {} ;(function (undefined) { let Player = AdventurePlayerObject let Screen = AdventureScreenObject let Game = AdventureGameObject Player.inventory = [] Player.itemsEquipped = [] Player.listInventory = function () { if (Player.inventory.length === 0) { return Screen.displayConsoleMessage('there are no items in your inventory') } Screen.displayConsoleMessage('Items currently in inventory:') return Player.inventory.forEach((item) => { Screen.displayConsoleMessage(`- ${item}`) }) } Player.addItem = function (item, itemIndex) { let testIfAlreadyInInventory = Game.findObjectIndexInArray(Player.inventory, item.name, 'name') if (testIfAlreadyInInventory !== -1) { return `You already have ${item.name} in your inventory` } Player.inventory.push(item) // remove the item from the currentLocation Game.currentLocation.items.splice(itemIndex, 1) console.log(Game.currentLocation.items) return `${item.name} has been added to your inventory.` } Player.equipItem = function (item) { Player.itemsEquipped.push(item) console.log(Player.itemsEquipped) return `${item.name} was equipped` } Player.unequipItem = function (itemIndex) { let item = Player.itemsEquipped.splice(itemIndex, 1) console.log(item[0].name) return `${item[0].name} was unequipped` } Player.useItem = function (itemName) { if (Player.inventory.indexOf(itemName) !== -1) { return console.log(`${itemName} has been used.`) } } })()
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", { d: "M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z" }), 'DoneSharp');
// MODULES // var // Expectation library: chai = require( 'chai' ), // Test utilities: utils = require( './utils' ), // Module to be tested: qStream = require( './../lib' ); // VARIABLES // var expect = chai.expect, assert = chai.assert; // TESTS // describe( 'iqr', function tests() { 'use strict'; it( 'should export a factory function', function test() { expect( qStream ).to.be.a( 'function' ); }); it( 'should compute the interquartile range of piped data', function test( done ) { var data, tStream; // Simulate some data... (quartiles: 4, 6; iqr: 2) data = [ 5, 6, 6, 4, 3, 3, 5, 7, 4, 7 ]; // Create a new iqr stream: tStream = qStream().stream(); // Mock reading from the stream: utils.readStream( tStream, onRead ); // Mock piping a data to the stream: utils.writeStream( data, tStream ); return; /** * FUNCTION: onRead( error, actual ) * Read event handler. Checks for errors and compares streamed data to expected data. */ function onRead( error, actual ) { expect( error ).to.not.exist; assert.strictEqual( actual[ 0 ], 2 ); done(); } // end FUNCTION onRead() }); });
'use strict'; app.controller('BrowseController', function($scope, $routeParams, toaster, Task, Auth, Comment) { $scope.searchTask = ''; $scope.tasks = Task.all; $scope.signedIn = Auth.signedIn; $scope.listMode = true; $scope.user = Auth.user; if($routeParams.taskId) { var task = Task.getTask($routeParams.taskId).$asObject(); $scope.listMode = false; setSelectedTask(task); } function setSelectedTask(task) { $scope.selectedTask = task; //I check isTaskCreator only if user signedIn if($scope.signedIn()) { $scope.isTaskCreator = Task.isCreator; $scope.isOpen = Task.isOpen; } // Get list of comments for the selected task $scope.comments = Comment.comments(task.$id); }; $scope.cancelTask = function(taskId) { Task.cancelTask(taskId).then(function() { toaster.pop('success', "This task is cancelled successfully."); }); }; //add addComment function $scope.addComment = function() { var comment = { content: $scope.content, name: $scope.user.profile.name, gravatar: $scope.user.profile.gravatar }; Comment.addComment($scope.selectedTask.$id, comment).then(function() { $scope.content = ''; }); }; });
'use strict'; /* jshint ignore:start */ /** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ /* jshint ignore:end */ var Q = require('q'); /* jshint ignore:line */ var _ = require('lodash'); /* jshint ignore:line */ var util = require('util'); /* jshint ignore:line */ var Page = require('../../../../../base/Page'); /* jshint ignore:line */ var deserialize = require( '../../../../../base/deserialize'); /* jshint ignore:line */ var values = require('../../../../../base/values'); /* jshint ignore:line */ var BucketList; var BucketPage; var BucketInstance; var BucketContext; /* jshint ignore:start */ /** * Initialize the BucketList * * @constructor Twilio.Verify.V2.ServiceContext.RateLimitContext.BucketList * * @param {Twilio.Verify.V2} version - Version of the resource * @param {string} serviceSid - * The SID of the Service that the resource is associated with * @param {string} rateLimitSid - Rate Limit Sid. */ /* jshint ignore:end */ BucketList = function BucketList(version, serviceSid, rateLimitSid) { /* jshint ignore:start */ /** * @function buckets * @memberof Twilio.Verify.V2.ServiceContext.RateLimitContext# * * @param {string} sid - sid of instance * * @returns {Twilio.Verify.V2.ServiceContext.RateLimitContext.BucketContext} */ /* jshint ignore:end */ function BucketListInstance(sid) { return BucketListInstance.get(sid); } BucketListInstance._version = version; // Path Solution BucketListInstance._solution = {serviceSid: serviceSid, rateLimitSid: rateLimitSid}; BucketListInstance._uri = `/Services/${serviceSid}/RateLimits/${rateLimitSid}/Buckets`; /* jshint ignore:start */ /** * create a BucketInstance * * @function create * @memberof Twilio.Verify.V2.ServiceContext.RateLimitContext.BucketList# * * @param {object} opts - Options for request * @param {number} opts.max - Max number of requests. * @param {number} opts.interval - * Number of seconds that the rate limit will be enforced over. * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed BucketInstance */ /* jshint ignore:end */ BucketListInstance.create = function create(opts, callback) { if (_.isUndefined(opts)) { throw new Error('Required parameter "opts" missing.'); } if (_.isUndefined(opts['max'])) { throw new Error('Required parameter "opts[\'max\']" missing.'); } if (_.isUndefined(opts['interval'])) { throw new Error('Required parameter "opts[\'interval\']" missing.'); } var deferred = Q.defer(); var data = values.of({'Max': _.get(opts, 'max'), 'Interval': _.get(opts, 'interval')}); var promise = this._version.create({uri: this._uri, method: 'POST', data: data}); promise = promise.then(function(payload) { deferred.resolve(new BucketInstance( this._version, payload, this._solution.serviceSid, this._solution.rateLimitSid, this._solution.sid )); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; /* jshint ignore:start */ /** * Streams BucketInstance records from the API. * * This operation lazily loads records as efficiently as possible until the limit * is reached. * * The results are passed into the callback function, so this operation is memory * efficient. * * If a function is passed as the first argument, it will be used as the callback * function. * * @function each * @memberof Twilio.Verify.V2.ServiceContext.RateLimitContext.BucketList# * * @param {object} [opts] - Options for request * @param {number} [opts.limit] - * Upper limit for the number of records to return. * each() guarantees never to return more than limit. * Default is no limit * @param {number} [opts.pageSize] - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no pageSize is defined but a limit is defined, * each() will attempt to read the limit with the most efficient * page size, i.e. min(limit, 1000) * @param {Function} [opts.callback] - * Function to process each record. If this and a positional * callback are passed, this one will be used * @param {Function} [opts.done] - * Function to be called upon completion of streaming * @param {Function} [callback] - Function to process each record */ /* jshint ignore:end */ BucketListInstance.each = function each(opts, callback) { if (_.isFunction(opts)) { callback = opts; opts = {}; } opts = opts || {}; if (opts.callback) { callback = opts.callback; } if (_.isUndefined(callback)) { throw new Error('Callback function must be provided'); } var done = false; var currentPage = 1; var currentResource = 0; var limits = this._version.readLimits({ limit: opts.limit, pageSize: opts.pageSize }); function onComplete(error) { done = true; if (_.isFunction(opts.done)) { opts.done(error); } } function fetchNextPage(fn) { var promise = fn(); if (_.isUndefined(promise)) { onComplete(); return; } promise.then(function(page) { _.each(page.instances, function(instance) { if (done || (!_.isUndefined(opts.limit) && currentResource >= opts.limit)) { done = true; return false; } currentResource++; callback(instance, onComplete); }); if (!done) { currentPage++; fetchNextPage(_.bind(page.nextPage, page)); } else { onComplete(); } }); promise.catch(onComplete); } fetchNextPage(_.bind(this.page, this, _.merge(opts, limits))); }; /* jshint ignore:start */ /** * Lists BucketInstance records from the API as a list. * * If a function is passed as the first argument, it will be used as the callback * function. * * @function list * @memberof Twilio.Verify.V2.ServiceContext.RateLimitContext.BucketList# * * @param {object} [opts] - Options for request * @param {number} [opts.limit] - * Upper limit for the number of records to return. * list() guarantees never to return more than limit. * Default is no limit * @param {number} [opts.pageSize] - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no page_size is defined but a limit is defined, * list() will attempt to read the limit with the most * efficient page size, i.e. min(limit, 1000) * @param {function} [callback] - Callback to handle list of records * * @returns {Promise} Resolves to a list of records */ /* jshint ignore:end */ BucketListInstance.list = function list(opts, callback) { if (_.isFunction(opts)) { callback = opts; opts = {}; } opts = opts || {}; var deferred = Q.defer(); var allResources = []; opts.callback = function(resource, done) { allResources.push(resource); if (!_.isUndefined(opts.limit) && allResources.length === opts.limit) { done(); } }; opts.done = function(error) { if (_.isUndefined(error)) { deferred.resolve(allResources); } else { deferred.reject(error); } }; if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } this.each(opts); return deferred.promise; }; /* jshint ignore:start */ /** * Retrieve a single page of BucketInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @function page * @memberof Twilio.Verify.V2.ServiceContext.RateLimitContext.BucketList# * * @param {object} [opts] - Options for request * @param {string} [opts.pageToken] - PageToken provided by the API * @param {number} [opts.pageNumber] - * Page Number, this value is simply for client state * @param {number} [opts.pageSize] - Number of records to return, defaults to 50 * @param {function} [callback] - Callback to handle list of records * * @returns {Promise} Resolves to a list of records */ /* jshint ignore:end */ BucketListInstance.page = function page(opts, callback) { if (_.isFunction(opts)) { callback = opts; opts = {}; } opts = opts || {}; var deferred = Q.defer(); var data = values.of({ 'PageToken': opts.pageToken, 'Page': opts.pageNumber, 'PageSize': opts.pageSize }); var promise = this._version.page({uri: this._uri, method: 'GET', params: data}); promise = promise.then(function(payload) { deferred.resolve(new BucketPage(this._version, payload, this._solution)); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; /* jshint ignore:start */ /** * Retrieve a single target page of BucketInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @function getPage * @memberof Twilio.Verify.V2.ServiceContext.RateLimitContext.BucketList# * * @param {string} [targetUrl] - API-generated URL for the requested results page * @param {function} [callback] - Callback to handle list of records * * @returns {Promise} Resolves to a list of records */ /* jshint ignore:end */ BucketListInstance.getPage = function getPage(targetUrl, callback) { var deferred = Q.defer(); var promise = this._version._domain.twilio.request({method: 'GET', uri: targetUrl}); promise = promise.then(function(payload) { deferred.resolve(new BucketPage(this._version, payload, this._solution)); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; /* jshint ignore:start */ /** * Constructs a bucket * * @function get * @memberof Twilio.Verify.V2.ServiceContext.RateLimitContext.BucketList# * * @param {string} sid - A string that uniquely identifies this Bucket. * * @returns {Twilio.Verify.V2.ServiceContext.RateLimitContext.BucketContext} */ /* jshint ignore:end */ BucketListInstance.get = function get(sid) { return new BucketContext( this._version, this._solution.serviceSid, this._solution.rateLimitSid, sid ); }; /* jshint ignore:start */ /** * Provide a user-friendly representation * * @function toJSON * @memberof Twilio.Verify.V2.ServiceContext.RateLimitContext.BucketList# * * @returns Object */ /* jshint ignore:end */ BucketListInstance.toJSON = function toJSON() { return this._solution; }; BucketListInstance[util.inspect.custom] = function inspect(depth, options) { return util.inspect(this.toJSON(), options); }; return BucketListInstance; }; /* jshint ignore:start */ /** * Initialize the BucketPage * * @constructor Twilio.Verify.V2.ServiceContext.RateLimitContext.BucketPage * * @param {V2} version - Version of the resource * @param {Response<string>} response - Response from the API * @param {BucketSolution} solution - Path solution * * @returns BucketPage */ /* jshint ignore:end */ BucketPage = function BucketPage(version, response, solution) { // Path Solution this._solution = solution; Page.prototype.constructor.call(this, version, response, this._solution); }; _.extend(BucketPage.prototype, Page.prototype); BucketPage.prototype.constructor = BucketPage; /* jshint ignore:start */ /** * Build an instance of BucketInstance * * @function getInstance * @memberof Twilio.Verify.V2.ServiceContext.RateLimitContext.BucketPage# * * @param {BucketPayload} payload - Payload response from the API * * @returns BucketInstance */ /* jshint ignore:end */ BucketPage.prototype.getInstance = function getInstance(payload) { return new BucketInstance( this._version, payload, this._solution.serviceSid, this._solution.rateLimitSid ); }; /* jshint ignore:start */ /** * Provide a user-friendly representation * * @function toJSON * @memberof Twilio.Verify.V2.ServiceContext.RateLimitContext.BucketPage# * * @returns Object */ /* jshint ignore:end */ BucketPage.prototype.toJSON = function toJSON() { let clone = {}; _.forOwn(this, function(value, key) { if (!_.startsWith(key, '_') && ! _.isFunction(value)) { clone[key] = value; } }); return clone; }; BucketPage.prototype[util.inspect.custom] = function inspect(depth, options) { return util.inspect(this.toJSON(), options); }; /* jshint ignore:start */ /** * Initialize the BucketContext * * @constructor Twilio.Verify.V2.ServiceContext.RateLimitContext.BucketInstance * * @property {string} sid - A string that uniquely identifies this Bucket. * @property {string} rateLimitSid - Rate Limit Sid. * @property {string} serviceSid - * The SID of the Service that the resource is associated with * @property {string} accountSid - The SID of the Account that created the resource * @property {number} max - Max number of requests. * @property {number} interval - * Number of seconds that the rate limit will be enforced over. * @property {Date} dateCreated - * The RFC 2822 date and time in GMT when the resource was created * @property {Date} dateUpdated - * The RFC 2822 date and time in GMT when the resource was last updated * @property {string} url - The URL of this resource. * * @param {V2} version - Version of the resource * @param {BucketPayload} payload - The instance payload * @param {sid} serviceSid - * The SID of the Service that the resource is associated with * @param {sid} rateLimitSid - Rate Limit Sid. * @param {sid} sid - A string that uniquely identifies this Bucket. */ /* jshint ignore:end */ BucketInstance = function BucketInstance(version, payload, serviceSid, rateLimitSid, sid) { this._version = version; // Marshaled Properties this.sid = payload.sid; // jshint ignore:line this.rateLimitSid = payload.rate_limit_sid; // jshint ignore:line this.serviceSid = payload.service_sid; // jshint ignore:line this.accountSid = payload.account_sid; // jshint ignore:line this.max = deserialize.integer(payload.max); // jshint ignore:line this.interval = deserialize.integer(payload.interval); // jshint ignore:line this.dateCreated = deserialize.iso8601DateTime(payload.date_created); // jshint ignore:line this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); // jshint ignore:line this.url = payload.url; // jshint ignore:line // Context this._context = undefined; this._solution = {serviceSid: serviceSid, rateLimitSid: rateLimitSid, sid: sid || this.sid, }; }; Object.defineProperty(BucketInstance.prototype, '_proxy', { get: function() { if (!this._context) { this._context = new BucketContext( this._version, this._solution.serviceSid, this._solution.rateLimitSid, this._solution.sid ); } return this._context; } }); /* jshint ignore:start */ /** * update a BucketInstance * * @function update * @memberof Twilio.Verify.V2.ServiceContext.RateLimitContext.BucketInstance# * * @param {object} [opts] - Options for request * @param {number} [opts.max] - Max number of requests. * @param {number} [opts.interval] - * Number of seconds that the rate limit will be enforced over. * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed BucketInstance */ /* jshint ignore:end */ BucketInstance.prototype.update = function update(opts, callback) { return this._proxy.update(opts, callback); }; /* jshint ignore:start */ /** * fetch a BucketInstance * * @function fetch * @memberof Twilio.Verify.V2.ServiceContext.RateLimitContext.BucketInstance# * * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed BucketInstance */ /* jshint ignore:end */ BucketInstance.prototype.fetch = function fetch(callback) { return this._proxy.fetch(callback); }; /* jshint ignore:start */ /** * remove a BucketInstance * * @function remove * @memberof Twilio.Verify.V2.ServiceContext.RateLimitContext.BucketInstance# * * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed BucketInstance */ /* jshint ignore:end */ BucketInstance.prototype.remove = function remove(callback) { return this._proxy.remove(callback); }; /* jshint ignore:start */ /** * Provide a user-friendly representation * * @function toJSON * @memberof Twilio.Verify.V2.ServiceContext.RateLimitContext.BucketInstance# * * @returns Object */ /* jshint ignore:end */ BucketInstance.prototype.toJSON = function toJSON() { let clone = {}; _.forOwn(this, function(value, key) { if (!_.startsWith(key, '_') && ! _.isFunction(value)) { clone[key] = value; } }); return clone; }; BucketInstance.prototype[util.inspect.custom] = function inspect(depth, options) { return util.inspect(this.toJSON(), options); }; /* jshint ignore:start */ /** * Initialize the BucketContext * * @constructor Twilio.Verify.V2.ServiceContext.RateLimitContext.BucketContext * * @param {V2} version - Version of the resource * @param {sid} serviceSid - * The SID of the Service that the resource is associated with * @param {sid} rateLimitSid - Rate Limit Sid. * @param {sid} sid - A string that uniquely identifies this Bucket. */ /* jshint ignore:end */ BucketContext = function BucketContext(version, serviceSid, rateLimitSid, sid) { this._version = version; // Path Solution this._solution = {serviceSid: serviceSid, rateLimitSid: rateLimitSid, sid: sid, }; this._uri = `/Services/${serviceSid}/RateLimits/${rateLimitSid}/Buckets/${sid}`; }; /* jshint ignore:start */ /** * update a BucketInstance * * @function update * @memberof Twilio.Verify.V2.ServiceContext.RateLimitContext.BucketContext# * * @param {object} [opts] - Options for request * @param {number} [opts.max] - Max number of requests. * @param {number} [opts.interval] - * Number of seconds that the rate limit will be enforced over. * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed BucketInstance */ /* jshint ignore:end */ BucketContext.prototype.update = function update(opts, callback) { if (_.isFunction(opts)) { callback = opts; opts = {}; } opts = opts || {}; var deferred = Q.defer(); var data = values.of({'Max': _.get(opts, 'max'), 'Interval': _.get(opts, 'interval')}); var promise = this._version.update({uri: this._uri, method: 'POST', data: data}); promise = promise.then(function(payload) { deferred.resolve(new BucketInstance( this._version, payload, this._solution.serviceSid, this._solution.rateLimitSid, this._solution.sid )); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; /* jshint ignore:start */ /** * fetch a BucketInstance * * @function fetch * @memberof Twilio.Verify.V2.ServiceContext.RateLimitContext.BucketContext# * * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed BucketInstance */ /* jshint ignore:end */ BucketContext.prototype.fetch = function fetch(callback) { var deferred = Q.defer(); var promise = this._version.fetch({uri: this._uri, method: 'GET'}); promise = promise.then(function(payload) { deferred.resolve(new BucketInstance( this._version, payload, this._solution.serviceSid, this._solution.rateLimitSid, this._solution.sid )); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; /* jshint ignore:start */ /** * remove a BucketInstance * * @function remove * @memberof Twilio.Verify.V2.ServiceContext.RateLimitContext.BucketContext# * * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed BucketInstance */ /* jshint ignore:end */ BucketContext.prototype.remove = function remove(callback) { var deferred = Q.defer(); var promise = this._version.remove({uri: this._uri, method: 'DELETE'}); promise = promise.then(function(payload) { deferred.resolve(payload); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; /* jshint ignore:start */ /** * Provide a user-friendly representation * * @function toJSON * @memberof Twilio.Verify.V2.ServiceContext.RateLimitContext.BucketContext# * * @returns Object */ /* jshint ignore:end */ BucketContext.prototype.toJSON = function toJSON() { return this._solution; }; BucketContext.prototype[util.inspect.custom] = function inspect(depth, options) { return util.inspect(this.toJSON(), options); }; module.exports = { BucketList: BucketList, BucketPage: BucketPage, BucketInstance: BucketInstance, BucketContext: BucketContext };
angular.module('devotionalfinder').controller('HomeCtrl',function($scope,$facebook){ $scope.isLoggedIn = false; $scope.login = function() { console.log('login clicked'); $facebook.login().then(function() { refresh(); }); } $scope.logout = function() { console.log('logout clicked'); $facebook.logout().then(function() { $scope.isLoggedIn = false; refresh(); }); } function refresh() { $facebook.api("/me").then( function(response) { console.log(response); $scope.welcomeMsg = "Welcome " + response.name; $scope.isLoggedIn = true; }, function(err) { $scope.welcomeMsg = "Please log in"; }); } refresh(); });
/*! * jQuery JavaScript Library v1.7.2 * http://jquery.com/ * * Copyright 2011, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Wed Mar 21 12:46:34 2012 -0700 */ (function( window, undefined ) { // Use the correct document accordingly with window argument (sandbox) var document = window.document, navigator = window.navigator, location = window.location; var jQuery = (function() { // 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, rootjQuery ); }, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // A central reference to the root jQuery(document) rootjQuery, // A simple way to check for HTML strings or ID strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, // Check if a string has a non-whitespace character in it rnotwhite = /\S/, // Used for trimming whitespace trimLeft = /^\s+/, trimRight = /\s+$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, // Useragent RegExp rwebkit = /(webkit)[ \/]([\w.]+)/, ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, rmsie = /(msie) ([\w.]+)/, rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, // Matches dashed string for camelizing rdashAlpha = /-([a-z]|[0-9])/ig, rmsPrefix = /^-ms-/, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return ( letter + "" ).toUpperCase(); }, // Keep a UserAgent string for use with jQuery.browser userAgent = navigator.userAgent, // For matching the engine and version of the browser browserMatch, // The deferred used on DOM ready readyList, // The ready event handler DOMContentLoaded, // Save a reference to some core methods toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty, push = Array.prototype.push, slice = Array.prototype.slice, trim = String.prototype.trim, indexOf = Array.prototype.indexOf, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { 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 && document.body ) { this.context = document; this[0] = document.body; this.selector = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { 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] ) { context = context instanceof jQuery ? context[0] : context; 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 = jQuery.buildFragment( [ match[1] ], [ doc ] ); selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes; } return jQuery.merge( this, selector ); // HANDLE: $("#id") } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // 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: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( 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.7.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[ this.length + num ] : 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 = this.constructor(); 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(); // Add the callback readyList.add( fn ); return this; }, eq: function( i ) { i = +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 || this.constructor(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() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // 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 plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // 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 ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Either a released hold or an DOMready/load event and not yet ready if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.fireWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger( "ready" ).off( "ready" ); } } }, bindReady: function() { if ( readyList ) { return; } readyList = jQuery.Callbacks( "once memory" ); // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready return setTimeout( jQuery.ready, 1 ); } // 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 jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ toString.call(obj) ] || "object"; }, 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 || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 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 || hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { for ( var name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( 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 ); // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { if ( typeof data !== "string" || !data ) { return null; } var xml, tmp; try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && rnotwhite.test( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, 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 ( ; i < length; ) { if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { break; } } } } return object; }, // Use native String.trim function wherever possible trim: trim ? function( text ) { return text == null ? "" : trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); }, // results is for internal usage only makeArray: function( array, results ) { var ret = results || []; if ( array != null ) { // The window, strings (and functions) also have 'length' // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 var type = jQuery.type( array ); if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { push.call( ret, array ); } else { jQuery.merge( ret, array ); } } return ret; }, inArray: function( elem, array, i ) { var len; if ( array ) { if ( indexOf ) { return indexOf.call( array, elem, i ); } len = array.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in array && 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 = [], retVal; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, length = elems.length; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, key, ret = [], i = 0, length = elems.length, // jquery objects are treated as arrays isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( key in elems ) { value = callback( elems[ key ], key, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { if ( typeof context === "string" ) { var tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind var args = slice.call( arguments, 2 ), proxy = function() { return fn.apply( context, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; return proxy; }, // Mutifunctional method to get and set values to a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, pass ) { var exec, bulk = key == null, i = 0, length = elems.length; // Sets many values if ( key && typeof key === "object" ) { for ( i in key ) { jQuery.access( elems, fn, i, key[i], 1, emptyGet, value ); } chainable = 1; // Sets one value } else if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = pass === undefined && jQuery.isFunction( value ); if ( bulk ) { // Bulk operations only iterate when executing function values if ( exec ) { exec = fn; fn = function( elem, key, value ) { return exec.call( jQuery( elem ), value ); }; // Otherwise they run against the entire set } else { fn.call( elems, value ); fn = null; } } if ( fn ) { for (; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } } chainable = 1; } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); }, // Use of jQuery.browser is frowned upon. // More details: http://docs.jquery.com/Utilities/jQuery.browser uaMatch: function( ua ) { ua = ua.toLowerCase(); var match = rwebkit.exec( ua ) || ropera.exec( ua ) || rmsie.exec( ua ) || ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || []; return { browser: match[1] || "", version: match[2] || "0" }; }, sub: function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); return jQuerySub; }, browser: {} }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); 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; } // IE doesn't match non-breaking spaces with \s if ( rnotwhite.test( "\xA0" ) ) { trimLeft = /^[\s\xA0]+/; trimRight = /[\s\xA0]+$/; } // 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(e) { setTimeout( doScrollCheck, 1 ); return; } // and execute any waiting functions jQuery.ready(); } return jQuery; })(); // String to Object flags format cache var flagsCache = {}; // Convert String-formatted flags into Object-formatted ones and store in cache function createFlags( flags ) { var object = flagsCache[ flags ] = {}, i, length; flags = flags.split( /\s+/ ); for ( i = 0, length = flags.length; i < length; i++ ) { object[ flags[i] ] = true; } return object; } /* * Create a callback list using the following parameters: * * flags: an optional list of space-separated flags that will change how * the callback list behaves * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible flags: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( flags ) { // Convert flags from String-formatted to Object-formatted // (we check in cache first) flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {}; var // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = [], // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Add one or several callbacks to the list add = function( args ) { var i, length, elem, type, actual; for ( i = 0, length = args.length; i < length; i++ ) { elem = args[ i ]; type = jQuery.type( elem ); if ( type === "array" ) { // Inspect recursively add( elem ); } else if ( type === "function" ) { // Add if not in unique mode and callback is not in if ( !flags.unique || !self.has( elem ) ) { list.push( elem ); } } } }, // Fire callbacks fire = function( context, args ) { args = args || []; memory = !flags.memory || [ context, args ]; fired = true; firing = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) { memory = true; // Mark as halted break; } } firing = false; if ( list ) { if ( !flags.once ) { if ( stack && stack.length ) { memory = stack.shift(); self.fireWith( memory[ 0 ], memory[ 1 ] ); } } else if ( memory === true ) { self.disable(); } else { list = []; } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { var length = list.length; add( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away, unless previous // firing was halted (stopOnFalse) } else if ( memory && memory !== true ) { firingStart = length; fire( memory[ 0 ], memory[ 1 ] ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { var args = arguments, argIndex = 0, argLength = args.length; for ( ; argIndex < argLength ; argIndex++ ) { for ( var i = 0; i < list.length; i++ ) { if ( args[ argIndex ] === list[ i ] ) { // Handle firingIndex and firingLength if ( firing ) { if ( i <= firingLength ) { firingLength--; if ( i <= firingIndex ) { firingIndex--; } } } // Remove the element list.splice( i--, 1 ); // If we have some unicity property then // we only need to do this once if ( flags.unique ) { break; } } } } } return this; }, // Control if a given callback is in the list has: function( fn ) { if ( list ) { var i = 0, length = list.length; for ( ; i < length; i++ ) { if ( fn === list[ i ] ) { return true; } } } return false; }, // Remove all callbacks from the list empty: function() { list = []; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory || memory === true ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( stack ) { if ( firing ) { if ( !flags.once ) { stack.push( [ context, args ] ); } } else if ( !( flags.once && memory ) ) { fire( context, args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; var // Static reference to slice sliceDeferred = [].slice; jQuery.extend({ Deferred: function( func ) { var doneList = jQuery.Callbacks( "once memory" ), failList = jQuery.Callbacks( "once memory" ), progressList = jQuery.Callbacks( "memory" ), state = "pending", lists = { resolve: doneList, reject: failList, notify: progressList }, promise = { done: doneList.add, fail: failList.add, progress: progressList.add, state: function() { return state; }, // Deprecated isResolved: doneList.fired, isRejected: failList.fired, then: function( doneCallbacks, failCallbacks, progressCallbacks ) { deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks ); return this; }, always: function() { deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments ); return this; }, pipe: function( fnDone, fnFail, fnProgress ) { return jQuery.Deferred(function( newDefer ) { jQuery.each( { done: [ fnDone, "resolve" ], fail: [ fnFail, "reject" ], progress: [ fnProgress, "notify" ] }, function( handler, data ) { var fn = data[ 0 ], action = data[ 1 ], returned; if ( jQuery.isFunction( fn ) ) { deferred[ handler ](function() { returned = fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify ); } else { newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); } }); } else { deferred[ handler ]( newDefer[ action ] ); } }); }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { if ( obj == null ) { obj = promise; } else { for ( var key in promise ) { obj[ key ] = promise[ key ]; } } return obj; } }, deferred = promise.promise({}), key; for ( key in lists ) { deferred[ key ] = lists[ key ].fire; deferred[ key + "With" ] = lists[ key ].fireWith; } // Handle state deferred.done( function() { state = "resolved"; }, failList.disable, progressList.lock ).fail( function() { state = "rejected"; }, doneList.disable, progressList.lock ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( firstParam ) { var args = sliceDeferred.call( arguments, 0 ), i = 0, length = args.length, pValues = new Array( length ), count = length, pCount = length, deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? firstParam : jQuery.Deferred(), promise = deferred.promise(); function resolveFunc( i ) { return function( value ) { args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; if ( !( --count ) ) { deferred.resolveWith( deferred, args ); } }; } function progressFunc( i ) { return function( value ) { pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; deferred.notifyWith( promise, pValues ); }; } if ( length > 1 ) { for ( ; i < length; i++ ) { if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) { args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) ); } else { --count; } } if ( !count ) { deferred.resolveWith( deferred, args ); } } else if ( deferred !== firstParam ) { deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); } return promise; } }); jQuery.support = (function() { var support, all, a, select, opt, input, fragment, tds, events, eventName, i, isSupported, div = document.createElement( "div" ), documentElement = document.documentElement; // Preliminary tests div.setAttribute("className", "t"); div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; all = div.getElementsByTagName( "*" ); a = div.getElementsByTagName( "a" )[ 0 ]; // Can't get basic test support if ( !all || !all.length || !a ) { return {}; } // First batch of supports tests select = document.createElement( "select" ); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName( "input" )[ 0 ]; 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 instead) style: /top/.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: ( input.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: opt.selected, // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // Tests for enctype support on a form(#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // Will be defined later submitBubbles: true, changeBubbles: true, focusinBubbles: false, deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, pixelMargin: true }; // jQuery.boxModel DEPRECATED in 1.3, use jQuery.support.boxModel instead jQuery.boxModel = support.boxModel = (document.compatMode === "CSS1Compat"); // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete div.test; } catch( e ) { support.deleteExpando = false; } if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { div.attachEvent( "onclick", function() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; }); div.cloneNode( true ).fireEvent( "onclick" ); } // Check if a radio maintains its value // after being appended to the DOM input = document.createElement("input"); input.value = "t"; input.setAttribute("type", "radio"); support.radioValue = input.value === "t"; input.setAttribute("checked", "checked"); // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "name", "t" ); div.appendChild( input ); fragment = document.createDocumentFragment(); fragment.appendChild( div.lastChild ); // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; fragment.removeChild( input ); fragment.appendChild( div ); // Technique from Juriy Zaytsev // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ // We only care about the case where non-standard event systems // are used, namely in IE. Short-circuiting here helps us to // avoid an eval call (in setAttribute) which can cause CSP // to go haywire. See: https://developer.mozilla.org/en/Security/CSP if ( div.attachEvent ) { for ( i in { submit: 1, change: 1, focusin: 1 }) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } fragment.removeChild( div ); // Null elements to avoid leaks in IE fragment = select = opt = div = input = null; // Run tests that need a body at doc ready jQuery(function() { var container, outer, inner, table, td, offsetSupport, marginDiv, conMarginTop, style, html, positionTopLeftWidthHeight, paddingMarginBorderVisibility, paddingMarginBorder, body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } conMarginTop = 1; paddingMarginBorder = "padding:0;margin:0;border:"; positionTopLeftWidthHeight = "position:absolute;top:0;left:0;width:1px;height:1px;"; paddingMarginBorderVisibility = paddingMarginBorder + "0;visibility:hidden;"; style = "style='" + positionTopLeftWidthHeight + paddingMarginBorder + "5px solid #000;"; html = "<div " + style + "display:block;'><div style='" + paddingMarginBorder + "0;display:block;overflow:hidden;'></div></div>" + "<table " + style + "' cellpadding='0' cellspacing='0'>" + "<tr><td></td></tr></table>"; container = document.createElement("div"); container.style.cssText = paddingMarginBorderVisibility + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px"; body.insertBefore( container, body.firstChild ); // Construct the test element div = document.createElement("div"); container.appendChild( div ); // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). // (only IE 8 fails this test) div.innerHTML = "<table><tr><td style='" + paddingMarginBorder + "0;display:none'></td><td>t</td></tr></table>"; tds = div.getElementsByTagName( "td" ); isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Check if empty table cells still have offsetWidth/Height // (IE <= 8 fail this test) support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. For more // info see bug #3333 // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right if ( window.getComputedStyle ) { div.innerHTML = ""; marginDiv = document.createElement( "div" ); marginDiv.style.width = "0"; marginDiv.style.marginRight = "0"; div.style.width = "2px"; div.appendChild( marginDiv ); support.reliableMarginRight = ( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; } if ( typeof div.style.zoom !== "undefined" ) { // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout // (IE < 8 does this) div.innerHTML = ""; div.style.width = div.style.padding = "1px"; div.style.border = 0; div.style.overflow = "hidden"; div.style.display = "inline"; div.style.zoom = 1; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = "block"; div.style.overflow = "visible"; div.innerHTML = "<div style='width:5px;'></div>"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); } div.style.cssText = positionTopLeftWidthHeight + paddingMarginBorderVisibility; div.innerHTML = html; outer = div.firstChild; inner = outer.firstChild; td = outer.nextSibling.firstChild.firstChild; offsetSupport = { doesNotAddBorder: ( inner.offsetTop !== 5 ), doesAddBorderForTableAndCells: ( td.offsetTop === 5 ) }; inner.style.position = "fixed"; inner.style.top = "20px"; // safari subtracts parent border width here which is 5px offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 ); inner.style.position = inner.style.top = ""; outer.style.overflow = "hidden"; outer.style.position = "relative"; offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 ); offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop ); if ( window.getComputedStyle ) { div.style.marginTop = "1%"; support.pixelMargin = ( window.getComputedStyle( div, null ) || { marginTop: 0 } ).marginTop !== "1%"; } if ( typeof container.style.zoom !== "undefined" ) { container.style.zoom = 1; } body.removeChild( container ); marginDiv = div = container = null; jQuery.extend( support, offsetSupport ); }); return support; })(); var rbrace = /^(?:\{.*\}|\[.*\])$/, rmultiDash = /([A-Z])/g; jQuery.extend({ cache: {}, // Please use with caution uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var privateCache, thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey, isEvents = name === "events"; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ internalKey ] = id = ++jQuery.uuid; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } privateCache = thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Users should not attempt to inspect the internal events object using jQuery.data, // it is undocumented and subject to change. But does anyone listen? No. if ( isEvents && !thisCache[ name ] ) { return privateCache.events; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( getByName ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, l, // Reference to internal data cache key internalKey = jQuery.expando, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, // See jQuery.data for more information id = isNode ? elem[ internalKey ] : internalKey; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split( " " ); } } } for ( i = 0, l = name.length; i < l; i++ ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject(cache[ id ]) ) { return; } } // Browsers that fail expando deletion also refuse to delete expandos on // the window, but it will allow it on all other JS objects; other browsers // don't care // Ensure that `cache` is not a window object #10080 if ( jQuery.support.deleteExpando || !cache.setInterval ) { delete cache[ id ]; } else { cache[ id ] = null; } // We destroyed the cache and need to eliminate the expando on the node to avoid // false lookups in the cache for entries that no longer exist if ( isNode ) { // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( jQuery.support.deleteExpando ) { delete elem[ internalKey ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { if ( elem.nodeName ) { var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; if ( match ) { return !(match === true || elem.getAttribute("classid") !== match); } } return true; } }); jQuery.fn.extend({ data: function( key, value ) { var parts, part, attr, name, l, elem = this[0], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attr = elem.attributes; for ( l = attr.length; i < l; i++ ) { name = attr[i].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } parts = key.split( ".", 2 ); parts[1] = parts[1] ? "." + parts[1] : ""; part = parts[1] + "!"; return jQuery.access( this, function( value ) { if ( value === undefined ) { data = this.triggerHandler( "getData" + part, [ parts[0] ] ); // Try to fetch any internally stored data first if ( data === undefined && elem ) { data = jQuery.data( elem, key ); data = dataAttr( elem, key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } parts[1] = value; this.each(function() { var self = jQuery( this ); self.triggerHandler( "setData" + part, parts ); jQuery.data( this, key, value ); self.triggerHandler( "changeData" + part, parts ); }); }, null, value, arguments.length > 1, null, false ); }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : jQuery.isNumeric( data ) ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { for ( var name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } function handleQueueMarkDefer( elem, type, src ) { var deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", defer = jQuery._data( elem, deferDataKey ); if ( defer && ( src === "queue" || !jQuery._data(elem, queueDataKey) ) && ( src === "mark" || !jQuery._data(elem, markDataKey) ) ) { // Give room for hard-coded callbacks to fire first // and eventually mark/queue something else on the element setTimeout( function() { if ( !jQuery._data( elem, queueDataKey ) && !jQuery._data( elem, markDataKey ) ) { jQuery.removeData( elem, deferDataKey, true ); defer.fire(); } }, 0 ); } } jQuery.extend({ _mark: function( elem, type ) { if ( elem ) { type = ( type || "fx" ) + "mark"; jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 ); } }, _unmark: function( force, elem, type ) { if ( force !== true ) { type = elem; elem = force; force = false; } if ( elem ) { type = type || "fx"; var key = type + "mark", count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 ); if ( count ) { jQuery._data( elem, key, count ); } else { jQuery.removeData( elem, key, true ); handleQueueMarkDefer( elem, type, "mark" ); } } }, queue: function( elem, type, data ) { var q; if ( elem ) { type = ( type || "fx" ) + "queue"; q = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { 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(), hooks = {}; // 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" ); } jQuery._data( elem, type + ".run", hooks ); fn.call( elem, function() { jQuery.dequeue( elem, type ); }, hooks ); } if ( !queue.length ) { jQuery.removeData( elem, type + "queue " + type + ".run", true ); handleQueueMarkDefer( elem, type, "queue" ); } } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { 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( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, object ) { if ( typeof type !== "string" ) { object = type; type = undefined; } type = type || "fx"; var defer = jQuery.Deferred(), elements = this, i = elements.length, count = 1, deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", tmp; function resolve() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } } while( i-- ) { if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) { count++; tmp.add( resolve ); } } resolve(); return defer.promise( object ); } }); var rclass = /[\n\t\r]/g, rspace = /\s+/, rreturn = /\r/g, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea)?$/i, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, nodeHook, boolHook, fixSpecified; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classNames, i, l, elem, setClass, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call(this, j, this.className) ); }); } if ( value && typeof value === "string" ) { classNames = value.split( rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 ) { if ( !elem.className && classNames.length === 1 ) { elem.className = value; } else { setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { var classNames, i, l, elem, className, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call(this, j, this.className) ); }); } if ( (value && typeof value === "string") || value === undefined ) { classNames = ( value || "" ).split( rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { className = (" " + elem.className + " ").replace( rclass, " " ); for ( 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 ) { jQuery( this ).toggleClass( value.call(this, i, this.className, 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 + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var self = jQuery(this), val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, i, max, option, 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 i = one ? index : 0; max = one ? index + 1 : options.length; for ( ; i < max; i++ ) { option = options[ i ]; // Don't return options that are disabled or in a disabled optgroup if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { // Get the specific 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 ); } } // Fixes Bug #2551 -- select.val() broken in IE after form.reset() if ( one && !values.length && options.length ) { return jQuery( options[ index ] ).val(); } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, attr: function( elem, name, value, pass ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } if ( pass && name in jQuery.attrFn ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, "" + value ); return value; } } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }, removeAttr: function( elem, value ) { var propName, attrNames, name, l, isBool, i = 0; if ( value && elem.nodeType === 1 ) { attrNames = value.toLowerCase().split( rspace ); l = attrNames.length; for ( ; i < l; i++ ) { name = attrNames[ i ]; if ( name ) { propName = jQuery.propFix[ name ] || name; isBool = rboolean.test( name ); // See #9699 for explanation of this approach (setting first, then removal) // Do not do this for boolean attributes (see #10870) if ( !isBool ) { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); // Set corresponding property to false for boolean attributes if ( isBool && propName in elem ) { elem[ propName ] = false; } } } } }, attrHooks: { type: { set: function( elem, value ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to it's default in case type is set after value // This is for element creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } }, // Use the value property for back compat // Use the nodeHook for button elements in IE6/7 (#1954) value: { get: function( elem, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.get( elem, name ); } return name in elem ? elem.value : null; }, set: function( elem, value, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.set( elem, value, name ); } // Does not return so that setAttribute is also used elem.value = value; } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return ( elem[ name ] = value ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }, propHooks: { tabIndex: { get: function( elem ) { // 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/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Add the tabIndex propHook to attrHooks for back-compat (different case is intentional) jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex; // Hook for boolean attributes boolHook = { get: function( elem, name ) { // Align boolean attributes with corresponding properties // Fall back to attribute presence where some booleans are not supported var attrNode, property = jQuery.prop( elem, name ); return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { var propName; if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { // value is true since we know at this point it's type boolean and not false // Set boolean attributes to the same name and set the DOM property propName = jQuery.propFix[ name ] || name; if ( propName in elem ) { // Only set the IDL specifically if it already exists on the element elem[ propName ] = true; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { fixSpecified = { name: true, id: true, coords: true }; // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function( elem, name ) { var ret; ret = elem.getAttributeNode( name ); return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ? ret.nodeValue : undefined; }, set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { ret = document.createAttribute( name ); elem.setAttributeNode( ret ); } return ( ret.nodeValue = value + "" ); } }; // Apply the nodeHook to tabindex jQuery.attrHooks.tabindex.set = nodeHook.set; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function( elem, value, name ) { if ( value === "" ) { value = "false"; } nodeHook.set( elem, value, name ); } }; } // Some attributes require a special call on IE if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret === null ? undefined : ret; } }); }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Normalize to lowercase since IE uppercases css property names return elem.style.cssText.toLowerCase() || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = "" + value ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }); }); var rformElems = /^(?:textarea|input|select)$/i, rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/, rhoverHack = /(?:^|\s)hover(\.\S+)?\b/, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/, quickParse = function( selector ) { var quick = rquickIs.exec( selector ); if ( quick ) { // 0 1 2 3 // [ _, tag, id, class ] quick[1] = ( quick[1] || "" ).toLowerCase(); quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" ); } return quick; }, quickIs = function( elem, m ) { var attrs = elem.attributes || {}; return ( (!m[1] || elem.nodeName.toLowerCase() === m[1]) && (!m[2] || (attrs.id || {}).value === m[2]) && (!m[3] || m[3].test( (attrs[ "class" ] || {}).value )) ); }, hoverHack = function( events ) { return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); }; /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { add: function( elem, types, handler, data, selector ) { var elemData, eventHandle, events, t, tns, type, namespaces, handleObj, handleObjIn, quick, handlers, special; // Don't attach events to noData or text/comment nodes (allow plain objects tho) if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first events = elemData.events; if ( !events ) { elemData.events = events = {}; } eventHandle = elemData.handle; if ( !eventHandle ) { elemData.handle = eventHandle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = jQuery.trim( hoverHack(types) ).split( " " ); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = tns[1]; namespaces = ( tns[2] || "" ).split( "." ).sort(); // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: tns[1], data: data, handler: handler, guid: handler.guid, selector: selector, quick: selector && quickParse( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first handlers = events[ type ]; if ( !handlers ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // 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 to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization 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, selector, mappedTypes ) { var elemData = jQuery.hasData( elem ) && jQuery._data( elem ), t, tns, type, origType, namespaces, origCount, j, events, special, handle, eventType, handleObj; if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = jQuery.trim( hoverHack( types || "" ) ).split(" "); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = origType = tns[1]; namespaces = tns[2]; // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector? special.delegateType : special.bindType ) || type; eventType = events[ type ] || []; origCount = eventType.length; namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null; // Remove matching events for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !namespaces || namespaces.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { eventType.splice( j--, 1 ); if ( handleObj.selector ) { eventType.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( eventType.length === 0 && origCount !== eventType.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { handle = elemData.handle; if ( handle ) { handle.elem = null; } // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery.removeData( elem, [ "events", "handle" ], true ); } }, // Events that are safe to short-circuit if no handlers are attached. // Native DOM events should not be added, they may have inline handlers. customEvent: { "getData": true, "setData": true, "changeData": true }, trigger: function( event, data, elem, onlyHandlers ) { // Don't do events on text and comment nodes if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { return; } // Event object or event type var type = event.type || event, namespaces = [], cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType; // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "!" ) >= 0 ) { // Exclusive events trigger only for the exact event (no namespaces) type = type.slice(0, -1); exclusive = true; } if ( type.indexOf( "." ) >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { // No jQuery handlers for this event type, and it can't have inline handlers return; } // Caller can pass in an Event, Object, or just an event type string event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal new jQuery.Event( type, event ) : // Just the event type (string) new jQuery.Event( type ); event.type = type; event.isTrigger = true; event.exclusive = exclusive; event.namespace = namespaces.join( "." ); event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null; ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; // Handle a global trigger if ( !elem ) { // TODO: Stop taunting the data cache; remove global events and always attach to document cache = jQuery.cache; for ( i in cache ) { if ( cache[ i ].events && cache[ i ].events[ type ] ) { jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); } } return; } // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data != null ? jQuery.makeArray( data ) : []; data.unshift( event ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) eventPath = [[ elem, special.bindType || type ]]; if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; old = null; for ( ; cur; cur = cur.parentNode ) { eventPath.push([ cur, bubbleType ]); old = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( old && old === elem.ownerDocument ) { eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); } } // Fire handlers on the event path for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { cur = eventPath[i][0]; event.type = eventPath[i][1]; handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Note that this is a bare JS function and not a jQuery handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) // IE<9 dies on focus/blur to hidden element (#1486) if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method old = elem[ ontype ]; if ( old ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( old ) { elem[ ontype ] = old; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event || window.event ); var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), delegateCount = handlers.delegateCount, args = [].slice.call( arguments, 0 ), run_all = !event.exclusive && !event.namespace, special = jQuery.event.special[ event.type ] || {}, handlerQueue = [], i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers that should run if there are delegated events // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && !(event.button && event.type === "click") ) { // Pregenerate a single jQuery object for reuse with .is() jqcur = jQuery(this); jqcur.context = this.ownerDocument || this; for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { // Don't process events on disabled elements (#6911, #8165) if ( cur.disabled !== true ) { selMatch = {}; matches = []; jqcur[0] = cur; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; sel = handleObj.selector; if ( selMatch[ sel ] === undefined ) { selMatch[ sel ] = ( handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel ) ); } if ( selMatch[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, matches: matches }); } } } } // Add the remaining (directly-bound) handlers if ( handlers.length > delegateCount ) { handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); } // Run delegates first; they may want to stop propagation beneath us for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { matched = handlerQueue[ i ]; event.currentTarget = matched.elem; for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { handleObj = matched.matches[ j ]; // Triggered event must either 1) be non-exclusive and have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { event.data = handleObj.data; event.handleObj = handleObj; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, // Includes some event props shared by KeyEvent and MouseEvent // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, originalEvent = event, fixHook = jQuery.event.fixHooks[ event.type ] || {}, copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = jQuery.Event( originalEvent ); for ( i = copy.length; i; ) { prop = copy[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Target should not be a text node (#504, Safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8) if ( event.metaKey === undefined ) { event.metaKey = event.ctrlKey; } return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { ready: { // Make sure the ready event is setup setup: jQuery.bindReady }, load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { delegateType: "focusin" }, blur: { delegateType: "focusout" }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; // Some plugins are using, but it's undocumented/deprecated and will be removed. // The 1.7 special event interface should provide all the hooks needed now. jQuery.event.handle = jQuery.event.dispatch; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { if ( elem.detachEvent ) { elem.detachEvent( "on" + type, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.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) } else { 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 }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var target = this, related = event.relatedTarget, handleObj = event.handleObj, selector = handleObj.selector, ret; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !form._submit_attached ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); form._submit_attached = true; } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; jQuery.event.simulate( "change", this, event, true ); } }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); elem._change_attached = true; } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // && selector != null // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event var handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( var type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, live: function( types, data, fn ) { jQuery( this.context ).on( types, this.selector, data, fn ); return this; }, die: function( types, fn ) { jQuery( this.context ).off( types, this.selector || "**", fn ); return this; }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn ); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { return jQuery.event.trigger( type, data, this[0], true ); } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, guid = fn.guid || jQuery.guid++, i = 0, toggler = 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; }; // link all the functions, so any of them can unbind this click handler toggler.guid = guid; while ( i < args.length ) { args[ i++ ].guid = guid; } return this.click( toggler ); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); 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 contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; if ( jQuery.attrFn ) { jQuery.attrFn[ name ] = true; } if ( rkeyEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; } if ( rmouseEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; } }); /*! * Sizzle CSS Selector Engine * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, expando = "sizcache" + (Math.random() + '').replace('.', ''), done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true, rBackslash = /\\/g, rReturn = /\r\n/g, rNonWord = /\W/; // 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 || []; context = context || document; var origContext = context; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var m, set, checkSet, extra, ret, cur, pop, i, prune = true, contextXML = Sizzle.isXML( context ), parts = [], soFar = selector; // Reset the position of the chunker regexp (start from head) do { chunker.exec( "" ); m = chunker.exec( soFar ); if ( m ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } } while ( m ); if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context, seed ); } 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, seed ); } } } 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]) ) { ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { 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 ) { 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 ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( 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.matchesSelector = function( node, expr ) { return Sizzle( expr, null, null, [node] ).length > 0; }; Sizzle.find = function( expr, context, isXML ) { var set, i, len, match, type, left; if ( !expr ) { return []; } for ( i = 0, len = Expr.order.length; i < len; i++ ) { type = Expr.order[i]; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { left = match[1]; match.splice( 1, 1 ); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace( rBackslash, "" ); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( "*" ) : []; } return { set: set, expr: expr }; }; Sizzle.filter = function( expr, set, inplace, not ) { var match, anyFound, type, found, item, filter, left, i, pass, old = expr, result = [], curLoop = set, isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); while ( expr && set.length ) { for ( type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { filter = Expr.filter[ type ]; 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 ( i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); 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 new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Utility function for retreiving the text value of an array of DOM nodes * @param {Array|Element} elem */ var getText = Sizzle.getText = function( elem ) { var i, node, nodeType = elem.nodeType, ret = ""; if ( nodeType ) { if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent || innerText for elements if ( typeof elem.textContent === 'string' ) { return elem.textContent; } else if ( typeof elem.innerText === 'string' ) { // Replace IE's carriage returns return elem.innerText.replace( rReturn, '' ); } else { // Traverse it's children for ( elem = elem.firstChild; elem; elem = elem.nextSibling) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } } else { // If no nodeType, this is expected to be an array for ( i = 0; (node = elem[i]); i++ ) { // Do not traverse comment nodes if ( node.nodeType !== 8 ) { ret += getText( node ); } } } return ret; }; 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|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, 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" ); }, type: function( elem ) { return elem.getAttribute( "type" ); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !rNonWord.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 elem, isPartStr = typeof part === "string", i = 0, l = checkSet.length; if ( isPartStr && !rNonWord.test( part ) ) { part = part.toLowerCase(); for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( ; i < l; i++ ) { 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 nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); }, "~": function( checkSet, part, isXML ) { var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; 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]); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [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 ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( match[1] ); } } }, preFilter: { CLASS: function( match, curLoop, inplace, result, not, isXML ) { match = " " + match[1].replace( rBackslash, "" ) + " "; 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\r]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function( match ) { return match[1].replace( rBackslash, "" ); }, TAG: function( match, curLoop ) { return match[1].replace( rBackslash, "" ).toLowerCase(); }, CHILD: function( match ) { if ( match[1] === "nth" ) { if ( !match[2] ) { Sizzle.error( match[0] ); } match[2] = match[2].replace(/^\+|\s*/g, ''); // 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; } else if ( match[2] ) { Sizzle.error( match[0] ); } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function( match, curLoop, inplace, result, not, isXML ) { var name = match[1] = match[1].replace( rBackslash, "" ); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } // Handle if an un-quoted value was used match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); 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 if ( elem.parentNode ) { 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 ) { var attr = elem.getAttribute( "type" ), type = elem.type; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); }, radio: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; }, checkbox: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; }, file: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; }, password: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; }, submit: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "submit" === elem.type; }, image: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; }, reset: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "reset" === elem.type; }, button: function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && "button" === elem.type || name === "button"; }, input: function( elem ) { return (/input|select|textarea|button/i).test( elem.nodeName ); }, focus: function( elem ) { return elem === elem.ownerDocument.activeElement; } }, 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 j = 0, l = not.length; j < l; j++ ) { if ( not[j] === elem ) { return false; } } return true; } else { Sizzle.error( name ); } }, CHILD: function( elem, match ) { var first, last, doneName, parent, cache, count, diff, 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; /* falls through */ case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case "nth": first = match[2]; last = match[3]; if ( first === 1 && last === 0 ) { return true; } doneName = match[0]; parent = elem.parentNode; if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) { count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent[ expando ] = doneName; } 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 && 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 = Sizzle.attr ? Sizzle.attr( elem, name ) : 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 && Sizzle.attr ? result != null : 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, fescape = function(all, num){ return "\\" + (num - 0 + 1); }; 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, fescape) ); } // Expose origPOS // "global" as in regardless of relation to brackets/parens Expr.match.globalPOS = origPOS; 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 i = 0, ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( ; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder, siblingCheck; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { return a.compareDocumentPosition ? -1 : 1; } return a.compareDocumentPosition(b) & 4 ? -1 : 1; }; } else { sortOrder = function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return a.sourceIndex - b.sourceIndex; } var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // If the nodes are siblings (or identical) we can do a quick check if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; siblingCheck = function( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; }; } // 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(), root = document.documentElement; form.innerHTML = "<a name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly 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 ); // release memory in IE root = form = null; })(); (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 ); }; } // release memory in IE div = null; })(); if ( document.querySelectorAll ) { (function(){ var oldSizzle = Sizzle, div = document.createElement("div"), id = "__sizzle__"; 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 && !Sizzle.isXML(context) ) { // See if we find a selector to speed up var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { // Speed-up: Sizzle("TAG") if ( match[1] ) { return makeArray( context.getElementsByTagName( query ), extra ); // Speed-up: Sizzle(".CLASS") } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { return makeArray( context.getElementsByClassName( match[2] ), extra ); } } if ( context.nodeType === 9 ) { // Speed-up: Sizzle("body") // The body element only exists once, optimize finding it if ( query === "body" && context.body ) { return makeArray( [ context.body ], extra ); // Speed-up: Sizzle("#ID") } else if ( match && match[3] ) { var elem = context.getElementById( match[3] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id === match[3] ) { return makeArray( [ elem ], extra ); } } else { return makeArray( [], extra ); } } try { return makeArray( context.querySelectorAll(query), extra ); } catch(qsaError) {} // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { var oldContext = context, old = context.getAttribute( "id" ), nid = old || id, hasParent = context.parentNode, relativeHierarchySelector = /^\s*[+~]/.test( query ); if ( !old ) { context.setAttribute( "id", nid ); } else { nid = nid.replace( /'/g, "\\$&" ); } if ( relativeHierarchySelector && hasParent ) { context = context.parentNode; } try { if ( !relativeHierarchySelector || hasParent ) { return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); } } catch(pseudoError) { } finally { if ( !old ) { oldContext.removeAttribute( "id" ); } } } } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } // release memory in IE div = null; })(); } (function(){ var html = document.documentElement, matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; if ( matches ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9 fails this) var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), pseudoWorks = false; try { // This should fail with an exception // Gecko does not error, returns false instead matches.call( document.documentElement, "[test!='']:sizzle" ); } catch( pseudoError ) { pseudoWorks = true; } Sizzle.matchesSelector = function( node, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); if ( !Sizzle.isXML( node ) ) { try { if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { var ret = matches.call( node, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || !disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9, so check for that node.document && node.document.nodeType !== 11 ) { return ret; } } } catch(e) {} } return Sizzle(expr, null, null, [node]).length > 0; }; } })(); (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]); } }; // release memory in IE div = null; })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem[ expando ] === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem[ expando ] = 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 ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem[ expando ] === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem[ expando ] = 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; } } } if ( document.documentElement.contains ) { Sizzle.contains = function( a, b ) { return a !== b && (a.contains ? a.contains(b) : true); }; } else if ( document.documentElement.compareDocumentPosition ) { Sizzle.contains = function( a, b ) { return !!(a.compareDocumentPosition(b) & 16); }; } else { Sizzle.contains = function() { return false; }; } Sizzle.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, seed ) { var match, tmpSet = [], later = "", 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, seed ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; Sizzle.selectors.attrMap = {}; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.filters; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })(); var runtil = /Until$/, rparentsprev = /^(?:parents|prevUntil|prevAll)/, // Note: This RegExp should be improved, or likely pulled from Sizzle rmultiselector = /,/, isSimple = /^.[^:#\[\.,]*$/, slice = Array.prototype.slice, POS = jQuery.expr.match.globalPOS, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var self = this, i, l; if ( typeof selector !== "string" ) { return jQuery( selector ).filter(function() { for ( i = 0, l = self.length; i < l; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }); } var ret = this.pushStack( "", "find", selector ), length, n, r; for ( 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 ( n = length; n < ret.length; n++ ) { for ( 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 && ( typeof selector === "string" ? // If this is a positional selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". POS.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var ret = [], i, l, cur = this[0]; // Array (deprecated as of jQuery 1.7) if ( jQuery.isArray( selectors ) ) { var level = 1; while ( cur && cur.ownerDocument && cur !== context ) { for ( i = 0; i < selectors.length; i++ ) { if ( jQuery( cur ).is( selectors[ i ] ) ) { ret.push({ selector: selectors[ i ], elem: cur, level: level }); } } cur = cur.parentNode; level++; } return ret; } // String var pos = POS.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( i = 0, l = this.length; i < l; i++ ) { cur = this[i]; while ( cur ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } else { cur = cur.parentNode; if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { break; } } } } ret = ret.length > 1 ? jQuery.unique( ret ) : ret; return this.pushStack( ret, "closest", selectors ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // 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 ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : 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 && !guaranteedUnique[ name ] ? 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 elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : 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; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === 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; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style)/i, rnocache = /<(?:script|object|embed|option|style)/i, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/, 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, "", "" ] }, safeFragment = createSafeFragment( document ); 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( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, 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 ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : 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.clean( arguments ); 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.clean(arguments) ); 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( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : null; } if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName( "*" ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, 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.length ? this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : this; } }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { var results, first, fragment, parent, value = args[0], scripts = []; // 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 = jQuery.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, lastIndex = l - 1; i < l; i++ ) { callback.call( table ? root(this[i], first) : this[i], // Make sure that we do not leak memory by inadvertently discarding // the original fragment (which might have attached data) instead of // using it; in addition, use the original fragment object for the last // item instead of first because it can end up being emptied incorrectly // in certain situations (Bug #8070). // Fragments from the fragment cache must always be cloned and never used // in place. results.cacheable || ( l > 1 && i < lastIndex ) ? jQuery.clone( fragment, true, true ) : fragment ); } } if ( scripts.length ) { jQuery.each( scripts, function( i, elem ) { if ( elem.src ) { jQuery.ajax({ type: "GET", global: false, url: elem.src, async: false, dataType: "script" }); } else { jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } }); } } return this; } }); function root( elem, cur ) { return jQuery.nodeName(elem, "table") ? (elem.getElementsByTagName("tbody")[0] || elem.appendChild(elem.ownerDocument.createElement("tbody"))) : elem; } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function cloneFixAttributes( src, dest ) { var nodeName; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want if ( dest.clearAttributes ) { dest.clearAttributes(); } // mergeAttributes, in contrast, only merges back on the // original attributes, not the events if ( dest.mergeAttributes ) { dest.mergeAttributes( src ); } nodeName = dest.nodeName.toLowerCase(); // IE6-8 fail to clone children inside object elements that use // the proprietary classid attribute value (rather than the type // attribute) to identify the type of content to display if ( nodeName === "object" ) { dest.outerHTML = src.outerHTML; } else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set if ( src.checked ) { dest.defaultChecked = dest.checked = src.checked; } // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; // IE blanks contents when cloning scripts } else if ( nodeName === "script" && dest.text !== src.text ) { dest.text = src.text; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); // Clear flags for bubbling special change/submit events, they must // be reattached when the newly cloned events are first activated dest.removeAttribute( "_submit_attached" ); dest.removeAttribute( "_change_attached" ); } jQuery.buildFragment = function( args, nodes, scripts ) { var fragment, cacheable, cacheresults, doc, first = args[ 0 ]; // nodes may contain either an explicit document object, // a jQuery collection or context object. // If nodes[0] contains a valid object to assign to doc if ( nodes && nodes[0] ) { doc = nodes[0].ownerDocument || nodes[0]; } // Ensure that an attr object doesn't incorrectly stand in as a document object // Chrome and Firefox seem to allow this to occur and will throw exception // Fixes #8950 if ( !doc.createDocumentFragment ) { doc = document; } // Only cache "small" (1/2 KB) HTML 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 // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501 if ( args.length === 1 && typeof first === "string" && first.length < 512 && doc === document && first.charAt(0) === "<" && !rnocache.test( first ) && (jQuery.support.checkClone || !rchecked.test( first )) && (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { cacheable = true; cacheresults = jQuery.fragments[ first ]; if ( cacheresults && cacheresults !== 1 ) { fragment = cacheresults; } } if ( !fragment ) { fragment = doc.createDocumentFragment(); jQuery.clean( args, doc, fragment, scripts ); } if ( cacheable ) { jQuery.fragments[ first ] = 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( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( typeof elem.getElementsByTagName !== "undefined" ) { return elem.getElementsByTagName( "*" ); } else if ( typeof elem.querySelectorAll !== "undefined" ) { return elem.querySelectorAll( "*" ); } else { return []; } } // Used in clean, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( elem.type === "checkbox" || elem.type === "radio" ) { elem.defaultChecked = elem.checked; } } // Finds all inputs and passes them to fixDefaultChecked function findInputs( elem ) { var nodeName = ( elem.nodeName || "" ).toLowerCase(); if ( nodeName === "input" ) { fixDefaultChecked( elem ); // Skip scripts, get other children } else if ( nodeName !== "script" && typeof elem.getElementsByTagName !== "undefined" ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } // Derived From: http://www.iecss.com/shimprove/javascript/shimprove.1-0-1.js function shimCloneNode( elem ) { var div = document.createElement( "div" ); safeFragment.appendChild( div ); div.innerHTML = elem.outerHTML; return div.firstChild; } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var srcElements, destElements, i, // IE<=8 does not properly clone detached, unknown element nodes clone = jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ? elem.cloneNode( true ) : shimCloneNode( elem ); if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // IE copies events bound via attachEvent when using cloneNode. // Calling detachEvent on the clone will also remove the events // from the original. In order to get around this, we use some // proprietary methods to clear the events. Thanks to MooTools // guys for this hotness. cloneFixAttributes( elem, clone ); // Using Sizzle here is crazy slow, so we use getElementsByTagName instead srcElements = getAll( elem ); destElements = getAll( clone ); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for ( i = 0; srcElements[i]; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { cloneFixAttributes( srcElements[i], destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { cloneCopyEvent( elem, clone ); if ( deepDataAndEvents ) { srcElements = getAll( elem ); destElements = getAll( clone ); for ( i = 0; srcElements[i]; ++i ) { cloneCopyEvent( srcElements[i], destElements[i] ); } } } srcElements = destElements = null; // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { var checkScriptType, script, j, ret = []; 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; } 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" ) { if ( !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else { // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // 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"), safeChildNodes = safeFragment.childNodes, remove; // Append wrapper element to unknown element safe doc fragment if ( context === document ) { // Use the fragment we've already created for this document safeFragment.appendChild( div ); } else { // Use a fragment created with the owner document createSafeFragment( context ).appendChild( 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 ( 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; // Clear elements from DocumentFragment (safeFragment or otherwise) // to avoid hoarding elements. Fixes #11356 if ( div ) { div.parentNode.removeChild( div ); // Guard against -1 index exceptions in FF3.6 if ( safeChildNodes.length > 0 ) { remove = safeChildNodes[ safeChildNodes.length - 1 ]; if ( remove && remove.parentNode ) { remove.parentNode.removeChild( remove ); } } } } } // Resets defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) var len; if ( !jQuery.support.appendChecked ) { if ( elem[0] && typeof (len = elem.length) === "number" ) { for ( j = 0; j < len; j++ ) { findInputs( elem[j] ); } } else { findInputs( elem ); } } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } } if ( fragment ) { checkScriptType = function( elem ) { return !elem.type || rscriptType.test( elem.type ); }; for ( i = 0; ret[i]; i++ ) { script = ret[i]; if ( scripts && jQuery.nodeName( script, "script" ) && (!script.type || rscriptType.test( script.type )) ) { scripts.push( script.parentNode ? script.parentNode.removeChild( script ) : script ); } else { if ( script.nodeType === 1 ) { var jsTags = jQuery.grep( script.getElementsByTagName( "script" ), checkScriptType ); ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); } fragment.appendChild( script ); } } } 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++ ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { continue; } id = elem[ jQuery.expando ]; if ( id ) { data = cache[ id ]; if ( data && data.events ) { for ( var type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } // Null the DOM reference to avoid IE6/7/8 leak (#7054) if ( data.handle ) { data.handle.elem = null; } } if ( deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } delete cache[ id ]; } } } }); var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, // fixed for IE9, see #8346 rupper = /([A-Z]|^ms)/g, rnum = /^[\-+]?(?:\d*\.)?\d+$/i, rnumnonpx = /^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i, rrelNum = /^([\-+])=([\-+.\de]+)/, rmargin = /^margin/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, // order is important! cssExpand = [ "Top", "Right", "Bottom", "Left" ], curCSS, getComputedStyle, currentStyle; jQuery.fn.css = function( name, value ) { return jQuery.access( this, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }; jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } else { return elem.style.opacity; } } } }, // Exclude the following css properties to add px cssNumber: { "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, origName = jQuery.camelCase( name ), style = elem.style, hooks = jQuery.cssHooks[ origName ]; name = jQuery.cssProps[ origName ] || origName; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( +( ret[1] + 1) * +ret[2] ) + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra ) { var ret, hooks; // Make sure that we're working with the right name name = jQuery.camelCase( name ); hooks = jQuery.cssHooks[ name ]; name = jQuery.cssProps[ name ] || name; // cssFloat needs a special treatment if ( name === "cssFloat" ) { name = "float"; } // If a hook was provided get the computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) { return ret; // Otherwise, if a way to get the computed value exists, use that } else if ( curCSS ) { return curCSS( elem, name ); } }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var old = {}, ret, name; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); // DEPRECATED in 1.3, Use jQuery.css() instead jQuery.curCSS = jQuery.css; if ( document.defaultView && document.defaultView.getComputedStyle ) { getComputedStyle = function( elem, name ) { var ret, defaultView, computedStyle, width, style = elem.style; name = name.replace( rupper, "-$1" ).toLowerCase(); if ( (defaultView = elem.ownerDocument.defaultView) && (computedStyle = defaultView.getComputedStyle( elem, null )) ) { ret = computedStyle.getPropertyValue( name ); if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { ret = jQuery.style( elem, name ); } } // A tribute to the "tr33 hack by Dean Edwards" // WebKit uses "computed value (percentage if specified)" instead of "used value" for margins // which is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( !jQuery.support.pixelMargin && computedStyle && rmargin.test( name ) && rnumnonpx.test( ret ) ) { width = style.width; style.width = ret; ret = computedStyle.width; style.width = width; } return ret; }; } if ( document.documentElement.currentStyle ) { currentStyle = function( elem, name ) { var left, rsLeft, uncomputed, ret = elem.currentStyle && elem.currentStyle[ name ], style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && (uncomputed = style[ name ]) ) { ret = uncomputed; } // From the tr33 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 ( rnumnonpx.test( ret ) ) { // Remember the original values left = style.left; rsLeft = elem.runtimeStyle && elem.runtimeStyle.left; // Put in the new values to get a computed value out if ( rsLeft ) { elem.runtimeStyle.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } curCSS = getComputedStyle || currentStyle; function getWidthOrHeight( elem, name, extra ) { // Start with offset property var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, i = name === "width" ? 1 : 0, len = 4; if ( val > 0 ) { if ( extra !== "border" ) { for ( ; i < len; i += 2 ) { if ( !extra ) { val -= parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ] ) ) || 0; } else { val -= parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } } return val + "px"; } // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; // Add padding, border, margin if ( extra ) { for ( ; i < len; i += 2 ) { val += parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0; if ( extra !== "padding" ) { val += parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ]) ) || 0; } } } return val + "px"; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { if ( elem.offsetWidth !== 0 ) { return getWidthOrHeight( elem, name, extra ); } else { return jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }); } } }, set: function( elem, value ) { return rnum.test( value ) ? value + "px" : value; } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( parseFloat( RegExp.$1 ) / 100 ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there there is no filter style applied in a css rule, we are done if ( currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } jQuery(function() { // This hook cannot be added until DOM ready because the support test // for it is not run until after DOM ready if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { return curCSS( elem, "margin-right" ); } else { return elem.style.marginRight; } }); } }; } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight; return ( width === 0 && height === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ], expanded = {}; for ( i = 0; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rselectTextarea = /^(?:select|textarea)/i, rspacesAjax = /\s+/, rts = /([?&])_=[^&]*/, rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Document location ajaxLocation, // Document location segments ajaxLocParts, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = ["*/"] + ["*"]; // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } if ( jQuery.isFunction( func ) ) { var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ), i = 0, length = dataTypes.length, dataType, list, placeBefore; // For each dataType in the dataTypeExpression for ( ; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ), selection; for ( ; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } } jQuery.fn.extend({ load: function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); // 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 = undefined; // 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 callback (responseText is used internally) complete: function( jqXHR, status, responseText ) { // Store the response as specified by the jqXHR object responseText = jqXHR.responseText; // If successful, inject the HTML into all the matched elements if ( jqXHR.isResolved() ) { // #4825: Get the actual response in case // a dataFilter is present in ajaxSettings jqXHR.done(function( r ) { responseText = r; }); // 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(responseText.replace(rscript, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result responseText ); } if ( callback ) { self.each( callback, [ responseText, status, jqXHR ] ); } } }); 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.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).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.on( o, f ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; }); jQuery.extend({ getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { if ( settings ) { // Building a settings object ajaxExtend( target, jQuery.ajaxSettings ); } else { // Extending ajaxSettings settings = target; target = jQuery.ajaxSettings; } ajaxExtend( target, settings ); return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded; charset=UTF-8", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, traditional: false, headers: {}, */ accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": allTypes }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // List of data converters // 1) key format is "source_type destination_type" (a single space in-between) // 2) the catchall symbol "*" can be used for source_type converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { context: true, url: true } }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events // It's the callbackContext if one was provided in the options // and if it's a DOM node or a jQuery collection globalEventContext = callbackContext !== s && ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // ifModified key ifModifiedKey, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // The jqXHR state state = 0, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Fake xhr jqXHR = { readyState: 0, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { var lname = name.toLowerCase(); name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match === undefined ? null : match; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Cancel the request abort: function( statusText ) { statusText = statusText || "abort"; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) function done( status, nativeStatusText, responses, headers ) { // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; var isSuccess, success, error, statusText = nativeStatusText, response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined, lastModified, etag; // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) { jQuery.lastModified[ ifModifiedKey ] = lastModified; } if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) { jQuery.etag[ ifModifiedKey ] = etag; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { try { success = ajaxConvert( s, response ); statusText = "success"; isSuccess = true; } catch(e) { // We have a parsererror statusText = "parsererror"; error = e; } } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( !statusText || status ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = "" + ( nativeStatusText || statusText ); // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } // Attach deferreds deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; jqXHR.complete = completeDeferred.add; // Status-dependent callbacks jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { for ( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.then( tmp, tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax ); // Determine if a cross-domain request is in order if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return false; } // We can fire global events as of now if asked to fireGlobals = s.global; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Get ifModifiedKey before adding the anti-cache parameter ifModifiedKey = s.url; // Add anti-cache in url if needed if ( s.cache === false ) { var ts = jQuery.now(), // try replacing _= if it is there ret = s.url.replace( rts, "$1_=" + ts ); // if nothing was replaced, add timestamp to the end s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { ifModifiedKey = ifModifiedKey || s.url; if ( jQuery.lastModified[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); } if ( jQuery.etag[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); } } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already jqXHR.abort(); return false; } // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout( function(){ jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } return jqXHR; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a, traditional ) { var s = [], add = function( 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 ); }; // 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 && !jQuery.isPlainObject( a ) ) ) { // 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 ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); } }); function buildParams( prefix, obj, traditional, add ) { if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.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" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( var name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // This is still on the jQuery object... for now // Want to move this to jQuery.ajax some day jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields, ct, type, finalDataType, firstDataType; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } var dataTypes = s.dataTypes, converters = {}, i, key, length = dataTypes.length, tmp, // Current and previous dataTypes current = dataTypes[ 0 ], prev, // Conversion expression conversion, // Conversion function conv, // Conversion functions (transitive conversion) conv1, conv2; // For each dataType in the chain for ( i = 1; i < length; i++ ) { // Create converters map // with lowercased keys if ( i === 1 ) { for ( key in s.converters ) { if ( typeof key === "string" ) { converters[ key.toLowerCase() ] = s.converters[ key ]; } } } // Get the dataTypes prev = current; current = dataTypes[ i ]; // If current is auto dataType, update it to prev if ( current === "*" ) { current = prev; // If no auto and dataTypes are actually different } else if ( prev !== "*" && prev !== current ) { // Get the converter conversion = prev + " " + current; conv = converters[ conversion ] || converters[ "* " + current ]; // If there is no direct converter, search transitively if ( !conv ) { conv2 = undefined; for ( conv1 in converters ) { tmp = conv1.split( " " ); if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) { conv2 = converters[ tmp[1] + " " + current ]; if ( conv2 ) { conv1 = converters[ conv1 ]; if ( conv1 === true ) { conv = conv2; } else if ( conv2 === true ) { conv = conv1; } break; } } } } // If we found no converter, dispatch an error if ( !( conv || conv2 ) ) { jQuery.error( "No conversion from " + conversion.replace(" "," to ") ); } // If found converter is not an equivalence if ( conv !== true ) { // Convert with 1 or 2 converters accordingly response = conv ? conv( response ) : conv2( conv1(response) ); } } } return response; } var jsc = jQuery.now(), jsre = /(\=)\?(&|$)|\?\?/i; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { return jQuery.expando + "_" + ( jsc++ ); } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var inspectData = ( typeof s.data === "string" ) && /^application\/x\-www\-form\-urlencoded/.test( s.contentType ); if ( s.dataTypes[ 0 ] === "jsonp" || s.jsonp !== false && ( jsre.test( s.url ) || inspectData && jsre.test( s.data ) ) ) { var responseContainer, jsonpCallback = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback, previous = window[ jsonpCallback ], url = s.url, data = s.data, replace = "$1" + jsonpCallback + "$2"; if ( s.jsonp !== false ) { url = url.replace( jsre, replace ); if ( s.url === url ) { if ( inspectData ) { data = data.replace( jsre, replace ); } if ( s.data === data ) { // Add callback manually url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback; } } } s.url = url; s.data = data; // Install callback window[ jsonpCallback ] = function( response ) { responseContainer = [ response ]; }; // Clean-up function jqXHR.always(function() { // Set callback back to previous value window[ jsonpCallback ] = previous; // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( previous ) ) { window[ jsonpCallback ]( responseContainer[ 0 ] ); } }); // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( jsonpCallback + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Delegate to script return "script"; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( head && script.parentNode ) { head.removeChild( script ); } // Dereference the script script = undefined; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // 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 ); }, abort: function() { if ( script ) { script.onload( 0, 1 ); } } }; } }); var // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject ? function() { // Abort all pending requests for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( 0, 1 ); } } : false, xhrId = 0, xhrCallbacks; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties (function( xhr ) { jQuery.extend( jQuery.support, { ajax: !!xhr, cors: !!xhr && ( "withCredentials" in xhr ) }); })( jQuery.ajaxSettings.xhr() ); // Create transport if the browser can provide an xhr if ( jQuery.support.ajax ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var xhr = s.xhr(), handle, i; // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( _ ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responseHeaders, responses, xml; // Firefox throws exceptions when accessing properties // of an xhr when a network error occured // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) try { responses.text = xhr.responseText; } catch( _ ) { } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; // if we're in sync mode or it's in cache // and has been retrieved directly (IE6 & IE7) // we need to manually fire the callback if ( !s.async || xhr.readyState === 4 ) { callback(); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback(0,1); } } }; } }); } var elemdisplay = {}, iframe, iframeDoc, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i, timerId, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ], fxNow; jQuery.fn.extend({ show: function( speed, easing, callback ) { var elem, display; if ( speed || speed === 0 ) { return this.animate( genFx("show", 3), speed, easing, callback ); } else { for ( var i = 0, j = this.length; i < j; i++ ) { elem = this[ i ]; if ( elem.style ) { display = elem.style.display; // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !jQuery._data(elem, "olddisplay") && display === "none" ) { display = elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( (display === "" && jQuery.css(elem, "display") === "none") || !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { elem = this[ i ]; if ( elem.style ) { display = elem.style.display; if ( display === "" || display === "none" ) { elem.style.display = jQuery._data( elem, "olddisplay" ) || ""; } } } return this; } }, hide: function( speed, easing, callback ) { if ( speed || speed === 0 ) { return this.animate( genFx("hide", 3), speed, easing, callback); } else { var elem, display, i = 0, j = this.length; for ( ; i < j; i++ ) { elem = this[i]; if ( elem.style ) { display = jQuery.css( elem, "display" ); if ( display !== "none" && !jQuery._data( elem, "olddisplay" ) ) { jQuery._data( elem, "olddisplay", display ); } } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { if ( this[i].style ) { this[i].style.display = "none"; } } return this; } }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2, callback ) { 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, callback); } return this; }, fadeTo: function( speed, to, easing, callback ) { return this.filter(":hidden").css("opacity", 0).show().end() .animate({opacity: to}, speed, easing, callback); }, animate: function( prop, speed, easing, callback ) { var optall = jQuery.speed( speed, easing, callback ); if ( jQuery.isEmptyObject( prop ) ) { return this.each( optall.complete, [ false ] ); } // Do not change referenced properties as per-property easing will be lost prop = jQuery.extend( {}, prop ); function doAnimation() { // XXX 'this' does not always have a nodeName when running the // test suite if ( optall.queue === false ) { jQuery._mark( this ); } var opt = jQuery.extend( {}, optall ), isElement = this.nodeType === 1, hidden = isElement && jQuery(this).is(":hidden"), name, val, p, e, hooks, replace, parts, start, end, unit, method; // will store per property easing and be used to determine when an animation is complete opt.animatedProperties = {}; // first pass over propertys to expand / normalize for ( p in prop ) { name = jQuery.camelCase( p ); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; } if ( ( hooks = jQuery.cssHooks[ name ] ) && "expand" in hooks ) { replace = hooks.expand( prop[ name ] ); delete prop[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'p' from above because we have the correct "name" for ( p in replace ) { if ( ! ( p in prop ) ) { prop[ p ] = replace[ p ]; } } } } for ( name in prop ) { val = prop[ name ]; // easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default) if ( jQuery.isArray( val ) ) { opt.animatedProperties[ name ] = val[ 1 ]; val = prop[ name ] = val[ 0 ]; } else { opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing'; } if ( val === "hide" && hidden || val === "show" && !hidden ) { return opt.complete.call( this ); } if ( isElement && ( name === "height" || name === "width" ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( this, "display" ) === "inline" && jQuery.css( this, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || defaultDisplay( this.nodeName ) === "inline" ) { this.style.display = "inline-block"; } else { this.style.zoom = 1; } } } } if ( opt.overflow != null ) { this.style.overflow = "hidden"; } for ( p in prop ) { e = new jQuery.fx( this, opt, p ); val = prop[ p ]; if ( rfxtypes.test( val ) ) { // Tracks whether to show or hide based on private // data attached to the element method = jQuery._data( this, "toggle" + p ) || ( val === "toggle" ? hidden ? "show" : "hide" : 0 ); if ( method ) { jQuery._data( this, "toggle" + p, method === "show" ? "hide" : "show" ); e[ method ](); } else { e[ val ](); } } else { parts = rfxnum.exec( val ); start = e.cur(); if ( parts ) { end = parseFloat( parts[2] ); unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" ) { jQuery.style( this, p, (end || 1) + unit); start = ( (end || 1) / e.cur() ) * start; jQuery.style( this, p, 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; } return optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var index, hadTimers = false, timers = jQuery.timers, data = jQuery._data( this ); // clear marker counters if we know they won't be if ( !gotoEnd ) { jQuery._unmark( true, this ); } function stopQueue( elem, data, index ) { var hooks = data[ index ]; jQuery.removeData( elem, index, true ); hooks.stop( gotoEnd ); } if ( type == null ) { for ( index in data ) { if ( data[ index ] && data[ index ].stop && index.indexOf(".run") === index.length - 4 ) { stopQueue( this, data, index ); } } } else if ( data[ index = type + ".run" ] && data[ index ].stop ){ stopQueue( this, data, index ); } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { if ( gotoEnd ) { // force the next step to be the last timers[ index ]( true ); } else { timers[ index ].saveState(); } hadTimers = true; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( !( gotoEnd && hadTimers ) ) { jQuery.dequeue( this, type ); } }); } }); // Animations created synchronously will run synchronously function createFxNow() { setTimeout( clearFxNow, 0 ); return ( fxNow = jQuery.now() ); } function clearFxNow() { fxNow = undefined; } // Generate parameters to create a standard animation function genFx( type, num ) { var obj = {}; jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice( 0, num )), function() { obj[ this ] = type; }); return obj; } // 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" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.extend({ speed: function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, 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 : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function( noUnmark ) { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } else if ( noUnmark !== false ) { jQuery._unmark( this ); } }; return opt; }, easing: { linear: function( p ) { return p; }, swing: function( p ) { return ( -Math.cos( p*Math.PI ) / 2 ) + 0.5; } }, timers: [], fx: function( elem, options, prop ) { this.options = options; this.elem = elem; this.prop = prop; 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 ); }, // Get the current size cur: function() { if ( this.elem[ this.prop ] != null && (!this.elem.style || this.elem.style[ this.prop ] == null) ) { return this.elem[ this.prop ]; } var parsed, r = jQuery.css( this.elem, this.prop ); // Empty strings, null, undefined and "auto" are converted to 0, // complex values such as "rotate(1rad)" are returned as is, // simple values such as "10px" are parsed to Float. return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed; }, // Start an animation from one number to another custom: function( from, to, unit ) { var self = this, fx = jQuery.fx; this.startTime = fxNow || createFxNow(); this.end = to; this.now = this.start = from; this.pos = this.state = 0; this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" ); function t( gotoEnd ) { return self.step( gotoEnd ); } t.queue = this.options.queue; t.elem = this.elem; t.saveState = function() { if ( jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) { if ( self.options.hide ) { jQuery._data( self.elem, "fxshow" + self.prop, self.start ); } else if ( self.options.show ) { jQuery._data( self.elem, "fxshow" + self.prop, self.end ); } } }; if ( t() && jQuery.timers.push(t) && !timerId ) { timerId = setInterval( fx.tick, fx.interval ); } }, // Simple 'show' function show: function() { var dataShow = jQuery._data( this.elem, "fxshow" + this.prop ); // Remember where we started, so that we can go back to it later this.options.orig[ this.prop ] = dataShow || 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 if ( dataShow !== undefined ) { // This show is picking up where a previous hide or show left off this.custom( this.cur(), dataShow ); } else { 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._data( this.elem, "fxshow" + 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 p, n, complete, t = fxNow || createFxNow(), done = true, elem = this.elem, options = this.options; if ( gotoEnd || t >= options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); options.animatedProperties[ this.prop ] = true; for ( p in options.animatedProperties ) { if ( options.animatedProperties[ p ] !== true ) { done = false; } } if ( done ) { // Reset the overflow if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) { jQuery.each( [ "", "X", "Y" ], function( index, value ) { elem.style[ "overflow" + value ] = options.overflow[ index ]; }); } // Hide the element if the "hide" operation was done if ( options.hide ) { jQuery( elem ).hide(); } // Reset the properties, if the item has been hidden or shown if ( options.hide || options.show ) { for ( p in options.animatedProperties ) { jQuery.style( elem, p, options.orig[ p ] ); jQuery.removeData( elem, "fxshow" + p, true ); // Toggle data is no longer needed jQuery.removeData( elem, "toggle" + p, true ); } } // Execute the complete function // in the event that the complete function throws an exception // we must ensure it won't be called twice. #5684 complete = options.complete; if ( complete ) { options.complete = false; complete.call( elem ); } } return false; } else { // classical easing cannot be used with an Infinity duration if ( options.duration == Infinity ) { this.now = t; } else { n = t - this.startTime; this.state = n / options.duration; // Perform the easing function, defaults to swing this.pos = jQuery.easing[ options.animatedProperties[this.prop] ]( this.state, n, 0, 1, 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 timer, timers = jQuery.timers, i = 0; for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } }, interval: 13, 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.now + fx.unit; } else { fx.elem[ fx.prop ] = fx.now; } } } }); // Ensure props that can't be negative don't go there on undershoot easing jQuery.each( fxAttrs.concat.apply( [], fxAttrs ), function( i, prop ) { // exclude marginTop, marginLeft, marginBottom and marginRight from this list if ( prop.indexOf( "margin" ) ) { jQuery.fx.step[ prop ] = function( fx ) { jQuery.style( fx.elem, prop, Math.max(0, fx.now) + fx.unit ); }; } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } // Try to restore the default display value of an element function defaultDisplay( nodeName ) { if ( !elemdisplay[ nodeName ] ) { var body = document.body, elem = jQuery( "<" + nodeName + ">" ).appendTo( body ), display = elem.css( "display" ); elem.remove(); // If the simple way fails, // get element's real default display by attaching it to a temp iframe if ( display === "none" || display === "" ) { // No iframe to use yet, so create it if ( !iframe ) { iframe = document.createElement( "iframe" ); iframe.frameBorder = iframe.width = iframe.height = 0; } body.appendChild( iframe ); // Create a cacheable copy of the iframe document on first call. // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML // document to it; WebKit & Firefox won't allow reusing the iframe document. if ( !iframeDoc || !iframe.createElement ) { iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; iframeDoc.write( ( jQuery.support.boxModel ? "<!doctype html>" : "" ) + "<html><body>" ); iframeDoc.close(); } elem = iframeDoc.createElement( nodeName ); iframeDoc.body.appendChild( elem ); display = jQuery.css( elem, "display" ); body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; } return elemdisplay[ nodeName ]; } var getOffset, rtable = /^t(?:able|d|h)$/i, rroot = /^(?:body|html)$/i; if ( "getBoundingClientRect" in document.documentElement ) { getOffset = function( elem, doc, docElem, box ) { try { box = elem.getBoundingClientRect(); } catch(e) {} // Make sure we're not dealing with a disconnected DOM node if ( !box || !jQuery.contains( docElem, elem ) ) { return box ? { top: box.top, left: box.left } : { top: 0, left: 0 }; } var body = doc.body, win = getWindow( doc ), clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop, scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft, top = box.top + scrollTop - clientTop, left = box.left + scrollLeft - clientLeft; return { top: top, left: left }; }; } else { getOffset = function( elem, doc, docElem ) { var computedStyle, offsetParent = elem.offsetParent, prevOffsetParent = elem, 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.support.fixedPosition && 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.support.doesNotAddBorder && !(jQuery.support.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevOffsetParent = offsetParent; offsetParent = elem.offsetParent; } if ( jQuery.support.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.support.fixedPosition && prevComputedStyle.position === "fixed" ) { top += Math.max( docElem.scrollTop, body.scrollTop ); left += Math.max( docElem.scrollLeft, body.scrollLeft ); } return { top: top, left: left }; }; } jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var elem = this[0], doc = elem && elem.ownerDocument; if ( !doc ) { return null; } if ( elem === doc.body ) { return jQuery.offset.bodyOffset( elem ); } return getOffset( elem, doc, doc.documentElement ); }; jQuery.offset = { bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.css(body, "marginTop") ) || 0; left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.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 = rroot.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.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 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 && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { var clientProp = "client" + name, scrollProp = "scroll" + name, offsetProp = "offset" + name; // innerHeight and innerWidth jQuery.fn[ "inner" + name ] = function() { var elem = this[0]; return elem ? elem.style ? parseFloat( jQuery.css( elem, type, "padding" ) ) : this[ type ]() : null; }; // outerHeight and outerWidth jQuery.fn[ "outer" + name ] = function( margin ) { var elem = this[0]; return elem ? elem.style ? parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) : this[ type ]() : null; }; jQuery.fn[ type ] = function( value ) { return jQuery.access( this, function( elem, type, value ) { var doc, docElemProp, orig, ret; if ( jQuery.isWindow( elem ) ) { // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat doc = elem.document; docElemProp = doc.documentElement[ clientProp ]; return jQuery.support.boxModel && docElemProp || doc.body && doc.body[ clientProp ] || docElemProp; } // Get document width or height if ( elem.nodeType === 9 ) { // Either scroll[Width/Height] or offset[Width/Height], whichever is greater doc = elem.documentElement; // when a window > document, IE6 reports a offset[Width/Height] > client[Width/Height] // so we can't use max, as it'll choose the incorrect offset[Width/Height] // instead we use the correct client[Width/Height] // support:IE6 if ( doc[ clientProp ] >= doc[ scrollProp ] ) { return doc[ clientProp ]; } return Math.max( elem.body[ scrollProp ], doc[ scrollProp ], elem.body[ offsetProp ], doc[ offsetProp ] ); } // Get width or height on the element if ( value === undefined ) { orig = jQuery.css( elem, type ); ret = parseFloat( orig ); return jQuery.isNumeric( ret ) ? ret : orig; } // Set the width or height on the element jQuery( elem ).css( type, value ); }, type, value, arguments.length, null ); }; }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use a proper concatenation script that understands anonymous // AMD modules. A named AMD is safest and most robust way to register. // Lowercase jquery is used because AMD module names are derived from // file names, and jQuery is normally delivered in a lowercase file name. // Do this after creating the global so that if an AMD module wants to call // noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window );
var default_cost_duration = 'hourly'; var default_region = 'us-east-1'; var default_reserved_term = 'yrTerm1.noUpfront'; var current_cost_duration = default_cost_duration; var current_region = default_region; var current_reserved_term = default_reserved_term; var data_table = null; var require = Array(); require['memory'] = 0; require['computeunits'] = 0; require['storage'] = 0; function init_data_table() { data_table = $('#data').DataTable({ "bPaginate": false, "bInfo": false, "bStateSave": true, "oSearch": { "bRegex" : true, "bSmart": false }, "aoColumnDefs": [ { "aTargets": ["memory", "computeunits", "cores", "coreunits", "storage", "ebs-throughput", "ebs-iops", "networkperf", "max_bandwidth"], "sType": "span-sort" }, { "aTargets": ["ecu-per-core", "enhanced-networking", "maxips", "linux-virtualization", "cost-ondemand-mswinSQLWeb", "cost-ondemand-mswinSQL", "cost-reserved-mswinSQLWeb", "cost-reserved-mswinSQL", "ebs-throughput", "ebs-iops", "max_bandwidth"], "bVisible": false } ], // default sort by linux cost "aaSorting": [ [ 14, "asc" ] ], 'initComplete': function() { // fire event in separate context so that calls to get_data_table() // receive the cached object. setTimeout(function() { on_data_table_initialized(); }, 0); }, 'drawCallback': function() { // abort if initialization hasn't finished yet (initial draw) if (data_table === null) { return; } // Whenever the table is drawn, update the costs. This is necessary // because the cost duration may have changed while a filter was being // used and so some rows will need updating. redraw_costs(); } }); return data_table; } $(document).ready(function() { init_data_table(); }); function change_cost(duration) { // update menu text var first = duration.charAt(0).toUpperCase(); var text = first + duration.substr(1); $("#cost-dropdown .dropdown-toggle .text").text(text); // update selected menu option $('#cost-dropdown li a').each(function(i, e) { e = $(e); if (e.attr('duration') == duration) { e.parent().addClass('active'); } else { e.parent().removeClass('active'); } }); var hour_multipliers = { "hourly": 1, "daily": 24, "weekly": (7*24), "monthly": (30*24), "annually": (365*24) }; var multiplier = hour_multipliers[duration]; var per_time; $.each($("td.cost-ondemand"), function(i, elem) { elem = $(elem); per_time = elem.data("pricing")[current_region]; if (per_time && !isNaN(per_time)) { per_time = (per_time * multiplier).toFixed(3); elem.text("$" + per_time + " " + duration); } else { elem.text("unavailable"); } }); $.each($("td.cost-reserved"), function(i, elem) { elem = $(elem); per_time = elem.data("pricing")[current_region]; if(!per_time) { elem.text("unavailable"); return; } per_time = per_time[current_reserved_term]; if (per_time && !isNaN(per_time)) { per_time = (per_time * multiplier).toFixed(3); elem.text("$" + per_time + " " + duration); } else { elem.text("unavailable"); } }); current_cost_duration = duration; maybe_update_url(); } function change_region(region) { current_region = region; var region_name = null; $('#region-dropdown li a').each(function(i, e) { e = $(e); if (e.data('region') === region) { e.parent().addClass('active'); region_name = e.text(); } else { e.parent().removeClass('active'); } }); $("#region-dropdown .dropdown-toggle .text").text(region_name); change_cost(current_cost_duration); } function change_reserved_term(term) { current_reserved_term = term; var $dropdown = $('#reserved-term-dropdown'), $activeLink = $dropdown.find('li a[data-reserved-term="'+term+'"]'), term_name = $activeLink.text(); $dropdown.find('li').removeClass('active'); $activeLink.closest('li').addClass('active'); $dropdown.find('.dropdown-toggle .text').text(term_name); change_cost(current_cost_duration); } // Update all visible costs to the current duration. // Called after new columns or rows are shown as their costs may be inaccurate. function redraw_costs() { change_cost(current_cost_duration); } function setup_column_toggle() { $.each(data_table.columns().indexes(), function(i, idx) { var column = data_table.column(idx); $("#filter-dropdown ul").append( $('<li>') .toggleClass('active', column.visible()) .append( $('<a>', {href: "javascript:;"}) .text($(column.header()).text()) .click(function(e) { toggle_column(i); $(this).parent().toggleClass("active"); $(this).blur(); // prevent focus style from sticking in Firefox e.stopPropagation(); // keep dropdown menu open }) ) ); }); } function url_for_selections() { var settings = { min_memory: require['memory'], min_computeunits: require['computeunits'], min_storage: require['storage'], filter: data_table.settings()[0].oPreviousSearch['sSearch'], region: current_region, cost: current_cost_duration, term: current_reserved_term }; if (settings.min_memory == '') delete settings.min_memory; if (settings.min_computeunits == '') delete settings.min_computeunits; if (settings.min_storage == '') delete settings.min_storage; if (settings.filter == '') delete settings.filter if (settings.region == default_region) delete settings.region; if (settings.cost == default_cost_duration) delete settings.cost; if (settings.term == default_reserved_term) delete settings.term; // selected rows var selected_row_ids = $('#data tbody tr.highlight').map(function() { return this.id; }).get(); if (selected_row_ids.length > 0) { settings.selected = selected_row_ids; } var url = location.origin + location.pathname; var parameters = []; for (var setting in settings) { if (settings[setting] !== undefined) { parameters.push(setting + '=' + settings[setting]); } } if (parameters.length > 0) url = url + '?' + parameters.join('&'); return url; } function maybe_update_url() { if (!history.replaceState) { return; } try { var url = url_for_selections(); if (document.location == url) { return; } history.replaceState(null, '', url); } catch(ex) { // doesn't matter } } var apply_min_values = function() { var all_filters = $('[data-action="datafilter"]'); var data_rows = $('#data tr:has(td)'); data_rows.show(); all_filters.each(function() { var filter_on = $(this).data('type'); var filter_val = parseFloat($(this).val()) || 0; // update global variable for dynamic URL require[filter_on] = filter_val; var match_fail = data_rows.filter(function() { var row_val; row_val = parseFloat( $(this).find('td[class~="' + filter_on + '"] span').attr('sort') ); return row_val < filter_val; }); match_fail.hide(); }); maybe_update_url(); }; function on_data_table_initialized() { // process URL settings var url_settings = get_url_parameters(); for (var key in url_settings) { switch(key) { case 'region': current_region = url_settings['region']; break; case 'cost': current_cost_duration = url_settings['cost']; break; case 'term': current_reserved_term = url_settings['term']; break; case 'filter': data_table.filter(url_settings['filter']); break; case 'min_memory': $('[data-action="datafilter"][data-type="memory"]').val(url_settings['min_memory']); apply_min_values(); break; case 'min_computeunits': $('[data-action="datafilter"][data-type="computeunits"]').val(url_settings['min_computeunits']); apply_min_values(); break; case 'min_storage': $('[data-action="datafilter"][data-type="storage"]').val(url_settings['min_storage']); apply_min_values(); break; case 'selected': // apply highlight to selected rows $.each(url_settings['selected'].split(','), function(_, id) { id = id.replace('.', '\\.'); $('#'+id).addClass('highlight'); }) break; } } configure_highlighting(); // Allow row filtering by min-value match. $('[data-action=datafilter]').on('keyup', apply_min_values); change_region(current_region); change_cost(current_cost_duration); change_reserved_term(current_reserved_term); $.extend($.fn.dataTableExt.oStdClasses, { "sWrapper": "dataTables_wrapper form-inline" }); setup_column_toggle(); // enable bootstrap tooltips $('abbr').tooltip({ placement: function(tt, el) { return (this.$element.parents('thead').length) ? 'top' : 'right'; } }); $("#cost-dropdown li").bind("click", function(e) { change_cost(e.target.getAttribute("duration")); }); $("#region-dropdown li").bind("click", function(e) { change_region($(e.target).data('region')); }); $("#reserved-term-dropdown li").bind("click", function(e) { change_reserved_term($(e.target).data('reservedTerm')); }); // apply classes to search box $('div.dataTables_filter input').addClass('form-control search'); } // sorting for colums with more complex data // http://datatables.net/plug-ins/sorting#hidden_title jQuery.extend(jQuery.fn.dataTableExt.oSort, { "span-sort-pre": function(elem) { var matches = elem.match(/sort="(.*?)"/); if (matches) { return parseInt(matches[1], 10); } return 0; }, "span-sort-asc": function(a, b) { return ((a < b) ? -1 : ((a > b) ? 1 : 0)); }, "span-sort-desc": function(a, b) { return ((a < b) ? 1 : ((a > b) ? -1 : 0)); } }); // toggle columns function toggle_column(col_index) { var is_visible = data_table.column(col_index).visible(); data_table.column(col_index).visible(is_visible ? false : true); redraw_costs(); } // retrieve all the parameters from the location string function get_url_parameters() { var params = location.search.slice(1).split('&'); var settings = {}; params.forEach(function(param) { settings[param.split('=')[0]] = param.split('=')[1]; }); return settings; } function configure_highlighting() { var compareOn = false, $compareBtn = $('.btn-compare'), $rows = $('#data tbody tr'); // Allow row highlighting by clicking. $rows.click(function() { $(this).toggleClass('highlight'); if (!compareOn) { $compareBtn.prop('disabled', !$rows.is('.highlight')); } maybe_update_url(); }); $compareBtn.prop('disabled', !$($rows).is('.highlight')); $compareBtn.text($compareBtn.data('textOff')); $compareBtn.click(function() { if (compareOn) { $rows.show(); $compareBtn.text($compareBtn.data('textOff')) .addClass('btn-primary') .removeClass('btn-success') .prop('disabled', !$rows.is('.highlight')); } else { $rows.filter(':not(.highlight)').hide(); $compareBtn.text($compareBtn.data('textOn')) .addClass('btn-success') .removeClass('btn-primary'); } compareOn = !compareOn; }); }
import defaultsDeep from 'lodash/fp/defaultsDeep'; /** * 解析 URL 中的参数为 JSON * @param {[type]} searchString [description] * @return {[type]} [description] */ export function searchToObject(search) { return search.substring(1).split("&").reduce(function(result, value) { var parts = value.split('='); if (parts[0]) result[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]); return result; }, {}) } /** * 对请求的接口数据进行 data 取值处理(暂时不建议使用,已在ajax API 中封装) * @param {[type]} response [返回数据] * @param {[type]} errormessage [自定义错误信息] * @param {[type]} successmessage [自定义成功信息] * @return {[type]} [description] */ export function lintData(response,errormessage,successmessage) { if(!response) return; let flag = response.flag; if(flag != 0) { summer.toast({msg:response.msg || errormessage}); //优先显示后台返回的错误信息 } if(successmessage) { summer.toast({msg:successmessage}); } return response; } /** * 基于 UA 判断设备情况 * @return {[type]} [description] */ export function browserRedirect() { var browser={ info:function(){ var ua = navigator.userAgent, app = navigator.appVersion; return { //移动终端浏览器版本信息 //trident: ua.indexOf('Trident') > -1, //IE内核 //presto: ua.indexOf('Presto') > -1, //opera内核 webKit: ua.indexOf('AppleWebKit') > -1, //苹果、谷歌内核 //gecko: ua.indexOf('Gecko') > -1 && ua.indexOf('KHTML') == -1, //火狐内核 mobile: !!ua.match(/AppleWebKit.*Mobile.*/), //是否为移动终端 ios: !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端 android: ua.indexOf('Android') > -1 || ua.indexOf('Linux') > -1, //android终端或uc浏览器 iPhone: ua.indexOf('iPhone') > -1 , //是否为iPhone或者QQHD浏览器 iPad: ua.indexOf('iPad') > -1, //是否iPad //webApp: ua.indexOf('Safari') == -1 //是否web应该程序,没有头部与底部 platform: navigator.platform }; }(), lang:(navigator.browserLanguage || navigator.language).toLowerCase() }; if(browser.info.platform.toLowerCase().indexOf("win")>= 0 || browser.info.platform.toLowerCase().indexOf("mac")>= 0){ return "pc"; }else if(browser.info.android){ return "android"; }else if(browser.info.ios || browser.info.iPhone || browser.info.iPad){ return "ios"; }else{ return ""; } } export function getQueryString (name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var r = window.location.search.substr(1).match(reg); if (r != null) return unescape(r[2]); return null; } /** * 对请求的接口数据进行 data 取值处理(暂时不建议使用,已在ajax API 中封装) * @param {[type]} response [返回数据] * @param {[type]} errormessage [自定义错误信息] * @param {[type]} successmessage [自定义成功信息] * @return {[type]} [description] */ /** 用法:仅仅修改头部名字 * param = { actionBar: { title: "兑换中心",//标题 } }*/ export function summerHeader(param){ let defaultParam = { id: "guidaaaefasfdzf",//页面id url: "html/main.html",//页面路径 create: "false", type: "actionBar", actionBar: { title: "我是测试",//标题 titleColor: "#333333",//标题颜色 backgroundColor: "#ffffff",//头部背景色 leftItem:{ image: "static/img/go_back.png",//头部左边 text: "返回", textColor: "#333333", method:""//执行的回调,不传默认为closeWin }, rightItems:[ {//右侧部分,可以传递一个数组 type:"text", text: "完成", textColor: "#333333", method: "aaaa2()"//点击回调的方法 }, { type:"image", image: "img/speech.png", method: "aaaa1()"//点击回调的方法 }] }, isKeep: true, animation: { duration: 0 } } let newParam = defaultsDeep(defaultParam,param); if (param.actionBar.rightItems) { newParam.actionBar.rightItems = param.actionBar.rightItems }else { delete newParam.actionBar.rightItems } summer.openWin(newParam); } /* * CircleType 0.36 * Peter Hrynkow * Copyright 2014, Licensed GPL & MIT * */ /** options = { tagName:"demo", // 目标元素的类名 radius:60 // 圆半径 dir: 1, // 文字环绕方向[1,-1] position: 'relative', fitText: false, //自适应屏幕 fontSizeUnit:'px', //自适应屏幕字体单位 kompressor:1, //自适应缩放比 fontSize: 20 //默认文字大小 } */ export function circleType(options) { function injector(name,t='', splitter='', klass='char', after='') { if(t=='') return; var text = name , a = text.split(splitter) , inject = ''; if (a.length) { a.map(function(item, i) { inject += '<span class="'+klass+(i+1)+'" aria-hidden="true">'+item+'</span>'+after; }); t.setAttribute("aria-label",text); t.textContent = ""; t.innerHTML = inject; } } function fitText(options) { let target = document.getElementsByClassName(options.tagName)[0]; debugger; // Setup options var compressor = options.kompressor || 1, settings = defaultsDeep({ 'minFontSize' : Number.NEGATIVE_INFINITY, 'maxFontSize' : Number.POSITIVE_INFINITY }, options); target.style.fontSize = Math.max(Math.min(target.clientWidth / (compressor*10), parseFloat(settings.maxFontSize)), parseFloat(settings.minFontSize)) + options.fontSizeUnit; window.onresize =function(){ target.style.fontSize = Math.max(Math.min(target.clientWidth / (compressor*10), parseFloat(settings.maxFontSize)), parseFloat(settings.minFontSize)) + options.fontSizeUnit; } }; if(!options.tagName) return; var target = document.getElementsByClassName(options.tagName)[0]; var self = this, settings = { dir: 1, position: 'relative', fitText: false, fontSizeUnit:'px', kompressor:1, fontSize: 20 }; function init(options) { if (options) { settings = defaultsDeep(settings, options); } let elem = target, delta = (180 / Math.PI), fs = parseInt(target.style.fontSize || settings.fontSize, 10), ch = parseInt(target.style.lineHeight, 10) || fs, txt = elem.innerHTML.replace(/^\s+|\s+$/g, '').replace(/\s/g, '&nbsp;'), letters, center; elem.innerHTML = txt; //$(elem).lettering(); injector(settings.name,target); elem.style.position = settings.position; letters = elem.getElementsByTagName('span'); center = Math.floor(letters.length / 2) let layout = function () { let tw = 0, i, offset = 0, minRadius, origin, innerRadius, l, style, r, transform; for (i = 0; i < letters.length; i++) { tw += letters[i].offsetWidth; } minRadius = (tw / Math.PI) / 2 + ch; if (settings.fluid && !settings.fitText) { settings.radius = Math.max(elem.offsetWidth / 2, minRadius); } else if (!settings.radius) { settings.radius = minRadius; } if (settings.dir === -1) { origin = 'center ' + (-settings.radius + ch) / fs + 'em'; } else { origin = 'center ' + settings.radius / fs + 'em'; } innerRadius = settings.radius - ch; for (i = 0; i < letters.length; i++) { l = letters[i]; offset += l.offsetWidth / 2 / innerRadius * delta; l.rot = offset; offset += l.offsetWidth / 2 / innerRadius * delta; } for (i = 0; i < letters.length; i++) { l = letters[i]; style = l.style; if(false) { // $summer.os == "android" r = (-offset*2 * settings.dir / 2) + l.rot*2 * settings.dir; }else { r = (-offset * settings.dir / 2) + l.rot * settings.dir; } transform = 'rotate(' + r + 'deg)'; style.position = 'absolute'; style.left = '50%'; style.marginLeft = -(l.offsetWidth / 2) / fs + 'em'; style.webkitTransform = transform; style.MozTransform = transform; style.OTransform = transform; style.msTransform = transform; style.transform = transform; style.webkitTransformOrigin = origin; style.MozTransformOrigin = origin; style.OTransformOrigin = origin; style.msTransformOrigin = origin; style.transformOrigin = origin; if(settings.dir === -1) { style.bottom = 0; } } if (settings.fitText) { fitText(settings); window.onresize = function() { updateHeight(); } } updateHeight(); if (typeof settings.callback === 'function') { // Execute our callback with the element we transformed as `this` settings.callback.apply(elem); } }; var getBounds = function (elem) { var docElem = document.documentElement, box = elem.getBoundingClientRect(); return { top: box.top + window.pageYOffset - docElem.clientTop, left: box.left + window.pageXOffset - docElem.clientLeft, height: box.height }; }; var updateHeight = function () { var mid = getBounds(letters[center]), first = getBounds(letters[0]), h; if (mid.top < first.top) { h = first.top - mid.top + first.height; } else { h = mid.top - first.top + first.height; } elem.style.height = h + 'px'; } if (settings.fluid && !settings.fitText) { window.onresize = function() { layout(); } } if (document.readyState !== "complete") { elem.style.visibility = 'hidden'; window.onload = function() { elem.style.visibility = 'visible'; layout(); } } else { layout(); } }; init(options) }; export function generateQRCode(code,type,imgId){ let param={ type:type, data:code } param=JSON.stringify(param) var codeImg = summer.generateQRCode({ size : 240,//二维码正方形的宽高 content : param//生成二维码所需的源文字 string类型 }); var MyCode = $summer.byId(imgId); $summer.attr(MyCode,"src",codeImg); } export const customStyles = { overlay : { position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, height: 4000, backgroundColor : 'rgba(0, 0, 0, 0.65)', }, content : { position: 'absolute', border: '1px solid #eee', height: '2.6rem', width: '5rem', background: '#fff', overflow : 'auto', WebkitOverflowScrolling : 'touch', borderRadius : '4px', outline : 'none', padding : '0.5rem 0.2rem 0.4rem .2rem ', textAlign:'center' } }; export const shareCustomStyles = { overlay: { position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, height: '100%', backgroundColor: 'rgba(0, 0, 0, 0.65)', }, content: { position: 'absolute', border: '1px solid #eee', width: '100%', background: '#fff', overflow: 'auto', WebkitOverflowScrolling: 'touch', outline: 'none', padding: '.2rem 0 0 0', textAlign: 'center', left: 0, bottom: 0 } }