code
stringlengths 2
1.05M
| repo_name
stringlengths 5
114
| path
stringlengths 4
991
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
---|---|---|---|---|---|
var archiver = require('archiver'),
async = require('async'),
escape = require('handlebars').Utils.escapeExpression,
fs = require('fs'),
glob = require('glob'),
path = require('path'),
yui = require('yui');
var config = require('../config'),
hbs = require('./hbs');
exports.archive = archiveLayout;
exports.clone = cloneLayouts;
exports.find = findLayout;
exports.load = loadLayouts;
// -----------------------------------------------------------------------------
var DIR_PATH = path.join(config.dirs.views, 'layouts', 'examples'),
LICENSE = fs.readFileSync(path.join(process.cwd(), 'LICENSE.md')),
README = fs.readFileSync(path.join(DIR_PATH, 'README.md')),
cache = null,
pending = null;
function archiveLayout(layout) {
if (!layout) { return null; }
var archive = archiver('zip');
archive.append(LICENSE, {name: 'LICENSE.md'});
archive.append(README, {name: 'README.md'});
archive.append(layout.html, {name: 'index.html'});
// Layout resources.
['css', 'js', 'imgs'].forEach(function (type) {
layout[type].forEach(function (file) {
archive.append(file.data, {name: file.filename});
});
});
return archive.finalize();
}
function cloneLayouts(layouts, options) {
layouts = clone(layouts);
options || (options = {});
layouts.forEach(function (layout) {
// Convert imgs back into Buffers.
layout.imgs.forEach(function (img) {
img.data = new Buffer(img.data);
});
if (options.escape) {
layout.description = escape(layout.description);
layout.html = escape(layout.html);
['css', 'js'].forEach(function (type) {
layout[type].forEach(function (file) {
file.data = escape(file.data);
});
});
}
});
return layouts;
}
function findLayout(layouts, name) {
var layout = null;
layouts.some(function (l) {
if (l.name === name) {
layout = l;
return true;
}
});
return layout;
}
/*
This provides metadata about the layout examples. If the `cache` option is set,
then the hard work is only performed once. A copy of the layouts metadata is
returned to the caller via the `callback`, therefore they are free to mute the
data and it won't affect any other caller.
*/
function loadLayouts(options, callback) {
// Options are optional.
if (typeof options === 'function') {
callback = options;
options = null;
}
options || (options = {});
// Check cache.
if (options.cache && cache) {
// Return clone of the cache.
callback(null, cloneLayouts(cache, options));
return;
}
// Put caller on the queue if the hard work of compiling the layouts
// metadata is currently in progress for another caller.
if (pending) {
pending.push(callback);
return;
}
pending = [callback];
// Run the show!
// 1) Glob the layout examples dir to get a list of filenames.
//
// 2) Create the metadata for the layout examples:
// a) Render each layout and capture its output *and* metadata set from
// within the template itself.
//
// b) Create a metadata object to represent the layout based on the
// data siphoned from the context object in which it was rendered.
//
// 3) Read the CSS, JS, and images associated with the layout example from
// the filesystem and capture it as part of the metadata.
//
// 4) Cache the result and call all queued calls with their own copy of the
// layout examples metadata.
async.waterfall([
glob.bind(null, '*' + hbs.extname, {cwd: DIR_PATH}),
createLayouts,
loadResources
], function (err, layouts) {
if (!err) { cache = layouts; }
while (pending.length) {
pending.shift().call(null, err, cloneLayouts(layouts, options));
}
pending = null;
});
}
// -- Utilities ----------------------------------------------------------------
function clone(obj) {
// Poor-man's clone.
return JSON.parse(JSON.stringify(obj));
}
function createLayouts(filenames, callback) {
// Default context values that mascarade as being the "app" and make the
// layout examples render in a particular way.
var contextProto = {
forDownload: true,
site : 'Pure',
section: 'Layout Examples',
pure: {
version: config.pure.version
},
yui_version: yui.YUI.version,
min: '-min',
layout : 'blank',
relativePath: '/',
helpers: {
pathTo: function () { return ''; }
}
};
function createLayout(filename, context, html, callback) {
var css = [];
// Include all `localCSS` files, including old IE versions.
(context.localCSS || []).forEach(function (entry) {
css.push(entry.path);
if (entry.oldIE) {
css.push(entry.oldIE);
}
});
callback(null, {
name : path.basename(filename, path.extname(filename)),
label : context.title,
description: context.subTitle,
tags : context.tags,
html: html,
css : css,
js : context.localJS || [],
imgs: context.localImgs || []
});
}
function renderTemplate(filename, callback) {
// Create a new context object that inherits from the defaults so when
// the template is rendered the own properties will be enumerable
// allowing us to sniff out the data added by the Handlebars helpers.
var context = Object.create(contextProto);
async.waterfall([
hbs.renderView.bind(hbs, path.join(DIR_PATH, filename), context),
createLayout.bind(null, filename, context)
], callback);
}
async.map(filenames, renderTemplate, callback);
}
function loadResources(layouts, callback) {
function processFile(type, filename, callback) {
fs.readFile(path.join(config.dirs.pub, filename), {
// Set the encoding for non-binary files.
encoding: type === 'imgs' ? null : 'utf8'
}, function (err, data) {
callback(err, {
name : path.basename(filename),
filename: filename,
data : data
});
});
}
function loadFiles(layout, type, callback) {
async.map(layout[type], processFile.bind(null, type), function (err, files) {
// Replace the list of filenames used by this layout with a
// collection of metadata for each file which includes its:
// name, filename, and contents.
layout[type] = files;
callback(err, files);
});
}
async.each(layouts, function (layout, callback) {
async.parallel([
loadFiles.bind(null, layout, 'css'),
loadFiles.bind(null, layout, 'js'),
loadFiles.bind(null, layout, 'imgs')
], callback);
}, function (err) {
callback(err, layouts);
});
}
| igorstefurak/pushcourse | lib/layouts.js | JavaScript | bsd-3-clause | 7,374 |
var searchData=
[
['native_5fhandle_5ftype_928',['native_handle_type',['../classpmem_1_1obj_1_1condition__variable.html#a5d6f2b49f88a03db9e9f3a2b49f6bf6d',1,'pmem::obj::condition_variable::native_handle_type()'],['../classpmem_1_1obj_1_1mutex.html#a746ecab28758da55f241b0f7b76ced36',1,'pmem::obj::mutex::native_handle_type()'],['../classpmem_1_1obj_1_1shared__mutex.html#ad4c7fd0b2addf9babd42dc3827585c87',1,'pmem::obj::shared_mutex::native_handle_type()'],['../classpmem_1_1obj_1_1timed__mutex.html#ac561c19b42016f409ae142395645f99b',1,'pmem::obj::timed_mutex::native_handle_type()']]]
];
| pbalcer/pbalcer.github.io | content/libpmemobj-cpp/master/doxygen/search/typedefs_7.js | JavaScript | bsd-3-clause | 592 |
import Immutable from "immutable";
import { remote } from "electron";
import { from } from "rxjs/observable/from";
import * as nativeWindow from "../../src/notebook/native-window";
import { makeAppRecord, makeDocumentRecord } from "@nteract/types/core/records";
const path = require("path");
describe("tildify", () => {
test("returns an empty string if given no path", () => {
expect(nativeWindow.tildify()).toBe("");
});
test("replaces the user directory with ~", () => {
const fixture = path.join(remote.app.getPath("home"), "test-notebooks");
const result = nativeWindow.tildify(fixture);
if (process.platform === "win32") {
expect(result).toBe(fixture);
} else {
expect(result).toContain("~");
}
});
});
describe("setTitleFromAttributes", () => {
test("sets the window title", () => {
// Set up our "Electron window"
const win = {
setRepresentedFilename: jest.fn(),
setDocumentEdited: jest.fn(),
setTitle: jest.fn()
};
remote.getCurrentWindow = jest.fn();
remote.getCurrentWindow.mockReturnValue(win);
const titleObject = {
fullpath: "/tmp/test.ipynb",
kernelStatus: "busy",
modified: true
};
nativeWindow.setTitleFromAttributes(titleObject);
expect(win.setTitle).toBeCalled();
});
});
describe("createTitleFeed", () => {
test("creates an observable that updates title attributes for modified notebook", done => {
const notebook = new Immutable.Map().setIn(
["metadata", "kernelspec", "display_name"],
"python3000"
);
const state = {
document: makeDocumentRecord({
notebook,
filename: "titled.ipynb"
}),
app: makeAppRecord({
kernelStatus: "not connected"
})
};
const state$ = from([state]);
const allAttributes = [];
nativeWindow.createTitleFeed(state$).subscribe(
attributes => {
allAttributes.push(attributes);
},
null,
() => {
expect(allAttributes).toEqual([
{
modified: process.platform === "darwin" ? true : false,
fullpath: "titled.ipynb",
kernelStatus: "not connected"
}
]);
done();
}
);
});
test("creates an observable that updates title attributes", done => {
const notebook = new Immutable.Map().setIn(
["metadata", "kernelspec", "display_name"],
"python3000"
);
const state = {
document: makeDocumentRecord({
notebook,
savedNotebook: notebook,
filename: "titled.ipynb"
}),
app: makeAppRecord({
kernelStatus: "not connected"
})
};
const state$ = from([state]);
const allAttributes = [];
nativeWindow.createTitleFeed(state$).subscribe(
attributes => {
allAttributes.push(attributes);
},
null,
() => {
expect(allAttributes).toEqual([
{
modified: false,
fullpath: "titled.ipynb",
kernelStatus: "not connected"
}
]);
done();
}
);
});
});
| captainsafia/nteract | applications/desktop/__tests__/renderer/native-window-spec.js | JavaScript | bsd-3-clause | 3,118 |
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule TouchEventUtils
*/
const TouchEventUtils = {
/**
* Utility function for common case of extracting out the primary touch from a
* touch event.
* - `touchEnd` events usually do not have the `touches` property.
* http://stackoverflow.com/questions/3666929/
* mobile-sarai-touchend-event-not-firing-when-last-touch-is-removed
*
* @param {Event} nativeEvent Native event that may or may not be a touch.
* @return {TouchesObject?} an object with pageX and pageY or null.
*/
extractSingleTouch: function(nativeEvent) {
const touches = nativeEvent.touches;
const changedTouches = nativeEvent.changedTouches;
const hasTouches = touches && touches.length > 0;
const hasChangedTouches = changedTouches && changedTouches.length > 0;
return !hasTouches && hasChangedTouches ? changedTouches[0] :
hasTouches ? touches[0] :
nativeEvent;
}
};
module.exports = TouchEventUtils;
| chicoxyzzy/fbjs | packages/fbjs/src/core/TouchEventUtils.js | JavaScript | bsd-3-clause | 1,271 |
/**
* Global adapter config
*
* The `adapters` configuration object lets you create different global "saved settings"
* that you can mix and match in your models. The `default` option indicates which
* "saved setting" should be used if a model doesn't have an adapter specified.
*
* Keep in mind that options you define directly in your model definitions
* will override these settings.
*
* For more information on adapter configuration, check out:
* http://sailsjs.org/#documentation
*/
module.exports.adapters = {
// If you leave the adapter config unspecified
// in a model definition, 'default' will be used.
'default': 'mongo',
// Persistent adapter for DEVELOPMENT ONLY
// (data is preserved when the server shuts down)
disk: {
module: 'sails-disk'
},
mongo: {
module: 'sails-mongo',
url: process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://localhost/joydb'
},
// MySQL is the world's most popular relational database.
// Learn more: http://en.wikipedia.org/wiki/MySQL
myLocalMySQLDatabase: {
module: 'sails-mysql',
host: 'YOUR_MYSQL_SERVER_HOSTNAME_OR_IP_ADDRESS',
user: 'YOUR_MYSQL_USER',
// Psst.. You can put your password in config/local.js instead
// so you don't inadvertently push it up if you're using version control
password: 'YOUR_MYSQL_PASSWORD',
database: 'YOUR_MYSQL_DB'
}
};
| gpedro/joy | config/adapters.js | JavaScript | bsd-3-clause | 1,463 |
(function ($) {
'use strict';
var dw, dh, rw, rh, lx, ly;
var defaults = {
// The text to display within the notice box while loading the zoom image.
loadingNotice: 'Loading image',
// The text to display within the notice box if an error occurs when loading the zoom image.
errorNotice: 'The image could not be loaded',
// The time (in milliseconds) to display the error notice.
errorDuration: 2500,
// Attribute to retrieve the zoom image URL from.
linkAttribute: 'href',
// Prevent clicks on the zoom image link.
preventClicks: true,
// Callback function to execute before the flyout is displayed.
beforeShow: $.noop,
// Callback function to execute before the flyout is removed.
beforeHide: $.noop,
// Callback function to execute when the flyout is displayed.
onShow: $.noop,
// Callback function to execute when the flyout is removed.
onHide: $.noop,
// Callback function to execute when the cursor is moved while over the image.
onMove: $.noop
};
/**
* EasyZoom
* @constructor
* @param {Object} target
* @param {Object} options (Optional)
*/
function EasyZoom(target, options) {
this.$target = $(target);
this.opts = $.extend({}, defaults, options, this.$target.data());
this.isOpen === undefined && this._init();
}
/**
* Init
* @private
*/
EasyZoom.prototype._init = function() {
this.$link = this.$target.find('a');
this.$image = this.$target.find('img');
this.$flyout = $('<div class="easyzoom-flyout" />');
this.$notice = $('<div class="easyzoom-notice" />');
this.$target.on({
'mousemove.easyzoom touchmove.easyzoom': $.proxy(this._onMove, this),
'mouseleave.easyzoom touchend.easyzoom': $.proxy(this._onLeave, this),
'mouseenter.easyzoom touchstart.easyzoom': $.proxy(this._onEnter, this)
});
this.opts.preventClicks && this.$target.on('click.easyzoom', function(e) {
e.preventDefault();
});
};
/**
* Show
* @param {MouseEvent|TouchEvent} e
* @param {Boolean} testMouseOver (Optional)
*/
EasyZoom.prototype.show = function(e, testMouseOver) {
var w1, h1, w2, h2;
var self = this;
if (this.opts.beforeShow.call(this) === false) return;
if (!this.isReady) {
return this._loadImage(this.$link.attr(this.opts.linkAttribute), function() {
if (self.isMouseOver || !testMouseOver) {
self.show(e);
}
});
}
this.$target.append(this.$flyout);
w1 = this.$target.width();
h1 = this.$target.height();
w2 = this.$flyout.width();
h2 = this.$flyout.height();
dw = this.$zoom.width() - w2;
dh = this.$zoom.height() - h2;
// For the case where the zoom image is actually smaller than
// the flyout.
if (dw < 0) dw = 0;
if (dh < 0) dh = 0;
rw = dw / w1;
rh = dh / h1;
this.isOpen = true;
this.opts.onShow.call(this);
e && this._move(e);
};
/**
* On enter
* @private
* @param {Event} e
*/
EasyZoom.prototype._onEnter = function(e) {
var touches = e.originalEvent.touches;
this.isMouseOver = true;
if (!touches || touches.length == 1) {
e.preventDefault();
this.show(e, true);
}
};
/**
* On move
* @private
* @param {Event} e
*/
EasyZoom.prototype._onMove = function(e) {
if (!this.isOpen) return;
e.preventDefault();
this._move(e);
};
/**
* On leave
* @private
*/
EasyZoom.prototype._onLeave = function() {
this.isMouseOver = false;
this.isOpen && this.hide();
};
/**
* On load
* @private
* @param {Event} e
*/
EasyZoom.prototype._onLoad = function(e) {
// IE may fire a load event even on error so test the image dimensions
if (!e.currentTarget.width) return;
this.isReady = true;
this.$notice.detach();
this.$flyout.html(this.$zoom);
this.$target.removeClass('is-loading').addClass('is-ready');
e.data.call && e.data();
};
/**
* On error
* @private
*/
EasyZoom.prototype._onError = function() {
var self = this;
this.$notice.text(this.opts.errorNotice);
this.$target.removeClass('is-loading').addClass('is-error');
this.detachNotice = setTimeout(function() {
self.$notice.detach();
self.detachNotice = null;
}, this.opts.errorDuration);
};
/**
* Load image
* @private
* @param {String} href
* @param {Function} callback
*/
EasyZoom.prototype._loadImage = function(href, callback) {
var zoom = new Image;
this.$target
.addClass('is-loading')
.append(this.$notice.text(this.opts.loadingNotice));
this.$zoom = $(zoom)
.on('error', $.proxy(this._onError, this))
.on('load', callback, $.proxy(this._onLoad, this));
zoom.style.position = 'absolute';
zoom.src = href;
};
/**
* Move
* @private
* @param {Event} e
*/
EasyZoom.prototype._move = function(e) {
if (e.type.indexOf('touch') === 0) {
var touchlist = e.touches || e.originalEvent.touches;
lx = touchlist[0].pageX;
ly = touchlist[0].pageY;
} else {
lx = e.pageX || lx;
ly = e.pageY || ly;
}
var offset = this.$target.offset();
var pt = ly - offset.top;
var pl = lx - offset.left;
var xt = Math.ceil(pt * rh);
var xl = Math.ceil(pl * rw);
// Close if outside
if (xl < 0 || xt < 0 || xl > dw || xt > dh) {
this.hide();
} else {
var top = xt * -1;
var left = xl * -1;
this.$zoom.css({
top: top,
left: left
});
this.opts.onMove.call(this, top, left);
}
};
/**
* Hide
*/
EasyZoom.prototype.hide = function() {
if (!this.isOpen) return;
if (this.opts.beforeHide.call(this) === false) return;
this.$flyout.detach();
this.isOpen = false;
this.opts.onHide.call(this);
};
/**
* Swap
* @param {String} standardSrc
* @param {String} zoomHref
* @param {String|Array} srcset (Optional)
*/
EasyZoom.prototype.swap = function(standardSrc, zoomHref, srcset) {
this.hide();
this.isReady = false;
this.detachNotice && clearTimeout(this.detachNotice);
this.$notice.parent().length && this.$notice.detach();
this.$target.removeClass('is-loading is-ready is-error');
this.$image.attr({
src: standardSrc,
srcset: $.isArray(srcset) ? srcset.join() : srcset
});
this.$link.attr(this.opts.linkAttribute, zoomHref);
};
/**
* Teardown
*/
EasyZoom.prototype.teardown = function() {
this.hide();
this.$target
.off('.easyzoom')
.removeClass('is-loading is-ready is-error');
this.detachNotice && clearTimeout(this.detachNotice);
delete this.$link;
delete this.$zoom;
delete this.$image;
delete this.$notice;
delete this.$flyout;
delete this.isOpen;
delete this.isReady;
};
// jQuery plugin wrapper
$.fn.easyZoom = function(options) {
return this.each(function() {
var api = $.data(this, 'easyZoom');
if (!api) {
$.data(this, 'easyZoom', new EasyZoom(this, options));
} else if (api.isOpen === undefined) {
api._init();
}
});
};
// AMD and CommonJS module compatibility
if (typeof define === 'function' && define.amd){
define(function() {
return EasyZoom;
});
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = EasyZoom;
}
})(jQuery);
| 201528013359030/basic_pai | views/js/easyzoom.js | JavaScript | bsd-3-clause | 8,461 |
'use strict';
describe('onDisconnect', function() {
var fireproof;
beforeEach(function() {
fireproof = new Fireproof(firebase);
});
describe('#set', function() {
it('promises to set the ref to the specified value on disconnect', function() {
return fireproof
.child('odSet')
.onDisconnect()
.set(true)
.then(function() {
Firebase.goOffline();
Firebase.goOnline();
return fireproof.child('odSet');
})
.then(function(snap) {
expect(snap.val()).to.equal(true);
});
});
});
describe('#remove', function() {
it('promises to remove the data at specified ref on disconnect', function() {
return fireproof
.child('odSet')
.onDisconnect()
.remove()
.then(function() {
Firebase.goOffline();
Firebase.goOnline();
return fireproof.child('odSet');
})
.then(function(snap) {
expect(snap.val()).to.equal(null);
});
});
});
describe('#setWithPriority', function() {
it('promises to set the ref to a value/priority on disconnect', function() {
return fireproof
.child('odSet')
.onDisconnect()
.setWithPriority(true, 5)
.then(function() {
Firebase.goOffline();
Firebase.goOnline();
return fireproof.child('odSet');
})
.then(function(snap) {
expect(snap.val()).to.equal(true);
expect(snap.getPriority()).to.equal(5);
});
});
});
describe('#update', function() {
it('promises to update the ref with the given values on disconnect', function() {
return fireproof
.child('odUpdate')
.set({ foo: 'bar', baz: 'quux' })
.then(function() {
return fireproof
.child('odUpdate')
.onDisconnect()
.update({ baz: 'bells', whistles: true });
})
.then(function() {
Firebase.goOffline();
Firebase.goOnline();
return fireproof.child('odUpdate');
})
.then(function(snap) {
expect(snap.val()).to.deep.equal({
foo: 'bar',
baz: 'bells',
whistles: true
});
});
});
});
describe('#cancel', function() {
it('promises to cancel all onDisconnect operations at the ref', function() {
return fireproof.child('odCancel')
.onDisconnect().set({ foo: 'bar '})
.then(function() {
return fireproof.child('odCancel')
.onDisconnect().cancel();
})
.then(function() {
Firebase.goOffline();
Firebase.goOnline();
return fireproof.child('odCancel');
})
.then(function(snap) {
expect(snap.val()).to.equal(null);
});
});
});
});
| airdrummingfool/fireproof | test/spec/lib/on-disconnect.js | JavaScript | isc | 2,784 |
var Orbit = requireModule("orbit");
// Globalize loader properties for use by other Orbit packages
Orbit.__define__ = define;
Orbit.__requireModule__ = requireModule;
Orbit.__require__ = require;
Orbit.__requirejs__ = requirejs;
window.Orbit = Orbit;
| opsb/orbit-firebase | build-support/globalize-orbit.js | JavaScript | mit | 253 |
///////////////////////////////////////////////////////////////////////////
// Copyright © Esri. All Rights Reserved.
//
// Licensed under the Apache License Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////////
define([
'dojo/_base/declare',
'dojo/_base/lang',
'dojo/_base/array',
'dojo/_base/html',
'dojo/topic',
'dijit/_WidgetBase',
'jimu/dijit/BindLabelPropsMixin',
'dijit/_TemplatedMixin',
'jimu/utils',
'./PanelManager'
], function(declare, lang, array, html, topic, _WidgetBase, BindLabelPropsMixin, _TemplatedMixin,
utils, PanelManager){
var clazz = declare([_WidgetBase, BindLabelPropsMixin, _TemplatedMixin], {
//type: String
// the value shoulb be widget
type: 'widget',
/****these properties can be configured (be overrided) in app's config.json*****/
//id: String
// the unique id of the widget, if not set in the config file,
// ConfigManager will generate one
id: undefined,
//label: String
// the display name of the widget
label: undefined,
//icon: String
// the uri of the icon, use images/icon.png if not set
icon: undefined,
//uir: String
// used in the config.json to locate where the widget is
uri: undefined,
/*======
//left: int
//top: int
//right: int
//bottom: int
//width: int
//height: int
======*/
// preload widget should config position property if it's not in group.
// the meaning of the property is the same as of the CSS
position: {},
//config: Object|String
// config info in config.json, url or json object
// if url is configured in the config.json, json file is parsed and stored in this property
config: undefined,
//defaultState: Boolean
openAtStart: false,
/***************************************************************/
/*********these properties is set by the framework**************/
//map: esri/Map|esri3d/Map
map: null,
//appConfig: Object
// the app's config.json
appConfig: null,
//folderUrl: String
// the folder url of the widget
folderUrl: null,
//state: String
// the current state of the widget, the available states are:
// opened, closed, active
state: 'closed',
//windowState: String
// the available states are normal, minimized, maximized
windowState: 'normal',
//started: boolean
// whether the widget has started
started: false,
//name: String
// the name is used to identify the widget. The name is the same as the widget folder name
name: '',
/***************************************************************/
/*********these properties is set by the developer**************/
//baseClass: String
// HTML CSS class name
baseClass: null,
//templateString: String
// widget UI part, the content of the file Widget.html will be set to this property
templateString: '<div></div>',
moveTopOnActive: true,
/***************************************************************/
constructor: function(){
//listenWidgetNames: String[]
// builder uses this property to filter widgets. App will not use this property to
// filter messages.
this.listenWidgetNames = [];
//listenWidgetIds: String[]
// app use this property to filter data message, if not set, all message will be received.
// this property can be set in config.json
this.listenWidgetIds = [];
//About the communication between widgets:
// * Two widgets can communicate each other directly, or transferred by DataManager.
// * If you want to share data, please call *publishData*. the published data will
// be stored in DataManager.
// * If you want to read share data, you can override *onReceiveData* method. Whenever
// any widgt publishes data, this method will be invoked. (communication directly)
// * If you want to read the data that published before your widget loaded, you can call
// *fetchData* method and get data in *onReceiveData* method. If the data contains
// history data, it will be availble in *historyData* parameter.
// (transferred by DataManager)
this.own(topic.subscribe('publishData', lang.hitch(this, this._onReceiveData)));
this.own(topic.subscribe('dataFetched', lang.hitch(this, this._onReceiveData)));
this.own(topic.subscribe('noData', lang.hitch(this, this._onNoData)));
this.own(topic.subscribe('dataSourceDataUpdated', lang.hitch(this, this.onDataSourceDataUpdate)));
},
startup: function(){
this.inherited(arguments);
this.started = true;
},
onOpen: function(){
// summary:
// this function will be called when widget is opened everytime.
// description:
// state has been changed to "opened" when call this method.
// this function will be called in two cases:
// 1. after widget's startup
// 2. if widget is closed, use re-open the widget
},
onClose: function(){
// summary:
// this function will be called when widget is closed.
// description:
// state has been changed to "closed" when call this method.
},
onNormalize: function(){
// summary:
// this function will be called when widget window is normalized.
// description:
// windowState has been changed to "normal" when call this method.
},
onMinimize: function(){
// summary:
// this function will be called when widget window is minimized.
// description:
// windowState has been changed to "minimized" when call this method.
},
onMaximize: function(){
// summary:
// this function will be called when widget window is maximized.
// description:
// windowState has been changed to "maximized" when call this method.
},
onActive: function(){
// summary:
// this function will be called when widget is clicked.
},
onDeActive: function(){
// summary:
// this function will be called when another widget is clicked.
},
onSignIn: function(credential){
// summary:
// this function will be called after user sign in.
/*jshint unused: false*/
},
onSignOut: function(){
// summary:
// this function will be called after user sign in.
},
onPositionChange: function(position){
//summary:
// this function will be called when position change,
// widget's position will be changed when layout change
// the position object may contain w/h/t/l/b/r
this.setPosition(position);
},
setPosition: function(position, containerNode){
//For on-screen off-panel widget, layout manager will call this function
//to set widget's position after load widget. If your widget will position by itself,
//please override this function.
this.position = position;
var style = utils.getPositionStyle(this.position);
style.position = 'absolute';
if(!containerNode){
if(position.relativeTo === 'map'){
containerNode = this.map.id;
}else{
containerNode = window.jimuConfig.layoutId;
}
}
html.place(this.domNode, containerNode);
html.setStyle(this.domNode, style);
if(this.started){
this.resize();
}
},
getPosition: function(){
return this.position;
},
getMarginBox: function() {
var box = html.getMarginBox(this.domNode);
return box;
},
setMap: function( /*esri.Map*/ map){
this.map = map;
},
setState: function(state){
this.state = state;
},
setWindowState: function(state){
this.windowState = state;
},
resize: function(){
},
//these three methods are used by builder.
onConfigChanged: function(config){
/*jshint unused: false*/
},
onAppConfigChanged: function(appConfig, reason, changedData){
/*jshint unused: false*/
},
onAction: function(action, data){
/*jshint unused: false*/
},
getPanel: function(){
//get panel of the widget. return null for off-panel widget.
if(this.inPanel === false){
return null;
}
if(this.gid === 'widgetOnScreen' || this.gid === 'widgetPool'){
return PanelManager.getInstance().getPanelById(this.id + '_panel');
}else{
//it's in group
var panel = PanelManager.getInstance().getPanelById(this.gid + '_panel');
if(panel){
//open all widgets in group together
return panel;
}else{
return PanelManager.getInstance().getPanelById(this.id + '_panel');
}
}
},
publishData: function(data, keepHistory){
//if set keepHistory = true, all published data will be stored in datamanager,
//this may cause memory problem.
if(typeof keepHistory === 'undefined'){
//by default, we don't keep the history of the data.
keepHistory = false;
}
topic.publish('publishData', this.name, this.id, data, keepHistory);
},
fetchData: function(widgetId){
//widgetId, the widget id that you want to read data. it is optional.
if(widgetId){
topic.publish('fetchData', widgetId);
}else{
if(this.listenWidgetIds.length !== 0){
array.forEach(this.listenWidgetIds, function(widgetId){
topic.publish('fetchData', widgetId);
}, this);
}else{
topic.publish('fetchData');
}
}
},
fetchDataByName: function(widgetName){
//widgetId, the widget name that you want to read data. it is required.
var widgets = this.widgetManager.getWidgetsByName(widgetName);
array.forEach(widgets, function(widget){
this.fetchData(widget.id);
}, this);
},
openWidgetById: function(widgetId){
return this.widgetManager.triggerWidgetOpen(widgetId);
},
_onReceiveData: function(name, widgetId, data, historyData){
//the data is what I published
if(widgetId === this.id){
return;
}
//I am not interested in the the widget id
if(this.listenWidgetIds.length !== 0 && this.listenWidgetIds.indexOf(widgetId) < 0){
return;
}
this.onReceiveData(name, widgetId, data, historyData);
},
onReceiveData: function(name, widgetId, data, historyData){
/* jshint unused: false */
// console.log('onReceiveData: ' + name + ',' + widgetId + ',data:' + data);
/****************About historyData:
The historyData maybe: undefined, true, object(data)
undefined: means data published without history
true: means data published with history. If this widget want to fetch history data,
Please call fetch data.
object: the history data.
*********************************/
},
updateDataSourceData: function(dsId, data){
topic.publish('updateDataSourceData', 'widget~' + this.id + '~' + dsId, data);
},
onDataSourceDataUpdate: function(dsId, data){
/* jshint unused: false */
},
_onNoData: function(name, widgetId){
/*jshint unused: false*/
if(this.listenWidgetIds.length !== 0 && this.listenWidgetIds.indexOf(widgetId) < 0){
return;
}
this.onNoData(name, widgetId);
},
onNoData: function(name, widgetId){
/*jshint unused: false*/
}
});
return clazz;
}); | tmcgee/cmv-wab-widgets | wab/2.15/jimu.js/BaseWidget.js | JavaScript | mit | 12,218 |
vti_encoding:SR|utf8-nl
vti_timelastmodified:TR|09 Feb 2017 03:34:58 -0000
vti_extenderversion:SR|6.0.2.8161
vti_backlinkinfo:VX|astro_site/mobile.html astro_site/mobile2.html
| akarys92/astro_site | vendor/scrollreveal/_vti_cnf/scrollreveal.min.js | JavaScript | mit | 176 |
/*! Select2 4.0.0 | https://github.com/select2/select2/blob/master/LICENSE.md */
(function(){if(jQuery&&jQuery.fn&&jQuery.fn.select2&&jQuery.fn.select2.amd)var e=jQuery.fn.select2.amd;return e.define("select2/i18n/et",[],function(){return{inputTooLong:function(e){var t=e.input.length-e.maximum,n="Sisesta "+t+" täht";return t!=1&&(n+="e"),n+=" vähem",n},inputTooShort:function(e){var t=e.minimum-e.input.length,n="Sisesta "+t+" täht";return t!=1&&(n+="e"),n+=" rohkem",n},loadingMore:function(){return"Laen tulemusi..."},maximumSelected:function(e){var t="Saad vaid "+e.maximum+" tulemus";return e.maximum==1?t+="e":t+="t",t+=" valida",t},noResults:function(){return"Tulemused puuduvad"},searching:function(){return"Otsin..."}}}),{define:e.define,require:e.require}})(); | jpaoletti/java-presentation-manager-2 | modules/jpm2-web-bs5/src/main/webapp/static/js/locale/select2/et.js | JavaScript | mit | 775 |
'use strict';
module.exports = function copyto(grunt) {
// Load task
grunt.loadNpmTasks('grunt-copy-to');
// Options
return {
build: {
files: [{
cwd: 'src',
src: ['**/*.json'],
dest: '.dist/'
},{
cwd: 'src',
src: ['public/css/**/*.less'],
dest: '.dist/'
}]
}
};
};
| samsel/Gander | tasks/copyto.js | JavaScript | mit | 436 |
/*
define(['iframeResizerContent'], function() {
describe('ParentIFrame methods: ', function() {
var id = 'parentIFrame';
var log = LOG;
it('Get ID of iFrame is same as iFrame', function() {
mockInitFromParent(id,log);
expect(window.parentIFrame.getId()).toBe(id);
closeChild();
});
it('call methods', function() {
var count = 0;
mockInitFromParent(id,false,function(msg){
switch(++count){
case 2:
expect(msg.split('#')[1]).toBe('foo');
break;
case 3:
expect(strEnd(msg,5)).toBe('reset');
break;
case 4:
expect(msg).toBe('foo');
break;
case 5:
expect(msg).toBe('foo');
break;
case 6:
expect(msg).toBe('foo');
break;
case 7:
expect(msg).toBe('foo');
break;
case 8:
expect(msg).toBe('foo');
break;
}
});
expect(window.parentIFrame.getId()).toBe(id);
window.parentIFrame.moveToAnchor('foo');
//window.parentIFrame.reset();
//setTimeout(closeChild,1);
});
});
});
*/ | tlan16/sushi-co | web/protected/controls/iframeResizer/doc/spec/parentIFrameMethodsSpec.js | JavaScript | mit | 1,024 |
define({
"showArcgisBasemaps": "Incluir mapas base do Portal",
"add": "Clique para adicionar um novo mapa base",
"edit": "Propriedades",
"titlePH": "Título do mapa base",
"thumbnailHint": "Clique na imagem para atualizar",
"urlPH": "URL da Camada",
"addlayer": "Adicionar mapa base",
"warning": "Entrada incorreta",
"save": "Voltar e salvar",
"back": "Voltar e cancelar",
"addUrl": "Adicionar URL",
"autoCheck": "Verificação automática",
"checking": "Verificando...",
"result": "Salvo com sucesso",
"spError": "Todo os mapas base adicionados na galeria precisam ter a mesma referência espacial.",
"invalidTitle1": "Um mapa base '",
"invalidTitle2": "‘ já existe. Escolha outro título.",
"invalidBasemapUrl1": "Este tipo de camada não pode ser utilizada como um mapa base.",
"invalidBasemapUrl2": "O mapa base que você está adicionando tem uma referência espacial diferente do mapa atual.",
"addBaselayer": "Adicionar camada de mapa base",
"repectOnline": "Sempre sincronizar com a configuração da Galeria de Mapa Base da organização",
"customBasemap": "Configurar mapas base personalizados",
"basemapTips": "Clique em \"${import}\" ou \"${createNew}\" para adicionar maps base.",
"importBasemap": "Importar",
"createBasemap": "Criar novo",
"importTitle": "Importar mapas base",
"createTitle": "Novo mapa base",
"selectGroupTip": "Seleciona um grupo cujo mapas da web podem ser utilizados como mapas base.",
"noBasemaps": "Nenhum mapa base.",
"defaultGroup": "Padrão Esri",
"defaultOrgGroup": "Organização padrão",
"warningTitle": "Aviso",
"confirmDelete": "Deseja excluir os mapas base selecionados?",
"noBasemapAvailable": "Não há mapas base disponíveis, pois todos os mapas base têm referência espacial ou esquema de mosaico diferente do mapa atual."
}); | tmcgee/cmv-wab-widgets | wab/2.15/widgets/BasemapGallery/setting/nls/pt-br/strings.js | JavaScript | mit | 1,850 |
import expect from 'expect';
import isFunction from '../../../src/validation/validators/isFunction';
describe('validators', () => {
describe('toFunction', () => {
it('should return infoObject if requested', () => {
expect(isFunction(null, true))
.toEqual({
type: 'Function',
required: false,
canBeEmpty: null,
converter: undefined,
unmanagedObject: false,
});
});
it('should validate a function correctly', () => {
expect(isFunction(() => {}))
.toBe(true);
});
it('should validate a function correctly when undefined', () => {
expect(isFunction(undefined))
.toBe(true);
});
it('should return error if value is not a function', () => {
expect(isFunction(1))
.toInclude('not a function');
});
it('should allow undefined and null', () => {
expect(isFunction(null))
.toBe(true);
expect(isFunction(undefined))
.toBe(true);
});
});
});
| vgno/roc-config | test/validation/validators/isFunction.js | JavaScript | mit | 1,209 |
/*!
* NETEYE Activity Indicator jQuery Plugin
*
* Copyright (c) 2010 NETEYE GmbH
* Licensed under the MIT license
*
* Author: Felix Gnass [fgnass at neteye dot de]
* Version: 1.0.0
*/
/**
* Plugin that renders a customisable activity indicator (spinner) using SVG or VML.
*/
(function($) {
$.fn.activity = function(opts) {
this.each(function() {
var $this = $(this);
var el = $this.data('activity');
if (el) {
clearInterval(el.data('interval'));
el.remove();
$this.removeData('activity');
}
if (opts !== false) {
opts = $.extend({color: $this.css('color')}, $.fn.activity.defaults, opts);
el = render($this, opts).css('position', 'absolute').prependTo(opts.outside ? 'body' : $this);
var h = $this.outerHeight() - el.height();
var w = $this.outerWidth() - el.width();
var margin = {
top: opts.valign == 'top' ? opts.padding : opts.valign == 'bottom' ? h - opts.padding : Math.floor(h / 2),
left: opts.align == 'left' ? opts.padding : opts.align == 'right' ? w - opts.padding : Math.floor(w / 2)
};
var offset = $this.offset();
if (opts.outside) {
el.css({top: offset.top + 'px', left: offset.left + 'px'});
}
else {
margin.top -= el.offset().top - offset.top;
margin.left -= el.offset().left - offset.left;
}
el.css({marginTop: margin.top + 'px', marginLeft: margin.left + 'px'});
animate(el, opts.segments, Math.round(10 / opts.speed) / 10);
$this.data('activity', el);
}
});
return this;
};
$.fn.activity.defaults = {
segments: 12,
space: 3,
length: 7,
width: 4,
speed: 1.2,
align: 'center',
valign: 'center',
padding: 4
};
$.fn.activity.getOpacity = function(opts, i) {
var steps = opts.steps || opts.segments-1;
var end = opts.opacity !== undefined ? opts.opacity : 1/steps;
return 1 - Math.min(i, steps) * (1 - end) / steps;
};
/**
* Default rendering strategy. If neither SVG nor VML is available, a div with class-name 'busy'
* is inserted, that can be styled with CSS to display an animated gif as fallback.
*/
var render = function() {
return $('<div>').addClass('busy');
};
/**
* The default animation strategy does nothing as we expect an animated gif as fallback.
*/
var animate = function() {
};
/**
* Utility function to create elements in the SVG namespace.
*/
function svg(tag, attr) {
var el = document.createElementNS("http://www.w3.org/2000/svg", tag || 'svg');
if (attr) {
$.each(attr, function(k, v) {
el.setAttributeNS(null, k, v);
});
}
return $(el);
}
if (document.createElementNS && document.createElementNS( "http://www.w3.org/2000/svg", "svg").createSVGRect) {
// =======================================================================================
// SVG Rendering
// =======================================================================================
/**
* Rendering strategy that creates a SVG tree.
*/
render = function(target, d) {
var innerRadius = d.width*2 + d.space;
var r = (innerRadius + d.length + Math.ceil(d.width / 2) + 1);
var el = svg().width(r*2).height(r*2);
var g = svg('g', {
'stroke-width': d.width,
'stroke-linecap': 'round',
stroke: d.color
}).appendTo(svg('g', {transform: 'translate('+ r +','+ r +')'}).appendTo(el));
for (var i = 0; i < d.segments; i++) {
g.append(svg('line', {
x1: 0,
y1: innerRadius,
x2: 0,
y2: innerRadius + d.length,
transform: 'rotate(' + (360 / d.segments * i) + ', 0, 0)',
opacity: $.fn.activity.getOpacity(d, i)
}));
}
return $('<div>').append(el).width(2*r).height(2*r);
};
// Check if Webkit CSS animations are available, as they work much better on the iPad
// than setTimeout() based animations.
if (document.createElement('div').style.WebkitAnimationName !== undefined) {
var animations = {};
/**
* Animation strategy that uses dynamically created CSS animation rules.
*/
animate = function(el, steps, duration) {
if (!animations[steps]) {
var name = 'spin' + steps;
var rule = '@-webkit-keyframes '+ name +' {';
for (var i=0; i < steps; i++) {
var p1 = Math.round(100000 / steps * i) / 1000;
var p2 = Math.round(100000 / steps * (i+1) - 1) / 1000;
var value = '% { -webkit-transform:rotate(' + Math.round(360 / steps * i) + 'deg); }\n';
rule += p1 + value + p2 + value;
}
rule += '100% { -webkit-transform:rotate(100deg); }\n}';
document.styleSheets[0].insertRule(rule,document.styleSheets[0].cssRules.length-1);
animations[steps] = name;
}
el.css('-webkit-animation', animations[steps] + ' ' + duration +'s linear infinite');
};
}
else {
/**
* Animation strategy that transforms a SVG element using setInterval().
*/
animate = function(el, steps, duration) {
var rotation = 0;
var g = el.find('g g').get(0);
el.data('interval', setInterval(function() {
g.setAttributeNS(null, 'transform', 'rotate(' + (++rotation % steps * (360 / steps)) + ')');
}, duration * 1000 / steps));
};
}
}
else {
// =======================================================================================
// VML Rendering
// =======================================================================================
var s = $('<shape>').css('behavior', 'url(#default#VML)').appendTo('body');
if (s.get(0).adj) {
// VML support detected. Insert CSS rules for group, shape and stroke.
var sheet = document.createStyleSheet();
$.each(['group', 'shape', 'stroke'], function() {
sheet.addRule(this, "behavior:url(#default#VML);");
});
/**
* Rendering strategy that creates a VML tree.
*/
render = function(target, d) {
var innerRadius = d.width*2 + d.space;
var r = (innerRadius + d.length + Math.ceil(d.width / 2) + 1);
var s = r*2;
var o = -Math.ceil(s/2);
var el = $('<group>', {coordsize: s + ' ' + s, coordorigin: o + ' ' + o}).css({top: o, left: o, width: s, height: s});
for (var i = 0; i < d.segments; i++) {
el.append($('<shape>', {path: 'm ' + innerRadius + ',0 l ' + (innerRadius + d.length) + ',0'}).css({
width: s,
height: s,
rotation: (360 / d.segments * i) + 'deg'
}).append($('<stroke>', {color: d.color, weight: d.width + 'px', endcap: 'round', opacity: $.fn.activity.getOpacity(d, i)})));
}
return $('<group>', {coordsize: s + ' ' + s}).css({width: s, height: s, overflow: 'hidden'}).append(el);
};
/**
* Animation strategy that modifies the VML rotation property using setInterval().
*/
animate = function(el, steps, duration) {
var rotation = 0;
var g = el.get(0);
el.data('interval', setInterval(function() {
g.style.rotation = ++rotation % steps * (360 / steps);
}, duration * 1000 / steps));
};
}
$(s).remove();
}
})(jQuery);
| MSylvia/feeds | Website/js/jquery.activity-indicator-1.0.1.js | JavaScript | mit | 6,993 |
/* jshint browser:true */
/* global define, google */
define(['underscore', 'backbone', 'oro/translator'],
function(_, Backbone, __) {
'use strict';
var $ = Backbone.$;
/**
* @export oro/mapservice/googlemaps
* @class oro.mapservice.Googlemaps
* @extends Backbone.View
*/
return Backbone.View.extend({
options: {
mapOptions: {
zoom: 17,
mapTypeControl: true,
panControl: false,
zoomControl: true
},
apiVersion: '3.exp',
sensor: false,
apiKey: null,
showWeather: true
},
mapLocationCache: {},
mapsLoadExecuted: false,
initialize: function() {
this.$mapContainer = $('<div class="map-visual"/>')
.appendTo(this.$el);
this.$unknownAddress = $('<div class="map-unknown">' + __('map.unknown.location') + '</div>')
.appendTo(this.$el);
this.mapLocationUnknown();
},
_initMapOptions: function() {
if (_.isUndefined(this.options.mapOptions.mapTypeControlOptions)) {
this.options.mapOptions.mapTypeControlOptions = {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
};
}
if (_.isUndefined(this.options.mapOptions.zoomControlOptions)) {
this.options.mapOptions.zoomControlOptions = {
style: google.maps.ZoomControlStyle.SMALL
};
}
if (_.isUndefined(this.options.mapOptions.mapTypeId)) {
this.options.mapOptions.mapTypeId = google.maps.MapTypeId.ROADMAP;
}
},
_initMap: function(location) {
this._initMapOptions();
this.map = new google.maps.Map(
this.$mapContainer[0],
_.extend({}, this.options.mapOptions, {center: location})
);
this.mapLocationMarker = new google.maps.Marker({
draggable: false,
map: this.map,
position: location
});
if (this.options.showWeather) {
var weatherLayer = new google.maps.weather.WeatherLayer();
weatherLayer.setMap(this.map);
var cloudLayer = new google.maps.weather.CloudLayer();
cloudLayer.setMap(this.map);
}
},
loadGoogleMaps: function() {
var googleMapsSettings = 'sensor=' + (this.options.sensor ? 'true' : 'false');
if (this.options.showWeather) {
googleMapsSettings += '&libraries=weather';
}
if (this.options.apiKey) {
googleMapsSettings += '&key=' + this.options.apiKey;
}
$.ajax({
url: window.location.protocol + "//www.google.com/jsapi",
dataType: "script",
cache: true,
success: _.bind(function() {
google.load('maps', this.options.apiVersion, {
other_params: googleMapsSettings,
callback: _.bind(this.onGoogleMapsInit, this)
});
}, this)
});
},
updateMap: function(address, label) {
// Load google maps js
if (!this.hasGoogleMaps() && !this.mapsLoadExecuted) {
this.mapsLoadExecuted = true;
this.requestedLocation = {
'address': address,
'label': label
};
this.loadGoogleMaps();
return;
}
if (this.mapLocationCache.hasOwnProperty(address)) {
this.updateMapLocation(this.mapLocationCache[address], label);
} else {
this.getGeocoder().geocode({'address': address}, _.bind(function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
this.mapLocationCache[address] = results[0].geometry.location;
//Move location marker and map center to new coordinates
this.updateMapLocation(results[0].geometry.location, label);
} else {
this.mapLocationUnknown();
}
}, this));
}
},
onGoogleMapsInit: function() {
if (!_.isUndefined(this.requestedLocation)) {
this.updateMap(this.requestedLocation.address, this.requestedLocation.label);
delete this.requestedLocation;
}
},
hasGoogleMaps: function() {
return !_.isUndefined(window.google) && google.hasOwnProperty('maps');
},
mapLocationUnknown: function() {
this.$mapContainer.hide();
this.$unknownAddress.show();
},
mapLocationKnown: function() {
this.$mapContainer.show();
this.$unknownAddress.hide();
},
updateMapLocation: function(location, label) {
this.mapLocationKnown();
if (location && (!this.location || location.toString() !== this.location.toString())) {
this._initMap(location);
this.map.setCenter(location);
this.mapLocationMarker.setPosition(location);
this.mapLocationMarker.setTitle(label);
this.location = location;
}
},
getGeocoder: function() {
if (_.isUndefined(this.geocoder)) {
this.geocoder = new google.maps.Geocoder();
}
return this.geocoder;
}
});
});
| minhnguyen-balance/oro_platform | web/bundles/oroaddress/js/mapservice/googlemaps.js | JavaScript | mit | 5,828 |
/* global Dubtrack */
const modal = require('../utils/modal.js');
var isActiveTab = true;
window.onfocus = function () {
isActiveTab = true;
};
window.onblur = function () {
isActiveTab = false;
};
var onDenyDismiss = function() {
modal.create({
title: 'Desktop Notifications',
content: "You have dismissed or chosen to deny the request to allow desktop notifications. Reset this choice by clearing your cache for the site."
});
};
export function notifyCheckPermission(cb){
var _cb = typeof cb === 'function' ? cb : function(){};
// first check if browser supports it
if (!("Notification" in window)) {
modal.create({
title: 'Desktop Notifications',
content: "Sorry this browser does not support desktop notifications. Please use the latest version of Chrome or FireFox"
});
return _cb(false);
}
// no request needed, good to go
if (Notification.permission === "granted") {
return _cb(true);
}
if (Notification.permission !== 'denied') {
Notification.requestPermission().then(function(result) {
if (result === 'denied' || result === 'default') {
onDenyDismiss();
_cb(false);
return;
}
_cb(true);
});
} else {
onDenyDismiss();
return _cb(false);
}
}
export function showNotification (opts){
var defaults = {
title : 'New Message',
content : '',
ignoreActiveTab : false,
callback : null,
wait : 5000
};
var options = Object.assign({}, defaults, opts);
// don't show a notification if tab is active
if (isActiveTab === true && !options.ignoreActiveTab) { return; }
var notificationOptions = {
body: options.content,
icon: "https://res.cloudinary.com/hhberclba/image/upload/c_lpad,h_100,w_100/v1400351432/dubtrack_new_logo_fvpxa6.png"
};
var n = new Notification(options.title, notificationOptions);
n.onclick = function() {
window.focus();
if (typeof options.callback === "function") { options.callback(); }
n.close();
};
setTimeout(n.close.bind(n), options.wait);
}
| coryshaw1/DubPlus | src/js/utils/notify.js | JavaScript | mit | 2,082 |
pageflow.VideoPlayer.bufferUnderrunWaiting = function(player) {
var originalPause = player.pause;
player.pause = function() {
cancelWaiting();
originalPause.apply(this, arguments);
};
function pauseAndPreloadOnUnderrun() {
if (bufferUnderrun()) {
pauseAndPreload();
}
}
function bufferUnderrun() {
return !player.isBufferedAhead(0.1, true) && !player.waitingOnUnderrun && !ignoringUnderruns();
}
function pauseAndPreload() {
pageflow.log('Buffer underrun');
player.trigger('bufferunderrun');
player.pause();
player.waitingOnUnderrun = true;
player.prebuffer({secondsToBuffer: 5, secondsToWait: 5}).then(function() {
// do nothing if user aborted waiting by clicking pause
if (player.waitingOnUnderrun) {
player.waitingOnUnderrun = false;
player.trigger('bufferunderruncontinue');
player.play();
}
});
}
function cancelWaiting() {
if (player.waitingOnUnderrun) {
player.ignoreUnderrunsUntil = new Date().getTime() + 5 * 1000;
player.waitingOnUnderrun = false;
player.trigger('bufferunderruncontinue');
}
}
function ignoringUnderruns() {
var r = player.ignoreUnderrunsUntil && new Date().getTime() < player.ignoreUnderrunsUntil;
if (r) {
pageflow.log('ignoring underrun');
}
return r;
}
function stopListeningForProgress() {
player.off('progress', pauseAndPreloadOnUnderrun);
}
if (pageflow.browser.has('buffer underrun waiting support')) {
player.on('play', function() {
player.on('progress', pauseAndPreloadOnUnderrun);
});
player.on('pause', stopListeningForProgress);
player.on('ended', stopListeningForProgress);
}
}; | tf/pageflow-dependabot-test | app/assets/javascripts/pageflow/video_player/buffer_underrun_waiting.js | JavaScript | mit | 1,736 |
var inspect = require("util").inspect,
fs = require("fs");
module.exports = function(grunt) {
var task = grunt.task;
var file = grunt.file;
var log = grunt.log;
var verbose = grunt.verbose;
var fail = grunt.fail;
var option = grunt.option;
var config = grunt.config;
var template = grunt.template;
var _ = grunt.util._;
var templates = {
doc: _.template( file.read("tpl/.docs.md") ),
img: _.template( file.read("tpl/.img.md") ),
fritzing: _.template( file.read("tpl/.fritzing.md") ),
doclink: _.template( file.read("tpl/.readme.doclink.md") ),
readme: _.template( file.read("tpl/.readme.md") )
};
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
docs: {
files: ["programs.json"]
},
nodeunit: {
tests: [
"test/board.js",
"test/button.js",
"test/options.js",
"test/pins.js",
"test/capabilities.js",
"test/led.js",
"test/pin.js",
"test/pir.js",
"test/sensor.js",
"test/ping.js",
"test/shiftregister.js"
]
},
jshint: {
options: {
curly: true,
eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
boss: true,
eqnull: true,
node: true,
strict: false,
globals: {
exports: true,
document: true,
$: true,
Radar: true,
WeakMap: true,
window: true
}
},
files: {
src: ["Gruntfile.js", "lib/**/!(johnny-five)*.js", "test/**/*.js", "eg/**/*.js"]
}
},
jsbeautifier: {
files: ["lib/**/*.js"],
options: {
js: {
braceStyle: "collapse",
breakChainedMethods: false,
e4x: false,
evalCode: false,
indentChar: " ",
indentLevel: 0,
indentSize: 2,
indentWithTabs: false,
jslintHappy: false,
keepArrayIndentation: false,
keepFunctionIndentation: false,
maxPreserveNewlines: 10,
preserveNewlines: true,
spaceBeforeConditional: true,
spaceInParen: false,
unescapeStrings: false,
wrapLineLength: 0
}
}
}
});
// Default tasks are contrib plugins
grunt.loadNpmTasks("grunt-contrib-nodeunit");
grunt.loadNpmTasks("grunt-contrib-jshint");
grunt.loadNpmTasks("grunt-jsbeautifier");
// Default task.
grunt.registerTask("default", ["jshint", "nodeunit"]);
grunt.registerMultiTask("docs", "generate simple docs from examples", function() {
// Concat specified files.
var entries, readme;
entries = JSON.parse(file.read(file.expand( this.data )));
readme = [];
entries.forEach(function( entry ) {
var values, markdown, eg, md, png, fzz, title,
hasPng, hasFzz, inMarkdown, filepath, fritzfile, fritzpath;
if ( Array.isArray(entry) ) {
// Produces:
// "### Heading\n"
readme.push( "\n### " + entry[0] + "\n" );
// TODO: figure out a way to have tiered subheadings
// readme.push(
// entry.reduce(function( prev, val, k ) {
// // Produces:
// // "### Board\n"
// return prev + (Array(k + 4).join("#")) + " " + val + "\n";
// }, "")
// );
}
else {
filepath = "eg/" + entry;
eg = file.read( filepath );
md = "docs/" + entry.replace(".js", ".md");
png = "docs/breadboard/" + entry.replace(".js", ".png");
fzz = "docs/breadboard/" + entry.replace(".js", ".fzz");
title = entry;
markdown = [];
// Generate a title string from the file name
[ [ /^.+\//, "" ],
[ /\.js/, "" ],
[ /\-/g, " " ]
].forEach(function( args ) {
title = "".replace.apply( title, args );
});
fritzpath = fzz.split("/");
fritzfile = fritzpath[ fritzpath.length - 1 ];
inMarkdown = false;
// Modify code in example to appear as it would if installed via npm
eg = eg.replace("../lib/johnny-five.js", "johnny-five")
.split("\n").filter(function( line ) {
if ( /@markdown/.test(line) ) {
inMarkdown = !inMarkdown;
return false;
}
if ( inMarkdown ) {
line = line.trim();
if ( line ) {
markdown.push(
line.replace(/^\/\//, "").trim()
);
}
// Filter out the markdown lines
// from the main content.
return false;
}
return true;
}).join("\n");
hasPng = fs.existsSync(png);
hasFzz = fs.existsSync(fzz);
// console.log( markdown );
values = {
title: _.titleize(title),
command: "node " + filepath,
example: eg,
file: md,
markdown: markdown.join("\n"),
breadboard: hasPng ? templates.img({ png: png }) : "",
fritzing: hasFzz ? templates.fritzing({ fzz: fzz }) : ""
};
// Write the file to /docs/*
file.write( md, templates.doc(values) );
// Push a rendered markdown link into the readme "index"
readme.push( templates.doclink(values) );
}
});
// Write the readme with doc link index
file.write( "README.md", templates.readme({ doclinks: readme.join("") }) );
log.writeln("Docs created.");
});
};
| ebberly/johnny-five-tutorial | node_modules/johnny-five/Gruntfile.js | JavaScript | mit | 5,627 |
define([
'extensions/collections/collection'
],
function (Collection) {
return Collection.extend({
initialize: function (models, options) {
if(options !== undefined){
options.flattenEverything = false;
}
return Collection.prototype.initialize.apply(this, arguments);
},
parse: function () {
var data = Collection.prototype.parse.apply(this, arguments);
var lines = this.options.axes.y;
var hasOther = _.findWhere(lines, { groupId: 'other' });
if (this.options.groupMapping) {
_.each(this.options.groupMapping, function (to, from) {
from = new RegExp(from + ':' + this.valueAttr);
_.each(data, function (model) {
var toAttr = to + ':' + this.valueAttr;
var sum = 0;
_.each(model, function (val, key) {
if (key.match(from)) {
if (val) {
sum += val;
}
delete model[key];
}
});
if (model[toAttr] === undefined) {
model[toAttr] = 0;
}
model[toAttr] += sum;
}, this);
}, this);
}
_.each(data, function (model) {
var total = null,
other = null;
_.each(model, function (val, key) {
var index = key.indexOf(this.valueAttr);
if (index > 1 && model[key]) {
// get the prefix value
var group = key.replace(':' + this.valueAttr, '');
var axis = _.findWhere(lines, { groupId: group });
if (axis || hasOther) {
total += model[key];
}
if (!axis) {
other += model[key];
delete model[key];
}
}
}, this);
model['other:' + this.valueAttr] = other;
model['total:' + this.valueAttr] = total;
_.each(lines, function (line) {
var prop = (line.key || line.groupId) + ':' + this.valueAttr;
var value = model[prop];
if (value === undefined) {
value = model[prop] = null;
}
if (model['total:' + this.valueAttr]) {
model[prop + ':percent'] = value / model['total:' + this.valueAttr];
} else {
model[prop + ':percent'] = null;
}
}, this);
}, this);
return data;
},
getYAxes: function () {
var axes = Collection.prototype.getYAxes.apply(this, arguments);
_.each(this.options.groupMapping, function (to, from) {
axes.push({ groupId: from });
});
return axes;
}
});
});
| alphagov/spotlight | app/common/collections/grouped_timeseries.js | JavaScript | mit | 2,654 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.11.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
/* jshint latedef:false */
/* jshint forin:false */
/* jshint noempty:false */
'use strict';
var util = require('util');
var msRest = require('ms-rest');
var ServiceClient = msRest.ServiceClient;
var WebResource = msRest.WebResource;
var models = require('./models');
var operations = require('./operations');
/**
* @class
* Initializes a new instance of the AutoRestComplexTestService class.
* @constructor
*
* @param {string} [baseUri] - The base URI of the service.
*
* @param {object} [options] - The parameter options
*
* @param {Array} [options.filters] - Filters to be added to the request pipeline
*
* @param {object} [options.requestOptions] - Options for the underlying request object
* {@link https://github.com/request/request#requestoptions-callback Options doc}
*
* @param {bool} [options.noRetryPolicy] - If set to true, turn off default retry policy
*/
function AutoRestComplexTestService(baseUri, options) {
if (!options) options = {};
AutoRestComplexTestService['super_'].call(this, null, options);
this.baseUri = baseUri;
if (!this.baseUri) {
this.baseUri = 'http://localhost';
}
this.basicOperations = new operations.BasicOperations(this);
this.primitive = new operations.Primitive(this);
this.arrayModel = new operations.ArrayModel(this);
this.dictionary = new operations.Dictionary(this);
this.inheritance = new operations.Inheritance(this);
this.polymorphism = new operations.Polymorphism(this);
this.polymorphicrecursive = new operations.Polymorphicrecursive(this);
this._models = models;
}
util.inherits(AutoRestComplexTestService, ServiceClient);
module.exports = AutoRestComplexTestService;
| colemickens/autorest | AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyComplex/autoRestComplexTestService.js | JavaScript | mit | 1,993 |
import { isUndefined, isObject } from '../utils/isType';
$(() => {
// url for the api we will be querying
let url = '';
// key/value lookup for standards
const descriptions = {};
// cleaned up structure of the API results
const minTree = {};
// keeps track of how many waiting api-requests still need to run
let noWaiting = 0;
// prune the min_tree where there are no standards
// opporates on the principal that no two subjects have the same name
function removeUnused(name) {
const num = Object.keys(minTree).find((x) => minTree[x].name === name);
// if not top level standard
if (isUndefined(num)) {
// for each top level standard
Object.keys(minTree).forEach((knum) => {
const child = Object.keys(minTree[knum].children)
.find((x) => minTree[knum].children[x].name === name);
if (isObject(child)) {
delete minTree[knum].children[child];
$(`.rda_metadata .sub-subject select option[value="${name}"]`).remove();
}
});
} else {
delete minTree[num];
// remove min_tree[num] from top-level dropdowns
$(`.rda_metadata .subject select option[value="${name}"]`).remove();
}
}
function getDescription(id) {
$.ajax({
url: url + id.slice(4),
type: 'GET',
crossDomain: true,
dataType: 'json',
}).done((results) => {
descriptions[id] = {};
descriptions[id].title = results.title;
descriptions[id].description = results.description;
noWaiting -= 1;
});
}
// init descriptions lookup table based on passed ids
function initDescriptions(ids) {
ids.forEach((id) => {
if (!(id in descriptions)) {
noWaiting += 1;
getDescription(id);
}
});
}
// takes in a subset of the min_tree which has name and standards properties
// initializes the standards property to the result of an AJAX POST
function getStandards(name, num, child) {
// slice -4 from url to remove '/api/'
noWaiting += 1;
$.ajax({
url: `${url.slice(0, -4)}query/schemes`,
type: 'POST',
crossDomain: true,
data: `keyword=${name}`,
dataType: 'json',
}).done((result) => {
if (isUndefined(child)) {
minTree[num].standards = result.ids;
} else {
minTree[num].children[child].standards = result.ids;
}
if (result.ids.length < 1) {
removeUnused(name);
}
noWaiting -= 1;
initDescriptions(result.ids);
});
}
// clean up the data initially returned from the API
function cleanTree(apiTree) {
// iterate over api_tree
Object.keys(apiTree).forEach((num) => {
minTree[num] = {};
minTree[num].name = apiTree[num].name;
minTree[num].children = [];
if (apiTree[num].children !== undefined) {
Object.keys(apiTree[num].children).forEach((child) => {
minTree[num].children[child] = {};
minTree[num].children[child].name = apiTree[num].children[child].name;
minTree[num].children[child].standards = [];
getStandards(minTree[num].children[child].name, num, child);
});
}
// init a standards on top level
minTree[num].standards = [];
getStandards(minTree[num].name, num, undefined);
});
}
// create object for typeahead
function initTypeahead() {
const data = [];
const simpdat = [];
Object.keys(descriptions).forEach((id) => {
data.push({ value: descriptions[id].title, id });
simpdat.push(descriptions[id].title);
});
const typ = $('.standards-typeahead');
typ.typeahead({ source: simpdat });
}
function initStandards() {
// for each metadata question, init selected standards according to html
$('.rda_metadata').each(function () { // eslint-disable-line func-names
// list of selected standards
const selectedStandards = $(this).find('.selected_standards .list');
// form listing of standards
const formStandards = $(this).next('form').find('#standards');
// need to pull in the value from frm_stds
const standardsArray = JSON.parse(formStandards.val());
// init the data value
formStandards.data('standard', standardsArray);
Object.keys(standardsArray).forEach((key) => {
// add the standard to list
if (key === standardsArray[key]) {
selectedStandards.append(`<li class="${key}">${key}<button class="remove-standard"><i class="fas fa-times-circle"></i></button></li`);
} else {
selectedStandards.append(`<li class="${key}">${descriptions[key].title}<button class="remove-standard"><i class="fas fa-times-circle"></i></button></li>`);
}
});
});
}
function waitAndUpdate() {
if (noWaiting > 0) {
// if we are waiting on api responces, call this function in 1 seccond
setTimeout(waitAndUpdate, 1000);
} else {
// update all the dropdowns/ standards explore box (calling on subject
// will suffice since it will necisarily update sub-subject)
$('.rda_metadata .subject select').change();
initStandards();
initTypeahead();
}
}
// given a subject name, returns the portion of the min_tree applicable
function getSubject(subjectText) {
const num = Object.keys(minTree).find((x) => minTree[x].name === subjectText);
return minTree[num];
}
// given a subsubject name and an array of children, data, return the
// applicable child
function getSubSubject(subsubjectText, data) {
const child = Object.keys(data).find((x) => data[x].name === subsubjectText);
return data[child];
}
function updateSaveStatus(group) {
// update save/autosave status
group.next('form').find('fieldset input').change();
}
// change sub-subjects and standards based on selected subject
$('.rda_metadata').on('change', '.subject select', (e) => {
const target = $(e.currentTarget);
const group = target.closest('.rda_metadata');
const subSubject = group.find('.sub-subject select');
const subjectText = target.find(':selected').text();
// find subject in min_tree
const subject = getSubject(subjectText);
// check to see if this object has no children(and thus it's own standards)
if (subject.children.length === 0) {
// hide sub-subject since there's no data for it
subSubject.closest('div').hide();
// update the standards display selector
$('.rda_metadata .sub-subject select').change();
} else {
// show the sub-subject incase it was previously hidden
subSubject.closest('div').show();
// update the sub-subject display selector
subSubject.find('option').remove();
subject.children.forEach((child) => {
$('<option />', { value: child.name, text: child.name }).appendTo(subSubject);
});
// once we have updated the sub-standards, ensure the standards displayed
// get updated as well
$('.rda_metadata .sub-subject select').change();
}
});
// change standards based on selected sub-subject
$('.rda_metadata').on('change', '.sub-subject select', (e) => {
const target = $(e.currentTarget);
const group = target.closest('.rda_metadata');
const subject = group.find('.subject select');
const subSubject = group.find('.sub-subject select');
const subjectText = subject.find(':selected').text();
const subjectData = getSubject(subjectText);
const standards = group.find('.browse-standards-border');
let standardsData;
if (subjectData.children.length === 0) {
// update based on subject's standards
standardsData = subjectData.standards;
} else {
// update based on sub-subject's standards
const subsubjectText = subSubject.find(':selected').text();
standardsData = getSubSubject(subsubjectText, subjectData.children).standards;
}
// clear list of standards
standards.empty();
// update list of standards
Object.keys(standardsData).forEach((num) => {
const standard = descriptions[standardsData[num]];
standards.append(`<div style="background-color:#EAEAEA;border-radius:3px"><strong>${standard.title}</strong><div style="float:right"><button class="btn btn-primary select_standard" data-standard="${standardsData[num]}">Add Standard</button></br></div><p>${standard.description}</p></div>`);
});
});
// when 'Add Standard' button next to the search is clicked, we need to add
// this to the user's selected list of standards.
// update the data and val of hidden standards field in form
$('.rda_metadata').on('click', '.select_standard_typeahead', (e) => {
const target = $(e.currentTarget);
const group = target.closest('.rda_metadata');
const selected = group.find('ul.typeahead li.active');
const selectedStandards = group.find('.selected_standards .list');
// the title of the standard
const standardTitle = selected.data('value');
// need to find the standard
let standard;
Object.keys(descriptions).forEach((standardId) => {
if (descriptions[standardId].title === standardTitle) {
standard = standardId;
}
});
selectedStandards.append(`<li class="${standard}">${descriptions[standard].title}<button class="remove-standard"><i class="fas fa-times-circle"></i></button></li>`);
const formStandards = group.next('form').find('#standards');
// get the data for selected standards from the data attribute 'standard'
// of the hidden field #standards within the answer form
let frmStdsDat = formStandards.data('standard');
// need to init data object for first time
if (typeof frmStdsDat === 'undefined') {
frmStdsDat = {};
}
// init the key to standard id and value to standard.
// NOTE: is there any point in storing the title or description here?
// storing the title could make export easier as we wolnt need to query api
// but queries to the api would be 1 per-standard if we dont store these
frmStdsDat[standard] = descriptions[standard].title;
// update data value
formStandards.data('standard', frmStdsDat);
// update input value
formStandards.val(JSON.stringify(frmStdsDat));
updateSaveStatus(group);
});
// when a 'Add standard' button is clicked, we need to add this to the user's
// selected list of standards
// update the data and val of hidden standards field in form
$('.rda_metadata').on('click', '.select_standard', (e) => {
const target = $(e.currentTarget);
const group = target.closest('.rda_metadata');
const selectedStandards = group.find('.selected_standards .list');
// the identifier for the standard which was selected
const standard = target.data('standard');
// append the standard to the displayed list of selected standards
selectedStandards.append(`<li class="${standard}">${descriptions[standard].title}<button class="remove-standard"><i class="fas fa-times-circle"></i></button></li>`);
const formStandards = group.next('form').find('#standards');
// get the data for selected standards from the data attribute 'standard'
// of the hidden field #standards within the answer form
let frmStdsDat = formStandards.data('standard');
// need to init data object for first time
if (isUndefined(frmStdsDat)) {
frmStdsDat = {};
}
// init the key to standard id and value to standard.
frmStdsDat[standard] = descriptions[standard].title;
// update data value
formStandards.data('standard', frmStdsDat);
// update input value
formStandards.val(JSON.stringify(frmStdsDat));
updateSaveStatus(group);
});
// when a 'Remove Standard' button is clicked, we need to remove this from the
// user's selected list of standards. Additionally, we need to remove the
// standard from the data/val fields of standards in hidden form
$('.rda_metadata').on('click', '.remove-standard', (e) => {
const target = $(e.currentTarget);
const group = target.closest('.rda_metadata');
const listedStandard = target.closest('li');
const standardId = listedStandard.attr('class');
// remove the standard from the list
listedStandard.remove();
// update the data for the form
const formStandards = group.next('form').find('#standards');
const frmStdsDat = formStandards.data('standard');
delete frmStdsDat[standardId];
// update data value
formStandards.data('standard', frmStdsDat);
// update input value
formStandards.val(JSON.stringify(frmStdsDat));
updateSaveStatus(group);
});
// show the add custom standard div when standard not listed clicked
$('.rda_metadata').on('click', '.custom-standard', (e) => {
e.preventDefault();
const target = $(e.currentTarget);
const group = target.closest('.rda_metadata');
const addStandardDiv = $(group.find('.add-custom-standard'));
addStandardDiv.show();
});
// when this button is clicked, we add the typed standard to the list of
// selected standards
$('.rda_metadata').on('click', '.submit_custom_standard', (e) => {
e.preventDefault();
const target = $(e.currentTarget);
const group = target.closest('.rda_metadata');
const selectedStandards = group.find('.selected_standards .list');
const standardName = group.find('.custom-standard-name').val();
selectedStandards.append(`<li class="${standardName}">${standardName}<button class="remove-standard"><i class="fas fa-times-circle"></i></button></li>`);
const formStandards = group.next('form').find('#standards');
// get the data for selected standards from the data attribute 'standard'
// of the hidden field #standards within the answer form
let frmStdsDat = formStandards.data('standard');
// need to init data object for first time
if (typeof frmStdsDat === 'undefined') {
frmStdsDat = {};
}
// init the key to standard id and value to standard.
frmStdsDat[standardName] = standardName;
// update data value
formStandards.data('standard', frmStdsDat);
// update input value
formStandards.val(JSON.stringify(frmStdsDat));
updateSaveStatus(group);
});
function initMetadataQuestions() {
// find all elements with rda_metadata div
$('.rda_metadata').each((idx, el) => {
// $(this) is the element
const sub = $(el).find('.subject select');
// var sub_subject = $(this).find(".sub-subject select");
Object.keys(minTree).forEach((num) => {
$('<option />', { value: minTree[num].name, text: minTree[num].name }).appendTo(sub);
});
});
waitAndUpdate();// $(".rda_metadata .subject select").change();
}
// callback from url+subject-index
// define api_tree and call to initMetadataQuestions
function subjectCallback(data) {
// remove unused standards/substandards
cleanTree(data);
// initialize the dropdowns/selected standards for the page
initMetadataQuestions();
}
// callback from get request to rda_api_address
// define url and make a call to url+subject-index
function urlCallback(data) {
// init url
({ url } = data);
// get api_tree structure from api
$.ajax({
url: `${url}subject-index`,
type: 'GET',
crossDomain: true,
dataType: 'json',
}).done((result) => {
subjectCallback(result);
});
}
// get the url we will be using for the api
// only do this if page has an rda_metadata div
if ($('.rda_metadata').length) {
$.getJSON('/question_formats/rda_api_address', urlCallback);
}
// when the autosave or save action occurs, this clears out both the list of
// selected standards, and the selectors for new standards, as it re-renders
// the partial. This "autosave" event is triggered by that JS in order to
// allow us to know when the save has happened and re-init the question
$('.rda_metadata').on('autosave', (e) => {
e.preventDefault();
// re-initialize the metadata question
initMetadataQuestions();
});
});
| DigitalCurationCentre/roadmap | app/javascript/src/answers/rdaMetadata.js | JavaScript | mit | 16,053 |
module.exports = require('./consistent_hashing');
| shawnvan/coffee-server-demo | node_modules/consistent-hashing/lib/index.js | JavaScript | mit | 50 |
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
| lagerjs/lager | demo/express-app/app.js | JavaScript | mit | 1,216 |
/* ==========================================================
* autocomplete.js
* Deal with the Typeahead.js/Bloodhound library to build the search field autocomplete
*
* Author: Yann, [email protected]
* Date: 2014-05-01 14:23:18
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
========================================================== */
(function($, data) {
'use strict';
var $searchFields = $('.form-search .search-field');
if (data) {
// Init the Bloodhound suggestion engine
var bloodhound = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: $.map(data, function(state) { return { value: state }; })
});
bloodhound.initialize();
// Init Typeahead on search-fields
$searchFields.typeahead({
hint: true,
highlight: true,
minLength: 1,
},
{
name: 'search',
displayKey: 'value',
source: bloodhound.ttAdapter()
});
}
// Insert the icons
$searchFields.after('<span class="icon icon--close" data-form-search-clear></span>');
$('.form-search').append('<button class="icon icon--search icon--before"></button>');
$('body').on('click', '[data-form-search-clear]', function () {
$('#search-field').val('').focus(); // clear search field and refocus it
});
}) (jQuery, (typeof searchData === 'undefined' ? false : searchData));
/* ==========================================================
* carousel.js
* Carousel helper
*
* Author: Yann, [email protected]
* Date: 2014-05-15 13:55:53
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
========================================================== */
(function($) {
'use strict';
$(window).load(function () {
carouselInit(jQuery);
});
$(window).resize(function () {
carouselInit(jQuery);
});
// slideshow counter
var slideshow_total = $('.carousel-slideshow .item').length;
$('#carousel-total').text(slideshow_total);
$('.carousel-slideshow').on('slid.bs.carousel', function () {
var carouselData = $(this).data('bs.carousel');
var currentIndex = carouselData.getItemIndex(carouselData.$element.find('.item.active'));
var total = carouselData.$items.length;
var text = (currentIndex + 1);
$('#carousel-index').text(text);
$('#carousel-total').text(total);
});
}) (jQuery);
function carouselInit($) {
'use strict';
var $carousel = $('.carousel:not(.carousel-slideshow)');
$('.carousel .item:first-child').addClass('first');
$('.carousel .item:last-child').addClass('last');
$('.carousel').each(function() {
disableControl($(this));
});
$('.carousel').on('slid.bs.carousel', function () {
disableControl($(this));
});
if($carousel) {
$carousel.each(function () {
var biggestHeight = 0,
titleHeight = $(this).find('.item.active h3:first-child').height(),
imgHeight = $(this).find('.item.active .carousel-img').height();
$(this).find('.carousel-indicators, .carousel-control').css('top', titleHeight + imgHeight + 50);
$(this).find('.item').each(function () {
if ($(this).height() >= biggestHeight) {
biggestHeight = $(this).height();
}
});
$(this).find('.item').height(biggestHeight);
});
}
}
function disableControl(element) {
'use strict';
if (element.find('.first').hasClass('active')) {
element.find('.left').addClass('disabled').attr('aria-disabled', 'true');
} else {
element.find('.left').removeClass('disabled').attr('aria-disabled', 'false');
}
if (element.find('.last').hasClass('active')) {
element.find('.right').addClass('disabled').attr('aria-disabled', 'true');
} else {
element.find('.right').removeClass('disabled').attr('aria-disabled', 'false');
}
}
/* ==========================================================
* collapse.js
* Add class when nav collapse is open
*
* Author: Yann, [email protected]
* Date: 2014-05-06
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
========================================================== */
(function($) {
'use strict';
// Normal Collapse
$('.collapse:not(tbody)').on('show.bs.collapse', function () {
$(this)
.prev()
.addClass('active icon--root')
.removeClass('icon--greater')
.attr({
'aria-selected': 'true',
'aria-expanded': 'true'
});
});
$('.collapse:not(tbody)').on('hide.bs.collapse', function () {
$(this)
.prev()
.removeClass('active icon--root')
.addClass('icon--greater')
.attr( {
'aria-selected': 'false',
'aria-expanded': 'false'
});
});
// Table Collapse
$('tbody.collapse').on('show.bs.collapse', function () {
$(this)
.prev().find('[data-toggle=collapse]')
.addClass('active')
.attr({
'aria-selected': 'true',
'aria-expanded': 'true'
});
});
$('tbody.collapse').on('hide.bs.collapse', function () {
$(this)
.prev().find('[data-toggle=collapse]')
.removeClass('active')
.attr({
'aria-selected': 'false',
'aria-expanded': 'false'
});
});
}) (jQuery);
/* ==========================================================
* drilldown.js
* Drilldown plugin scripts. For page-list-nav element
*
* Author: Toni Fisler, [email protected]
* Date: 2014-05-30 09:02:09
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
========================================================== */
(function($) {
'use strict';
var options = {
event: 'click', // * View note below
selector: 'a', // * View note below
speed: 100,
cssClass: {
container: 'drilldown-container',
root: 'nav-page-list',
sub: 'drilldown-sub',
back: 'drilldown-back'
}
};
$('.drilldown').drilldown(options);
}) (jQuery);
/* ==========================================================
* global-nav.js
* Global Navigation syripts
*
* Author: Toni Fisler, [email protected]
* Date: 2014-05-27 16:36:15
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
========================================================== */
(function($) {
'use strict';
// Handle scroll to position nav as fixed
var top = 36;
$(window).scroll(function () {
var y = $(this).scrollTop();
if (y >= top) {
if (!$('.nav-mobile').hasClass('fixed')) {
$('.nav-mobile').addClass('fixed')
.after('<div class="nav-mobile-spacer" id="spacer" style="height:36px;"></div>');
}
}
else {
if ($('.nav-mobile').hasClass('fixed')) {
$('.nav-mobile').removeClass('fixed');
$('#spacer').remove();
}
}
});
}) (jQuery);
// OUTLINE.JS
// https://github.com/lindsayevans/outline.js
//
// Based on http://www.paciellogroup.com/blog/2012/04/how-to-remove-css-outlines-in-an-accessible-manner/
//
// Hide outline on mouse interactions
// Show it on keyboard interactions
(function(doc){
'use strict';
var styleElement = doc.createElement('STYLE'),
domEvents = 'addEventListener' in doc,
addListener = function(type, callback){
// Basic cross-browser event handling
if (domEvents) {
doc.addEventListener(type, callback);
} else {
doc.attachEvent('on' + type, callback);
}
},
setCSS = function(cssText){
!!styleElement.styleSheet ? styleElement.styleSheet.cssText = cssText : styleElement.innerHTML = cssText;
};
doc.getElementsByTagName('HEAD')[0].appendChild(styleElement);
// Using mousedown instead of mouseover, so that previously focused elements don't lose focus ring on mouse move
addListener('mousedown', function(){
setCSS(':focus{outline:0!important}::-moz-focus-inner{border:0!important}');
});
addListener('keydown', function(){
setCSS('');
});
})(document);
/* ==========================================================
* print.js
* Add print preview windows
*
* Author: Yann, [email protected]
* Date: 2015-02-02
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
========================================================== */
(function($) {
'use strict';
// Initialization
$.fn.printPreview = function() {
return this;
};
$.printPreview = {
printPreview: function(element) {
var $body = $('body'),
$container = $('.container-main'),
footnoteLinks = "",
linksIndex = 0;
$body.find('.nav-mobile, .drilldown, .nav-main, .header-separator, .nav-service, .nav-lang, .form-search, .yamm--select, header > div:first-child, footer, .alert, .icon--print, .social-sharing, form, .nav-process, .carousel-indicators, .carousel-control, .breadcrumb, .pagination-container').remove();
// if an element is passed, we want it to be the only thing to print out
if (element) {
element = $('[data-print=' + element + ']').clone(); // clone to fix issue with IE render
var header = $('header').clone(), // clone to fix issue with IE render
title = element.attr('data-title') ? '<h1>' + element.attr('data-title') + '</h1>' : '';
$container.addClass('print-element').html('').append(header, title, element);
}
$body.addClass('print-preview');
$container.prepend('<div class="row" id="print-settings">'+
'<div class="col-sm-12">'+
'<nav class="pagination-container clearfix">'+
'<span class="pull-left">'+
'<input type="checkbox" id="footnote-links"> '+
'<label for="footnote-links">Links as footnotes</label>'+
'</span>'+
'<ul class="pull-right">'+
'<li>'+
'<button id="print-button" title="print" class="btn"><span class="icon icon--print"></span></button>'+
' '+
'<button id="close-button" title="close" class="btn btn-secondary"><span class="icon icon--close"></span></button>'+
'</li>'+
'</ul>'+
'</nav>'+
'</div>'+
'</div>');
$('#print-button').click(function () {
$.printPreview.printProcess();
});
$('#close-button').click(function () {
$.printPreview.printClose();
});
$('a').not('.access-keys a').each(function () {
var target = $(this).attr('href');
target = String(target);
if (target !== "undefined" && target.indexOf("http") === 0) {
linksIndex ++;
footnoteLinks += '<li>'+target+'</li>';
$('<sup class="link-ref">('+linksIndex+')</sup>').insertAfter(this);
}
});
$('#footnote-links').change(function(){
if (this.checked) {
$container.append('<div id="footnote-links-wrapper" class="row footnote-links-wrapper">'+
'<div class="col-sm-12">'+
'<h3>Page Links</h3><hr>'+
'<ol>'+
footnoteLinks+
'</ol>'+
'</div>'+
'</div>');
$body.addClass('print-footnotes');
} else {
$('#footnote-links-wrapper').remove();
$body.removeClass('print-footnotes');
}
});
},
printProcess: function() {
window.print();
},
printClose: function() {
window.location.reload();
}
};
}) (jQuery);
/* ==========================================================
* rich-menu.js
* Add overlay when openning a rich yamm menu and define open/close events
*
* Author: Yann Gouffon, [email protected]
* Date: 2014-04-30 11:48:48
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
=========================================================== */
(function($) {
'use strict';
// Keep jQuery object in variables
var $yamm = $('.yamm'),
$yammClose = $('.yamm-close, .yamm-close-bottom'),
$dropdown = $('.yamm .dropdown'),
$dropdownToggle = $('.yamm .dropdown-toggle');
// Toggle dropdown and fix z-index errors
$yamm.each(function () {
var $that = $(this);
$that.on('click', '.dropdown-toggle', function () {
if (!$(this).parent().hasClass('open')){
var dropdownHeight = $(window).height() - 49;
$that.find('.drilldown-container').height( dropdownHeight );
}
});
});
$dropdownToggle.on('click', function() {
$(this).parents($dropdown).trigger('get.hidden');
});
$dropdown.on({
"shown.bs.dropdown": function() { this.closable = false; },
"get.hidden": function() { this.closable = true; }
});
$('.dropdown').on('show.bs.dropdown', function () {
$dropdown.removeClass('open');
$yamm.removeClass('nav-open');
$(this).parents($yamm).addClass('nav-open');
});
$dropdown.on('hide.bs.dropdown', function () {
// only remove the nav-open class if effectively closing dropdown
if (this.closable) {
$yamm.removeClass('nav-open');
}
return this.closable;
});
$(document).on('click', function(e) {
// hide dropdown if dropdown is open and target is not in dropdown
if ($('.dropdown.open').length > 0 && $(e.target).parents('.dropdown').length === 0) {
$('.dropdown.open .dropdown-toggle').trigger('click');
}
});
// Trigger close yamm menu
$dropdown.each(function () {
var $that = $(this);
$that.find($yammClose).click( function (e) {
e.preventDefault();
$that.find($dropdownToggle).trigger("click");
});
});
}) (jQuery);
/* ==========================================================
* select.js
* Scripts handling `select` elements
*
* Author: Toni Fisler, [email protected]
* Date: 2014-04-30 10:20:33
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
========================================================== */
(function($) {
'use strict';
$(document).ready(function(){
$('select').chosen({
disable_search_threshold: 10
});
});
}) (jQuery);
/* ==========================================================
* shame.js
* DOM rewritting on mobile, issue #160
*
* Author: Yann, [email protected]
* Date: 2014-06-18 15:57:23
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
========================================================== */
(function($) {
'use strict';
$(document).ready(function () {
var id;
var isCarouselified = false;
var isCollapsified = false;
carouselify();
collapsify();
$(window).resize(function() {
clearTimeout(id);
id = setTimeout(resizeLauncher, 500);
});
function resizeLauncher() {
carouselify();
collapsify();
}
function carouselify() {
var $tabFocus = $('.tab-focus'),
focusIndex = 0;
if($tabFocus && $(window).width() <= 767 && !isCarouselified ) {
isCarouselified = true;
$tabFocus.each(function () {
var $that = $(this),
itemIndex = -1;
focusIndex += 1;
$that.attr('id', 'tab-focus-'+focusIndex);
$that.next('.nav-tabs').hide();
// Prevent those mobile-only carousels from riding automatically by setting interval to 0
$that.addClass('carousel slide').removeClass('tab-content tab-border').attr('data-interval', 0);
$that.wrapInner('<div class="carousel-inner"></div>');
$that.prepend('<ol class="carousel-indicators"></ol>');
$that.find('.tab-pane').each(function () {
itemIndex += 1;
$(this).removeClass('tab-pane in active').addClass('item');
$that.find('.carousel-indicators').append('<li data-target="#tab-focus-' + focusIndex + '" data-slide-to="' + itemIndex + '"></li>');
});
$that.find('.item:first').addClass('active');
$that.find('.carousel-indicators li:first-child').addClass('active');
$that.append('<a class="left carousel-control icon icon--before icon--less" href="#tab-focus-' + focusIndex + '" data-slide="prev"></a><a class="right carousel-control icon icon--before icon--greater" href="#tab-focus-' + focusIndex + '" data-slide="next"></a>');
});
}
else if($tabFocus && $(window).width() > 767 && isCarouselified) {
isCarouselified = false;
$tabFocus.each(function () {
var $that = $(this);
focusIndex -= 1;
$that.attr('id', '');
$that.next('.nav-tabs-focus').css('display', 'flex'); // we can't use .show() because it should be a flex wrapper
$that.removeClass('carousel slide').addClass('tab-content tab-border');
$that.find('ol.carousel-indicators').remove();
$that.find('.item').each(function () {
$(this).addClass('tab-pane').removeClass('item');
$(this).css('height', 'auto');
});
$that.find('.tab-pane:first-child').addClass('active in');
if ( $that.find('.tab-pane').parent().hasClass('carousel-inner') ) {
$that.find('.tab-pane').unwrap();
}
$that.find('.carousel-control').remove();
});
}
}
function collapsify() {
var $navTab = $('.nav-tabs:not(.focus)'),
$collapsify = $('.collapsify'),
linkIndex = 0;
if($navTab && $(window).width() <= 767 && !isCollapsified ) {
isCollapsified = true;
$navTab.not('.tab-focus').each(function (){
var $that = $(this);
$that.removeClass('nav-tabs').addClass('collapsify');
$that.next('.tab-content').hide();
$that.find('a').each(function (){
var $target = $(this).attr('href');
linkIndex += 1;
$(this).unwrap();
$('<div class="collapse" id="collapse-' + linkIndex + '">' + $($target).html() + '</div>').insertAfter(this);
$(this).attr('data-toggle', 'collapse');
$(this).attr('data-target', '#collapse-' + linkIndex);
$(this).addClass('collapse-closed');
$(this).click(function(){
$(this).toggleClass('collapse-closed');
});
});
//$that.find('a:first-child').removeClass('collapse-closed').next('.collapse').addClass('in');
});
}
else if($collapsify && $(window).width() > 767 && isCollapsified) {
isCollapsified = false;
$collapsify.each(function (){
var $that = $(this);
$that.addClass('nav-tabs').removeClass('collapsify');
$that.next('.tab-content').show();
$that.find('a').each(function (){
linkIndex -= 1;
$(this).wrap('<li></li>');
$(this).parent().next('.collapse').remove();
$(this).attr('data-toggle', 'tab');
$(this).attr('data-target', '');
$(this).removeClass('collapse-closed');
});
$that.find('li a').each(function () {
var $tabTarget = $(this).attr('href');
if($($tabTarget).hasClass('active')){
$(this).parent().addClass('active');
}
});
});
}
}
});
}) (jQuery);
/* ==========================================================
* subnavigation.js
* Sub-navigation scripts, handles mainly how the nav-page-list behaves on small
* screens
*
* Author: Toni Fisler, [email protected]
* Date: 2014-09-24 10:18:19
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
========================================================== */
(function($) {
'use strict';
subNavInit(jQuery);
$(window).resize(function () {
subNavInit(jQuery);
});
$('a[href=#collapseSubNav]').on('click', function() {
$(this).attr('aria-expanded', ($(this).attr('aria-expanded') === 'true' ? 'false' : 'true') );
});
}) (jQuery);
function subNavInit($) {
'use strict';
var $drilldown = $('.drilldown[class*=col-]');
if ($(window).width() <= 767 && !$drilldown.hasClass('collapse-enabled')) {
$drilldown
.addClass('collapse-enabled')
.find('.drilldown-container')
.addClass('collapse')
.attr('id', 'collapseSubNav');
} else if ($(window).width() > 767 && $drilldown.hasClass('collapse-enabled')) {
$drilldown
.removeClass('collapse-enabled')
.find('.drilldown-container')
.removeClass('collapse in')
.attr('id', '')
.css({
'height': 'auto'
});
}
}
/* ==========================================================
* tablesorter.js
* Control tablesort from markup
*
* Author: Simon Perdrisat, [email protected]
* Date: 2014-05-01 11:11:33
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
========================================================== */
(function($) {
'use strict';
$('.table-sort').tablesorter();
}) (jQuery);
/* ==========================================================
* tabs.js
* JS for the tabs and tab-focus elements
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
========================================================== */
(function($) {
'use strict';
/**
* @constructor
* @param {Object} domNode
*/
function TabFocus(element) {
this.$wrapper = $(element).parent();
this.domNodes = '.tab-focus, .nav-tabs-focus';
this.delay = 3000;
this.playing = null;
this.interval = null;
this.$wrapper
.on('click', '.nav-tabs-focus', function() {
this.pause(null, true);
}.bind(this))
.on('click', '.tab-focus-control', function() {
if (this.playing) {
this.pause(null, true);
} else {
this.play(null, true);
}
}.bind(this));
this.play(null, true);
}
TabFocus.prototype = {
addListeners: function() {
this.$wrapper
.on('mouseenter.tabfocus focus.tabfocus', this.domNodes, this.pause.bind(this))
.on('mouseleave.tabfocus blur.tabfocus', this.domNodes, this.play.bind(this));
},
removeListeners: function() {
this.$wrapper
.off('mouseenter.tabfocus focus.tabfocus', this.domNodes)
.off('mouseleave.tabfocus blur.tabfocus', this.domNodes);
},
play: function(event, startListening) {
if (this.interval) {
clearInterval(this.interval);
}
this.interval = setInterval(this.slide.bind(this), this.delay);
if (startListening) {
this.playing = true;
this.addListeners();
this.$wrapper.find('.tab-focus-control .icon').removeClass('icon--play').addClass('icon--pause');
}
},
pause: function(event, stopListening) {
clearInterval(this.interval);
if (stopListening) {
this.playing = false;
this.removeListeners();
this.$wrapper.find('.tab-focus-control .icon').removeClass('icon--pause').addClass('icon--play');
}
},
slide: function() {
var $nav = this.$wrapper.find('.nav-tabs-focus');
// If the nav is hidden, it means the focus has been changed for a carousel (mobile)
// We don’t want to slide automatically anymore
if ($nav.is(':hidden')) {
return this.pause(null, true);
}
if ($nav.find('> li').length) {
var tabs = this.$wrapper.find('.nav-tabs-focus > li'),
activeTab = tabs.filter('.active'),
nextTab = activeTab.next('li'),
newTab = nextTab.length ? nextTab.find('a') : tabs.eq(0).find('a');
newTab.tab('show');
}
}
};
$.fn.tabFocus = function() {
return this.each(function() {
if (!$.data(this, 'TabFocus')) {
$.data(this, 'TabFocus', new TabFocus(this));
}
});
};
$('.tab-focus').tabFocus();
})(jQuery);
/* ==========================================================
* treecrumb.js
* Change icon class to change the caret direction
*
* Author: Yann Gouffon, [email protected]
* Date: 2014-05-01 11:11:33
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
========================================================== */
(function($) {
'use strict';
$('.treecrumb').each(function() {
var $that = $(this);
$that.on('hide.bs.dropdown', function() {
$that.find('.dropdown-toggle span').removeClass('icon--bottom');
$that.find('.dropdown-toggle span').addClass('icon--right');
});
$that.on('show.bs.dropdown', function(e) {
var target = e.relatedTarget;
$that.find('.dropdown-toggle span').removeClass('icon--bottom');
$that.find('.dropdown-toggle span').addClass('icon--right');
$(target).find('span').removeClass('icon--right');
$(target).find('span').addClass('icon--bottom');
});
});
}) (jQuery);
| eonum/drg-search | vendor/assets/javascripts/styleguide.js | JavaScript | mit | 24,803 |
Xktta.I18n = function(locale, translations){
this.translations[locale] = translations || {};
return this;
}
Xktta.afterInit.push(function(){
var __this__ = Xktta;
eval.call(__this__.window, "var I18n;");
I18n = {
locale: 'en',
translate: function(path, params){
var translation = path;
var translations = __this__.translations[I18n.locale] || {};
path.split('.').forEach(function(key){
translations = translations[key] || {};
});
if(typeof translations === 'string'){
translation = translations;
params = params || {};
translation = translation.interpolate(params, '%');
}else if(typeof translations === 'object' && translations.constructor.name === 'Array'){
translation = translations;
} else {
translation = '#{locale}.#{path}'.interpolate({locale: I18n.locale, path: path});
}
return translation;
},
localize: function(value, options){
options = options || {};
var format = options.format || 'default';
var dateType = options.dateType || 'date';
var formatted = value;
if(typeof value === 'object' && value.constructor.name === 'Date'){
var dayWeak = value.getDay();
var month = value.getMonth() + 1;
var dayMonth = value.getDate();
var year = value.getFullYear();
var hours = value.getHours();
var minutes = value.getMinutes();
var seconds = value.getSeconds();
var meridiem = hours < 12 ? 'am' : 'pm';
var zone = value.toString().match(/([A-Z]+[\+-][0-9]+.*)/)[1];
formatted = __this__.translations[I18n.locale][dateType].formats[format];
var formatBy = {
function: function(){
formatted = formatted(value);
},
string: function(){
var to = {
date: function(){
formatted = formatted
.interpolate({
a: I18n.t('date.abbrDayNames')[dayWeak],
A: I18n.t('date.dayNames')[dayWeak],
m: new String(month + 100).toString().substr(1),
b: I18n.t('date.abbrMonthNames')[month],
B: I18n.t('date.monthNames')[month],
d: new String(dayMonth + 100).toString().substr(1),
Y: year
}, '%', false);
},
time: function(){
formatted = formatted
.interpolate({
h: new String( (hours || 24) - 12 + 100 ).toString().substr(1),
H: new String(hours + 100).toString().substr(1),
M: new String(minutes + 100).toString().substr(1),
S: new String(seconds + 100).toString().substr(1),
p: I18n.t(['time', meridiem].join('.')),
z: zone
}, '%', false);
},
datetime: function(){
this.date();
this.time();
}
}
to[dateType]();
}
}
formatBy[typeof formatted]();
}
else if(typeof value === 'number'){
var functionFormat = __this__.translations[I18n.locale].integer.formats[format];
if(/\./.test(value) || options.forceDecimal){
functionFormat = __this__.translations[I18n.locale].decimal.formats[format];
}
formatted = functionFormat(value);
}
else if(typeof value === 'boolean'){
formatted = __this__.translations[I18n.locale].logic.formats[format][value];
}
return formatted;
}
}
I18n.t = I18n.translate
I18n.l = I18n.localize
}); | juniormesquitadandao/xikitita | app/models/i18n.js | JavaScript | mit | 3,738 |
import Ember from 'ember';
export default Ember.Handlebars.template(function anonymous(Handlebars,depth0,helpers,partials,data) {
this.compilerInfo = [4,'>= 1.0.0'];
helpers = this.merge(helpers, Ember.Handlebars.helpers); data = data || {};
var buffer = '', stack1, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, self=this;
function program1(depth0,data) {
var buffer = '', helper, options;
data.buffer.push("\n <div class=\"row\">\n <div class=\"col-md-4\"> <span class=\"glyphicon glyphicon-user\"></span> ");
data.buffer.push(escapeExpression((helper = helpers['link-to'] || (depth0 && depth0['link-to']),options={hash:{},hashTypes:{},hashContexts:{},contexts:[depth0,depth0,depth0],types:["ID","STRING","ID"],data:data},helper ? helper.call(depth0, "user.name", "users.user", "user", options) : helperMissing.call(depth0, "link-to", "user.name", "users.user", "user", options))));
data.buffer.push("</div>\n </div>\n ");
return buffer;
}
data.buffer.push("<h2>Buddies</h2>\n\n<div class=\"container\">\n ");
stack1 = helpers.each.call(depth0, "user", "in", "content", {hash:{},hashTypes:{},hashContexts:{},inverse:self.noop,fn:self.program(1, program1, data),contexts:[depth0,depth0,depth0],types:["ID","ID","ID"],data:data});
if(stack1 || stack1 === 0) { data.buffer.push(stack1); }
data.buffer.push("\n\n\n</div>\n");
return buffer;
});
| alicht/buddybuddy | public/tmp/tree_merger-tmp_dest_dir-KPkHvOkI.tmp/buddybuddy/templates/users/index.js | JavaScript | mit | 1,413 |
exports.defaultType = require('ot-json0').type;
exports.map = {};
exports.register = function(type) {
if (type.name) exports.map[type.name] = type;
if (type.uri) exports.map[type.uri] = type;
};
exports.register(exports.defaultType);
| share/livedb | lib/types.js | JavaScript | mit | 242 |
/**
* Copyright 2012-2017, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
module.exports = require('../src/traces/heatmapgl');
| chethanjjj/gentelella | vendors/plotlyjs/lib/heatmapgl.js | JavaScript | mit | 261 |
require('can-view-import/can-view-import_test');
| tracer99/canjs | view/import/import_test.js | JavaScript | mit | 49 |
import COMMAND from '../../../session/command';
import FileListWrapper from './file-list-wrapper';
import nativeMethods from '../native-methods';
import transport from '../../transport';
import settings from '../../settings';
import * as Browser from '../../utils/browser';
import * as HiddenInfo from './hidden-info';
import SHADOW_UI_CLASSNAME from '../../../shadow-ui/class-name';
import Promise from 'pinkie';
// NOTE: https://html.spec.whatwg.org/multipage/forms.html#fakepath-srsly.
const FAKE_PATH_STRING = 'C:\\fakepath\\';
const UPLOAD_IFRAME_FOR_IE9_ID = 'uploadIframeForIE9' + SHADOW_UI_CLASSNAME.postfix;
export default class UploadInfoManager {
constructor (shadowUI) {
this.shadowUI = shadowUI;
this.uploadInfo = [];
}
static _getFileListData (fileList) {
var data = [];
for (var i = 0; i < fileList.length; i++)
data.push(fileList[i].base64);
return data;
}
static _getUploadIframeForIE9 () {
var uploadIframe = nativeMethods.querySelector.call(document, '#' + UPLOAD_IFRAME_FOR_IE9_ID);
if (!uploadIframe) {
uploadIframe = nativeMethods.createElement.call(document, 'iframe');
nativeMethods.setAttribute.call(uploadIframe, 'id', UPLOAD_IFRAME_FOR_IE9_ID);
nativeMethods.setAttribute.call(uploadIframe, 'name', UPLOAD_IFRAME_FOR_IE9_ID);
uploadIframe.style.display = 'none';
nativeMethods.appendChild.call(this.shadowUI.getRoot(), uploadIframe);
}
return uploadIframe;
}
_loadFileListDataForIE9 (input) {
return Promise(resolve => {
var form = input.form;
if (form && input.value) {
var sourceTarget = form.target;
var sourceActionString = form.action;
var sourceMethod = form.method;
var uploadIframe = UploadInfoManager._getUploadIframeForIE9();
var loadHandler = () => {
var fileListWrapper = new FileListWrapper([JSON.parse(uploadIframe.contentWindow.document.body.innerHTML)]);
uploadIframe.removeEventListener('load', loadHandler);
resolve(fileListWrapper);
};
uploadIframe.addEventListener('load', loadHandler);
form.action = settings.get().ie9FileReaderShimUrl + '?input-name=' + input.name + '&filename=' +
input.value;
form.target = UPLOAD_IFRAME_FOR_IE9_ID;
form.method = 'post';
nativeMethods.formSubmit.call(form);
form.action = sourceActionString;
form.target = sourceTarget;
form.method = sourceMethod;
}
else
resolve(new FileListWrapper([]));
});
}
static formatValue (fileNames) {
var value = '';
fileNames = typeof fileNames === 'string' ? [fileNames] : fileNames;
if (fileNames && fileNames.length) {
if (Browser.isWebKit)
value = FAKE_PATH_STRING + fileNames[0].split('/').pop();
else if (Browser.isIE9 || Browser.isIE10) {
var filePaths = [];
for (var i = 0; i < fileNames.length; i++)
filePaths.push(FAKE_PATH_STRING + fileNames[i].split('/').pop());
value = filePaths.join(', ');
}
else
return fileNames[0].split('/').pop();
}
return value;
}
static getFileNames (fileList, value) {
var result = [];
if (fileList) {
for (var i = 0; i < fileList.length; i++)
result.push(fileList[i].name);
}
else if (value.lastIndexOf('\\') !== -1)
result.push(value.substr(value.lastIndexOf('\\') + 1));
return result;
}
static loadFilesInfoFromServer (filePaths) {
return transport.asyncServiceMsg({
cmd: COMMAND.getUploadedFiles,
filePaths: typeof filePaths === 'string' ? [filePaths] : filePaths
});
}
static prepareFileListWrapper (filesInfo) {
var errs = [];
var validFilesInfo = [];
for (var i = 0; i < filesInfo.length; i++) {
if (filesInfo[i].err)
errs.push(filesInfo[i]);
else
validFilesInfo.push(filesInfo[i]);
}
return {
errs: errs,
fileList: new FileListWrapper(validFilesInfo)
};
}
static sendFilesInfoToServer (fileList, fileNames) {
return transport.asyncServiceMsg({
cmd: COMMAND.uploadFiles,
data: UploadInfoManager._getFileListData(fileList),
fileNames: fileNames
});
}
clearUploadInfo (input) {
var inputInfo = this.getUploadInfo(input);
if (inputInfo) {
inputInfo.files = new FileListWrapper([]);
inputInfo.value = '';
return HiddenInfo.removeInputInfo(input);
}
return null;
}
getFiles (input) {
var inputInfo = this.getUploadInfo(input);
return inputInfo ? inputInfo.files : new FileListWrapper([]);
}
getUploadInfo (input) {
for (var i = 0; i < this.uploadInfo.length; i++) {
if (this.uploadInfo[i].input === input)
return this.uploadInfo[i];
}
return null;
}
getValue (input) {
var inputInfo = this.getUploadInfo(input);
return inputInfo ? inputInfo.value : '';
}
loadFileListData (input, fileList) {
/*eslint-disable no-else-return */
if (Browser.isIE9)
return this._loadFileListDataForIE9(input);
else if (!fileList.length)
return Promise.resolve(new FileListWrapper([]));
else {
return new Promise(resolve => {
var index = 0;
var fileReader = new FileReader();
var file = fileList[index];
var readedFiles = [];
fileReader.addEventListener('load', e => {
readedFiles.push({
data: e.target.result.substr(e.target.result.indexOf(',') + 1),
blob: file.slice(0, file.size),
info: {
type: file.type,
name: file.name,
lastModifiedDate: file.lastModifiedDate
}
});
if (fileList[++index]) {
file = fileList[index];
fileReader.readAsDataURL(file);
}
else
resolve(new FileListWrapper(readedFiles));
});
fileReader.readAsDataURL(file);
});
}
/*eslint-enable no-else-return */
}
setUploadInfo (input, fileList, value) {
var inputInfo = this.getUploadInfo(input);
if (!inputInfo) {
inputInfo = { input: input };
this.uploadInfo.push(inputInfo);
}
inputInfo.files = fileList;
inputInfo.value = value;
HiddenInfo.addInputInfo(input, fileList, value);
}
}
| georgiy-abbasov/testcafe-hammerhead | src/client/sandbox/upload/info-manager.js | JavaScript | mit | 7,469 |
/* Get Programming with JavaScript
* Listing 12.04
* Guess the random number
*/
var getGuesser = function () {
var secret = Math.floor(Math.random() * 10 + 1);
return function (userNumber) {
if (userNumber === secret) {
return "Well done!";
} else {
return "Unlucky, try again.";
}
};
};
var guess = getGuesser();
/* Further Adventures
*
* 1) Run the program.
*
* 2) Play the game a few times on the console.
* e.g. guess(2)
*
* 3) Change the code so the secret number is
* between 30 and 50.
*
* 4) Test your changes.
*
* CHALLENGE: Create a function called 'between'
* that returns a random whole number between two
* numbers passed as arguments.
*
* e.g. between(1, 5) // 1 <= whole number <= 5
* between(100, 200) // 100 <= whole number <= 200
*
*/ | jrlarsen/GetProgramming | Ch12_Conditions/listing12.04.js | JavaScript | mit | 829 |
(function () {
var totalFactory = function ($resource) {
return $resource("/api/priv/total/");
};
controlCajaApp.factory('totalFactory', ['$resource', totalFactory]);
}()); | froilanq/CursoAngularJS | 10-Configuracion-Cache/client/totalFactory.js | JavaScript | mit | 198 |
/*
** delay_deny
**
** This plugin delays all pre-DATA 'deny' results until the recipients are sent
** and all post-DATA commands until all hook_data_post plugins have run.
** This allows relays and authenticated users to bypass pre-DATA rejections.
*/
exports.hook_deny = function (next, connection, params) {
/* params
** [0] = plugin return value (DENY or DENYSOFT)
** [1] = plugin return message
*/
var pi_name = params[2];
var pi_function = params[3];
// var pi_params = params[4];
var pi_hook = params[5];
var plugin = this;
var transaction = connection.transaction;
// Don't delay ourselves...
if (pi_name == 'delay_deny') return next();
// Load config
var cfg = this.config.get('delay_deny.ini');
var skip;
var included;
if (cfg.main.included_plugins) {
included = cfg.main.included_plugins.split(/[;, ]+/);
} else if (cfg.main.excluded_plugins) {
skip = cfg.main.excluded_plugins.split(/[;, ]+/);
}
// 'included' mode: only delay deny plugins in the included list
if (included && included.length) {
if (included.indexOf(pi_name) === -1 &&
included.indexOf(pi_name + ':' + pi_hook) === -1 &&
included.indexOf(pi_name + ':' + pi_hook + ':' + pi_function) === -1) {
return next();
}
} else if (skip && skip.length) { // 'excluded' mode: delay deny everything except in skip list
// Skip by <plugin name>
if (skip.indexOf(pi_name) !== -1) {
connection.logdebug(plugin, 'not delaying excluded plugin: ' + pi_name);
return next();
}
// Skip by <plugin name>:<hook>
if (skip.indexOf(pi_name + ':' + pi_hook) !== -1) {
connection.logdebug(plugin, 'not delaying excluded hook: ' + pi_hook +
' in plugin: ' + pi_name);
return next();
}
// Skip by <plugin name>:<hook>:<function name>
if (skip.indexOf(pi_name + ':' + pi_hook + ':' + pi_function) !== -1) {
connection.logdebug(plugin, 'not delaying excluded function: ' + pi_function +
' on hook: ' + pi_hook + ' in plugin: ' + pi_name);
return next();
}
}
switch (pi_hook) {
// Pre-DATA connection delays
case 'lookup_rdns':
case 'connect':
case 'ehlo':
case 'helo':
if (!connection.notes.delay_deny_pre) {
connection.notes.delay_deny_pre = [];
}
connection.notes.delay_deny_pre.push(params);
if (!connection.notes.delay_deny_pre_fail) {
connection.notes.delay_deny_pre_fail = {};
}
connection.notes.delay_deny_pre_fail[pi_name] = 1;
return next(OK);
// Pre-DATA transaction delays
case 'mail':
case 'rcpt':
case 'rcpt_ok':
if (!transaction.notes.delay_deny_pre) {
transaction.notes.delay_deny_pre = [];
}
transaction.notes.delay_deny_pre.push(params);
if (!transaction.notes.delay_deny_pre_fail) {
transaction.notes.delay_deny_pre_fail = {};
}
transaction.notes.delay_deny_pre_fail[pi_name] = 1;
return next(OK);
// Post-DATA delays
case 'data':
case 'data_post':
// fall through
default:
// No delays
return next();
}
};
exports.hook_rcpt_ok = function (next, connection, rcpt) {
var plugin = this;
var transaction = connection.transaction;
// Bypass all pre-DATA deny for AUTH/RELAY
if (connection.relaying) {
connection.loginfo(plugin, 'bypassing all pre-DATA deny: AUTH/RELAY');
return next();
}
// Apply any delayed rejections
// Check connection level pre-DATA rejections first
if (connection.notes.delay_deny_pre) {
for (let i=0; i<connection.notes.delay_deny_pre.length; i++) {
let params = connection.notes.delay_deny_pre[i];
return next(params[0], params[1]);
}
}
// Then check transaction level pre-DATA
if (transaction.notes.delay_deny_pre) {
for (let i=0; i<transaction.notes.delay_deny_pre.length; i++) {
let params = transaction.notes.delay_deny_pre[i];
// Remove rejection from the array if it was on the rcpt hooks
if (params[5] === 'rcpt' || params[5] === 'rcpt_ok') {
transaction.notes.delay_deny_pre.splice(i, 1);
}
return next(params[0], params[1]);
}
}
return next();
};
exports.hook_data = function (next, connection) {
var transaction = connection.transaction;
// Add a header showing all pre-DATA rejections
var fails = [];
if (connection.notes.delay_deny_pre_fail) {
fails.push.apply(Object.keys(connection.notes.delay_deny_pre_fail));
}
if (transaction.notes.delay_deny_pre_fail) {
fails.push.apply(Object.keys(transaction.notes.delay_deny_pre_fail));
}
if (fails.length) transaction.add_header('X-Haraka-Fail-Pre', fails.join(' '));
return next();
}
| Synchro/Haraka | plugins/delay_deny.js | JavaScript | mit | 5,266 |
module.exports = {
entry: './client/index.js',
output: {
path: __dirname + '/public',
filename: 'bundle.js'
},
module: {
loaders: [{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/
}]
},
resolve: {
extensions: ['.js', '.jsx']
},
devtool: 'source-map'
}
| kelly-keating/kelly-keating.github.io | webpack.config.js | JavaScript | mit | 324 |
define( 'test2', ['test3', 'test4'], function( obj, str ){
return 'test2 is done, deps : [ ' + obj.name + str + ' ]';
}); | eleanors/EaseJS | core/test/assets/test2.js | JavaScript | mit | 122 |
import React, { PureComponent } from 'react';
class ProgressBar extends PureComponent {
render() {
const { progress, className, percent = 100 } = this.props;
return (
<div className={className}>
{progress && <div className="progress">
<div
className="progress-bar progress-bar-striped progress-bar-animated"
role="progressbar"
style={{ width: `${percent}%` }}
/>
</div>}
</div>
);
}
}
export default ProgressBar;
| Apozhidaev/terminal.mobi | src/components/ProgressBar/index.js | JavaScript | mit | 517 |
var DEFAULT_HANDEDNESS = require('../constants').DEFAULT_HANDEDNESS;
var AXIS_LABELS = ['x', 'y', 'z', 'w'];
var NUM_HANDS = 2; // Number of hands in a pair. Should always be 2.
/**
* Called on controller component `.play` handlers.
* Check if controller matches parameters and inject tracked-controls component.
* Handle event listeners.
* Generate controllerconnected or controllerdisconnected events.
*
* @param {object} component - Tracked controls component.
* @param {object} idPrefix - Prefix to match in gamepad id if any.
* @param {object} queryObject - Map of values to match.
*/
module.exports.checkControllerPresentAndSetup = function (component, idPrefix, queryObject) {
var el = component.el;
var isPresent = isControllerPresent(component, idPrefix, queryObject);
// If component was previously paused and now playing, re-add event listeners.
// Handle the event listeners here since this helper method is control of calling
// `.addEventListeners` and `.removeEventListeners`.
if (component.controllerPresent && !component.controllerEventsActive) {
component.addEventListeners();
}
// Nothing changed, no need to do anything.
if (isPresent === component.controllerPresent) { return isPresent; }
component.controllerPresent = isPresent;
// Update controller presence.
if (isPresent) {
component.injectTrackedControls();
component.addEventListeners();
el.emit('controllerconnected', {name: component.name, component: component});
} else {
component.removeEventListeners();
el.emit('controllerdisconnected', {name: component.name, component: component});
}
};
/**
* Enumerate controller (that have pose) and check if they match parameters.
*
* @param {object} component - Tracked controls component.
* @param {object} idPrefix - Prefix to match in gamepad id if any.
* @param {object} queryObject - Map of values to match.
*/
function isControllerPresent (component, idPrefix, queryObject) {
var gamepads;
var sceneEl = component.el.sceneEl;
var trackedControlsSystem;
var filterControllerIndex = queryObject.index || 0;
if (!idPrefix) { return false; }
trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls'];
if (!trackedControlsSystem) { return false; }
gamepads = trackedControlsSystem.controllers;
if (!gamepads.length) { return false; }
return !!findMatchingController(gamepads, null, idPrefix, queryObject.hand,
filterControllerIndex);
}
module.exports.isControllerPresent = isControllerPresent;
/**
* Walk through the given controllers to find any where the device ID equals
* filterIdExact, or startsWith filterIdPrefix.
* A controller where this considered true is considered a 'match'.
*
* For each matching controller:
* If filterHand is set, and the controller:
* is handed, we further verify that controller.hand equals filterHand.
* is unhanded (controller.hand is ''), we skip until we have found a
* number of matching controllers that equals filterControllerIndex
* If filterHand is not set, we skip until we have found the nth matching
* controller, where n equals filterControllerIndex
*
* The method should be called with one of: [filterIdExact, filterIdPrefix] AND
* one or both of: [filterHand, filterControllerIndex]
*
* @param {object} controllers - Array of gamepads to search
* @param {string} filterIdExact - If set, used to find controllers with id === this value
* @param {string} filterIdPrefix - If set, used to find controllers with id startsWith this value
* @param {object} filterHand - If set, further filters controllers with matching 'hand' property
* @param {object} filterControllerIndex - Find the nth matching controller,
* where n equals filterControllerIndex. defaults to 0.
*/
function findMatchingController (controllers, filterIdExact, filterIdPrefix, filterHand,
filterControllerIndex) {
var controller;
var i;
var matchingControllerOccurence = 0;
var targetControllerMatch = filterControllerIndex || 0;
for (i = 0; i < controllers.length; i++) {
controller = controllers[i];
// Determine if the controller ID matches our criteria.
if (filterIdPrefix && !controller.id.startsWith(filterIdPrefix)) {
continue;
}
if (!filterIdPrefix && controller.id !== filterIdExact) { continue; }
// If the hand filter and controller handedness are defined we compare them.
if (filterHand && controller.hand && filterHand !== controller.hand) { continue; }
// If we have detected an unhanded controller and the component was asking
// for a particular hand, we need to treat the controllers in the array as
// pairs of controllers. This effectively means that we need to skip
// NUM_HANDS matches for each controller number, instead of 1.
if (filterHand && !controller.hand) {
targetControllerMatch = NUM_HANDS * filterControllerIndex + ((filterHand === DEFAULT_HANDEDNESS) ? 0 : 1);
}
// We are looking for the nth occurence of a matching controller
// (n equals targetControllerMatch).
if (matchingControllerOccurence === targetControllerMatch) { return controller; }
++matchingControllerOccurence;
}
return undefined;
}
module.exports.findMatchingController = findMatchingController;
/**
* Emit specific `moved` event(s) if axes changed based on original axismoved event.
*
* @param {object} component - Controller component in use.
* @param {array} axesMapping - For example `{thumbstick: [0, 1]}`.
* @param {object} evt - Event to process.
*/
module.exports.emitIfAxesChanged = function (component, axesMapping, evt) {
var axes;
var buttonType;
var changed;
var detail;
var j;
for (buttonType in axesMapping) {
axes = axesMapping[buttonType];
changed = false;
for (j = 0; j < axes.length; j++) {
if (evt.detail.changed[axes[j]]) { changed = true; }
}
if (!changed) { continue; }
// Axis has changed. Emit the specific moved event with axis values in detail.
detail = {};
for (j = 0; j < axes.length; j++) {
detail[AXIS_LABELS[j]] = evt.detail.axis[axes[j]];
}
component.el.emit(buttonType + 'moved', detail);
}
};
/**
* Handle a button event and reemits the events.
*
* @param {string} id - id of the button.
* @param {string} evtName - name of the reemitted event
* @param {object} component - reference to the component
* @param {string} hand - handedness of the controller: left or right.
*/
module.exports.onButtonEvent = function (id, evtName, component, hand) {
var mapping = hand ? component.mapping[hand] : component.mapping;
var buttonName = mapping.buttons[id];
component.el.emit(buttonName + evtName);
if (component.updateModel) {
component.updateModel(buttonName, evtName);
}
};
| RSpace/aframe | src/utils/tracked-controls.js | JavaScript | mit | 6,862 |
module.exports={A:{A:{"2":"K D G E A B iB"},B:{"1":"AB","2":"2 C","132":"d J M H I"},C:{"1":"0 1 3 4 7 8 9 r s t u v w x y z IB BB CB DB GB","2":"2 fB FB F N K D G E A B C d J M H I O P Q R S T U V W X Y Z ZB YB","132":"6 a b c e f g h i j k l m n o L q"},D:{"1":"GB SB OB MB lB NB KB AB PB QB","2":"2 6 F N K D G E A B C d J M H I O P Q R S T U V W X Y Z a b c e","132":"0 1 3 4 7 8 9 f g h i j k l m n o L q r s t u v w x y z IB BB CB DB"},E:{"1":"5 A B C WB XB p aB","2":"F N K D RB JB TB UB","132":"G E VB"},F:{"1":"0 1 y z","2":"5 E B C J M H I O P Q R bB cB dB eB p EB gB","132":"6 S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x"},G:{"1":"nB oB pB qB rB sB tB uB","2":"JB hB HB jB kB LB","16":"G","132":"mB"},H:{"2":"vB"},I:{"1":"4","2":"FB F wB xB yB zB HB 0B 1B"},J:{"1":"A","2":"D"},K:{"2":"5 A B C p EB","132":"L"},L:{"1":"KB"},M:{"1":"3"},N:{"2":"A B"},O:{"132":"2B"},P:{"132":"F 3B 4B 5B 6B 7B"},Q:{"132":"8B"},R:{"132":"9B"},S:{"1":"AC"}},B:1,C:"Path2D"};
| quentinbernet/quentinbernet.github.io | node_modules/caniuse-lite/data/features/path2d.js | JavaScript | mit | 984 |
const prettyBytes = require("pretty-bytes");
(prettyBytes(123): string);
// $ExpectError
prettyBytes("123");
// $ExpectError
prettyBytes(true);
| mwalkerwells/flow-typed | definitions/npm/pretty-bytes_v4.x.x/test_pretty-bytes_v4.x.x.js | JavaScript | mit | 147 |
import React from 'react'
import UiValidate from '../../../../components/forms/validation/UiValidate'
import MaskedInput from '../../../../components/forms/inputs/MaskedInput'
import UiDatepicker from '../../../../components/forms/inputs/UiDatepicker'
const validationOptions = {
// Rules for form validation
rules: {
name: {
required: true
},
email: {
required: true,
email: true
},
review: {
required: true,
minlength: 20
},
quality: {
required: true
},
reliability: {
required: true
},
overall: {
required: true
}
},
// Messages for form validation
messages: {
name: {
required: 'Please enter your name'
},
email: {
required: 'Please enter your email address',
email: '<i class="fa fa-warning"></i><strong>Please enter a VALID email addres</strong>'
},
review: {
required: 'Please enter your review'
},
quality: {
required: 'Please rate quality of the product'
},
reliability: {
required: 'Please rate reliability of the product'
},
overall: {
required: 'Please rate the product'
}
}
};
export default class ReviewForm extends React.Component {
onSubmit(e) {
e.preventDefault();
console.log('submit stuff')
}
render() {
return (
<UiValidate options={validationOptions}>
<form id="review-form" className="smart-form" noValidate="novalidate" onSubmit={this.onSubmit}>
<header>
Review form
</header>
<fieldset>
<section>
<label className="input"> <i className="icon-append fa fa-user"/>
<input type="text" name="name" id="name" placeholder="Your name"/>
</label>
</section>
<section>
<label className="input"> <i className="icon-append fa fa-envelope-o"/>
<input type="email" name="email" id="email" placeholder="Your e-mail"/>
</label>
</section>
<section>
<label className="label"/>
<label className="textarea"> <i className="icon-append fa fa-comment"/>
<textarea rows="3" name="review" id="review" placeholder="Text of the review"/>
</label>
</section>
<section>
<div className="rating">
<input type="radio" name="quality" id="quality-5"/>
<label htmlFor="quality-5"><i className="fa fa-star"/></label>
<input type="radio" name="quality" id="quality-4"/>
<label htmlFor="quality-4"><i className="fa fa-star"/></label>
<input type="radio" name="quality" id="quality-3"/>
<label htmlFor="quality-3"><i className="fa fa-star"/></label>
<input type="radio" name="quality" id="quality-2"/>
<label htmlFor="quality-2"><i className="fa fa-star"/></label>
<input type="radio" name="quality" id="quality-1"/>
<label htmlFor="quality-1"><i className="fa fa-star"/></label>
Quality of the product
</div>
<div className="rating">
<input type="radio" name="reliability" id="reliability-5"/>
<label htmlFor="reliability-5"><i className="fa fa-star"/></label>
<input type="radio" name="reliability" id="reliability-4"/>
<label htmlFor="reliability-4"><i className="fa fa-star"/></label>
<input type="radio" name="reliability" id="reliability-3"/>
<label htmlFor="reliability-3"><i className="fa fa-star"/></label>
<input type="radio" name="reliability" id="reliability-2"/>
<label htmlFor="reliability-2"><i className="fa fa-star"/></label>
<input type="radio" name="reliability" id="reliability-1"/>
<label htmlFor="reliability-1"><i className="fa fa-star"/></label>
Reliability of the product
</div>
<div className="rating">
<input type="radio" name="overall" id="overall-5"/>
<label htmlFor="overall-5"><i className="fa fa-star"/></label>
<input type="radio" name="overall" id="overall-4"/>
<label htmlFor="overall-4"><i className="fa fa-star"/></label>
<input type="radio" name="overall" id="overall-3"/>
<label htmlFor="overall-3"><i className="fa fa-star"/></label>
<input type="radio" name="overall" id="overall-2"/>
<label htmlFor="overall-2"><i className="fa fa-star"/></label>
<input type="radio" name="overall" id="overall-1"/>
<label htmlFor="overall-1"><i className="fa fa-star"/></label>
Overall rating
</div>
</section>
</fieldset>
<footer>
<button type="submit" className="btn btn-primary">
Validate Form
</button>
</footer>
</form>
</UiValidate>
)
}
} | backpackcoder/world-in-flames | src/app/routes/forms/components/layouts/ReviewForm.js | JavaScript | mit | 5,184 |
jQuery(document).ready(function($) {
var $start_date = $("#podlove_season_start_date")
$start_date.datepicker({
dateFormat: $.datepicker.ISO_8601,
changeMonth: true,
changeYear: true
});
$start_date.closest("div").on("click", function() {
$start_date.datepicker("show");
});
});
| katrinleinweber/podlove-publisher | lib/modules/seasons/js/admin.js | JavaScript | mit | 311 |
/*jshint laxbreak:true */
var assert = require('assert');
var metadata = require('./index');
describe('metadata.cmd()', function() {
it('returns command without exif data', function() {
var cmd = 'identify -format "name=\nsize=%[size]\nformat=%m\n'
+ 'colorspace=%[colorspace]\nheight=%[height]\nwidth=%[width]\n'
+ 'orientation=%[orientation]\n" /foo/bar/baz';
assert.equal(metadata.cmd('/foo/bar/baz'), cmd);
});
it('returns command with exif data', function() {
var cmd = 'identify -format "name=\nsize=%[size]\nformat=%m\n'
+ 'colorspace=%[colorspace]\nheight=%[height]\nwidth=%[width]\n'
+ 'orientation=%[orientation]\n%[exif:*]" /foo/bar/baz';
assert.equal(metadata.cmd('/foo/bar/baz', {exif: true}), cmd);
});
});
describe('metadata.parse()', function() {
var path = '/foo/bar/baz.jpg';
it('returns object for single value', function() {
assert.deepEqual(metadata.parse(path, 'foo=bar'), {
path: path,
foo: 'bar'
});
});
it('returns object for metadata string', function() {
assert.deepEqual(metadata.parse(path, 'foo=bar\nbar=foo'), {
path: path,
foo: 'bar',
bar: 'foo'
});
});
it('skips empty lines', function() {
assert.deepEqual(metadata.parse(path, 'foo=bar\n\nbar=foo\n\n'), {
path: path,
foo: 'bar',
bar: 'foo'
});
});
it('returns correct size for bogus value', function() {
assert.deepEqual(metadata.parse(path, 'size=4.296MBB'), {
path: path,
size: 4504682
});
});
it('returns size in bytes', function() {
assert.deepEqual(metadata.parse(path, 'size=20MB'), {
path: path,
size: 20 * 1024 * 1024
});
});
it('returns RGB for sRGB colorspace', function() {
assert.deepEqual(metadata.parse(path, 'colorspace=sRGB'), {
path: path,
colorspace: 'RGB'
});
});
it('returns "" for Undefined orientation', function() {
assert.deepEqual(metadata.parse(path, 'orientation=Undefined'), {
path: path,
orientation: ''
});
});
it('returns height and widt for auto-orient', function() {
var meta = 'width=100\nheight=150\norientation=';
var opts = {autoOrient: true};
var orientation = [
'TopLeft', 'TopRight', 'BottomRight', 'BottomLeft',
'LeftTop', 'RightTop', 'RightBottom', 'LeftBottom'
];
for (var i = 0; i < 4; i++) {
assert.deepEqual(metadata.parse(path, meta + orientation[i], opts), {
height: 150,
width: 100,
path: path,
orientation: orientation[i]
});
}
for (var j = 4; j < 8; j++) {
assert.deepEqual(metadata.parse(path, meta + orientation[j], opts), {
height: 100,
width: 150,
path: path,
orientation: orientation[j]
});
}
});
});
describe('metadata()', function() {
it('returns metadata for image', function(done) {
metadata('./assets/image.jpg', { exif: false }, function(err, data) {
assert.ifError(err);
assert.equal(data.path, './assets/image.jpg');
assert.equal(data.name, '');
assert.equal(data.size, 4504682);
assert.equal(data.format, 'JPEG');
assert.equal(data.colorspace, 'RGB');
assert.equal(data.height, 3456);
assert.equal(data.width, 5184);
assert.equal(data.orientation, 'TopLeft');
assert.equal(typeof data.exif, 'undefined');
done();
});
});
it('returns metadata for image with exif data', function(done) {
metadata('./assets/image.jpg', { exif: true }, function(err, data) {
assert.ifError(err);
assert.equal(data.path, './assets/image.jpg');
assert.equal(data.name, '');
assert.equal(data.size, 4504682);
assert.equal(data.format, 'JPEG');
assert.equal(data.colorspace, 'RGB');
assert.equal(data.height, 3456);
assert.equal(data.width, 5184);
assert.equal(data.orientation, 'TopLeft');
assert.equal(typeof data.exif, 'object');
assert.equal(Object.keys(data.exif).length, 36);
assert.equal(data.exif.ApertureValue, '37/8');
done();
});
});
it('returns correct height and width for auto-orient', function(done) {
metadata('./assets/orient.jpg', { autoOrient: true }, function(err, data) {
assert.ifError(err);
assert.equal(data.height, 3264);
assert.equal(data.width, 2448);
done();
});
});
});
| Turistforeningen/node-im-metadata | test.js | JavaScript | mit | 4,447 |
module.exports = {
"sha": "6d1fd68d5d273f6c46113f5843731131ad226d64",
"name": "numenta/experiments",
"target_url": "https://travis-ci.org/numenta/experiments",
"description": "NuPIC Status: Travis CI build has not started.",
"state": "pending",
"branches": [],
"commit": {
"sha": "6d1fd68d5d273f6c46113f5843731131ad226d64",
"commit": {
"author": {
"name": "Matthew Taylor",
"email": "[email protected]",
"date": "2014-03-25T04:38:48Z"
},
"committer": {
"name": "Matthew Taylor",
"email": "[email protected]",
"date": "2014-03-25T04:38:48Z"
},
"message": "Update README.md",
"tree": {
"sha": "067e3d6dd8e046735031285b633fe7c20c4b2b27",
"url": "https://api.github.com/repos/numenta/experiments/git/trees/067e3d6dd8e046735031285b633fe7c20c4b2b27"
},
"url": "https://api.github.com/repos/numenta/experiments/git/commits/6d1fd68d5d273f6c46113f5843731131ad226d64",
"comment_count": 0
},
"url": "https://api.github.com/repos/numenta/experiments/commits/6d1fd68d5d273f6c46113f5843731131ad226d64",
"html_url": "https://github.com/numenta/experiments/commit/6d1fd68d5d273f6c46113f5843731131ad226d64",
"comments_url": "https://api.github.com/repos/numenta/experiments/commits/6d1fd68d5d273f6c46113f5843731131ad226d64/comments",
"author": {
"login": "rhyolight",
"id": 15566,
"avatar_url": "https://avatars.githubusercontent.com/u/15566?",
"gravatar_id": "92b95d73c678f23c6060e63bff3dbcbd",
"url": "https://api.github.com/users/rhyolight",
"html_url": "https://github.com/rhyolight",
"followers_url": "https://api.github.com/users/rhyolight/followers",
"following_url": "https://api.github.com/users/rhyolight/following{/other_user}",
"gists_url": "https://api.github.com/users/rhyolight/gists{/gist_id}",
"starred_url": "https://api.github.com/users/rhyolight/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/rhyolight/subscriptions",
"organizations_url": "https://api.github.com/users/rhyolight/orgs",
"repos_url": "https://api.github.com/users/rhyolight/repos",
"events_url": "https://api.github.com/users/rhyolight/events{/privacy}",
"received_events_url": "https://api.github.com/users/rhyolight/received_events",
"type": "User",
"site_admin": false
},
"committer": {
"login": "rhyolight",
"id": 15566,
"avatar_url": "https://avatars.githubusercontent.com/u/15566?",
"gravatar_id": "92b95d73c678f23c6060e63bff3dbcbd",
"url": "https://api.github.com/users/rhyolight",
"html_url": "https://github.com/rhyolight",
"followers_url": "https://api.github.com/users/rhyolight/followers",
"following_url": "https://api.github.com/users/rhyolight/following{/other_user}",
"gists_url": "https://api.github.com/users/rhyolight/gists{/gist_id}",
"starred_url": "https://api.github.com/users/rhyolight/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/rhyolight/subscriptions",
"organizations_url": "https://api.github.com/users/rhyolight/orgs",
"repos_url": "https://api.github.com/users/rhyolight/repos",
"events_url": "https://api.github.com/users/rhyolight/events{/privacy}",
"received_events_url": "https://api.github.com/users/rhyolight/received_events",
"type": "User",
"site_admin": false
},
"parents": [{
"sha": "9594d18d57ca80cdb66aacce2475eebca61c1593",
"url": "https://api.github.com/repos/numenta/experiments/commits/9594d18d57ca80cdb66aacce2475eebca61c1593",
"html_url": "https://github.com/numenta/experiments/commit/9594d18d57ca80cdb66aacce2475eebca61c1593"
}]
},
"repository": {
"id": 10708772,
"name": "experiments",
"full_name": "numenta/experiments",
"owner": {
"login": "numenta",
"id": 1039191,
"avatar_url": "https://avatars.githubusercontent.com/u/1039191?",
"gravatar_id": "faac04630eba5ec1aeda8bcbca3ff018",
"url": "https://api.github.com/users/numenta",
"html_url": "https://github.com/numenta",
"followers_url": "https://api.github.com/users/numenta/followers",
"following_url": "https://api.github.com/users/numenta/following{/other_user}",
"gists_url": "https://api.github.com/users/numenta/gists{/gist_id}",
"starred_url": "https://api.github.com/users/numenta/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/numenta/subscriptions",
"organizations_url": "https://api.github.com/users/numenta/orgs",
"repos_url": "https://api.github.com/users/numenta/repos",
"events_url": "https://api.github.com/users/numenta/events{/privacy}",
"received_events_url": "https://api.github.com/users/numenta/received_events",
"type": "Organization",
"site_admin": false
},
"private": false,
"html_url": "https://github.com/numenta/experiments",
"description": "A junk repo for experimenting with git flows and toolins",
"fork": false,
"url": "https://api.github.com/repos/numenta/experiments",
"forks_url": "https://api.github.com/repos/numenta/experiments/forks",
"keys_url": "https://api.github.com/repos/numenta/experiments/keys{/key_id}",
"collaborators_url": "https://api.github.com/repos/numenta/experiments/collaborators{/collaborator}",
"teams_url": "https://api.github.com/repos/numenta/experiments/teams",
"hooks_url": "https://api.github.com/repos/numenta/experiments/hooks",
"issue_events_url": "https://api.github.com/repos/numenta/experiments/issues/events{/number}",
"events_url": "https://api.github.com/repos/numenta/experiments/events",
"assignees_url": "https://api.github.com/repos/numenta/experiments/assignees{/user}",
"branches_url": "https://api.github.com/repos/numenta/experiments/branches{/branch}",
"tags_url": "https://api.github.com/repos/numenta/experiments/tags",
"blobs_url": "https://api.github.com/repos/numenta/experiments/git/blobs{/sha}",
"git_tags_url": "https://api.github.com/repos/numenta/experiments/git/tags{/sha}",
"git_refs_url": "https://api.github.com/repos/numenta/experiments/git/refs{/sha}",
"trees_url": "https://api.github.com/repos/numenta/experiments/git/trees{/sha}",
"statuses_url": "https://api.github.com/repos/numenta/experiments/statuses/{sha}",
"languages_url": "https://api.github.com/repos/numenta/experiments/languages",
"stargazers_url": "https://api.github.com/repos/numenta/experiments/stargazers",
"contributors_url": "https://api.github.com/repos/numenta/experiments/contributors",
"subscribers_url": "https://api.github.com/repos/numenta/experiments/subscribers",
"subscription_url": "https://api.github.com/repos/numenta/experiments/subscription",
"commits_url": "https://api.github.com/repos/numenta/experiments/commits{/sha}",
"git_commits_url": "https://api.github.com/repos/numenta/experiments/git/commits{/sha}",
"comments_url": "https://api.github.com/repos/numenta/experiments/comments{/number}",
"issue_comment_url": "https://api.github.com/repos/numenta/experiments/issues/comments/{number}",
"contents_url": "https://api.github.com/repos/numenta/experiments/contents/{+path}",
"compare_url": "https://api.github.com/repos/numenta/experiments/compare/{base}...{head}",
"merges_url": "https://api.github.com/repos/numenta/experiments/merges",
"archive_url": "https://api.github.com/repos/numenta/experiments/{archive_format}{/ref}",
"downloads_url": "https://api.github.com/repos/numenta/experiments/downloads",
"issues_url": "https://api.github.com/repos/numenta/experiments/issues{/number}",
"pulls_url": "https://api.github.com/repos/numenta/experiments/pulls{/number}",
"milestones_url": "https://api.github.com/repos/numenta/experiments/milestones{/number}",
"notifications_url": "https://api.github.com/repos/numenta/experiments/notifications{?since,all,participating}",
"labels_url": "https://api.github.com/repos/numenta/experiments/labels{/name}",
"releases_url": "https://api.github.com/repos/numenta/experiments/releases{/id}",
"created_at": "2013-06-15T16:23:06Z",
"updated_at": "2014-03-25T04:30:09Z",
"pushed_at": "2014-03-25T04:30:07Z",
"git_url": "git://github.com/numenta/experiments.git",
"ssh_url": "[email protected]:numenta/experiments.git",
"clone_url": "https://github.com/numenta/experiments.git",
"svn_url": "https://github.com/numenta/experiments",
"homepage": null,
"size": 344,
"stargazers_count": 2,
"watchers_count": 2,
"language": null,
"has_issues": true,
"has_downloads": true,
"has_wiki": true,
"forks_count": 4,
"mirror_url": null,
"open_issues_count": 7,
"forks": 4,
"open_issues": 7,
"watchers": 2,
"default_branch": "master",
"master_branch": "master"
},
"sender": {
"login": "numenta-ci",
"id": 4650657,
"avatar_url": "https://avatars.githubusercontent.com/u/4650657?",
"gravatar_id": "00d730d6342f80cdad84a37a176d0c49",
"url": "https://api.github.com/users/numenta-ci",
"html_url": "https://github.com/numenta-ci",
"followers_url": "https://api.github.com/users/numenta-ci/followers",
"following_url": "https://api.github.com/users/numenta-ci/following{/other_user}",
"gists_url": "https://api.github.com/users/numenta-ci/gists{/gist_id}",
"starred_url": "https://api.github.com/users/numenta-ci/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/numenta-ci/subscriptions",
"organizations_url": "https://api.github.com/users/numenta-ci/orgs",
"repos_url": "https://api.github.com/users/numenta-ci/repos",
"events_url": "https://api.github.com/users/numenta-ci/events{/privacy}",
"received_events_url": "https://api.github.com/users/numenta-ci/received_events",
"type": "User",
"site_admin": false
}
}; | brev/nupic.tools | test/github_payloads/status_nupic_pending.js | JavaScript | mit | 10,928 |
describe('Layer', function() {
// Currently not testing subdomain-based templatedmapprovider, since
// the implementation should be kind of undefined.
it('layer can be created and destroyed', function() {
var p = new MM.TemplatedLayer(
'http://{S}.tile.openstreetmap.org/{Z}/{X}/{Y}.png', ['a']);
var l = new MM.Layer(p);
l.destroy();
expect(l.map).toEqual(null);
});
// Currently not testing subdomain-based templatedmapprovider, since
// the implementation should be kind of undefined.
it('causes the map to throw requesterror when things are not accessible', function() {
var manager, message, p;
var fourohfour = 'http://fffffffffffffffffffffffffffffffff.org/404.png';
runs(function() {
p = new MM.TemplatedLayer(fourohfour);
p.requestManager.addCallback('requesterror', function(a, b, c) {
manager = a;
message = b;
});
var m = new MM.Map(document.createElement('div'), p, { x: 500, y: 500 });
m.setCenter({ lat: 0, lon: 0 }).setZoom(5);
});
waits(500);
runs(function() {
expect(manager).toEqual(p.requestManager);
expect(jasmine.isDomNode(message.element)).toBeTruthy();
expect(message.url).toEqual(fourohfour);
expect(message.url).toEqual('http://fffffffffffffffffffffffffffffffff.org/404.png');
});
});
});
| nickchikore/Product-Developer-Test | node_modules/modestmaps/test/spec/Layer.js | JavaScript | mit | 1,490 |
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
require('./chunk-14c82365.js');
require('./helpers.js');
require('./chunk-cd0dcc1d.js');
require('./chunk-d7fda995.js');
var __chunk_5 = require('./chunk-13e039f5.js');
var __chunk_19 = require('./chunk-3b860353.js');
//
var script = {
name: 'BMessage',
mixins: [__chunk_19.MessageMixin],
props: {
ariaCloseLabel: String
},
data: function data() {
return {
newIconSize: this.iconSize || this.size || 'is-large'
};
}
};
/* script */
const __vue_script__ = script;
/* template */
var __vue_render__ = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('transition',{attrs:{"name":"fade"}},[(_vm.isActive)?_c('article',{staticClass:"message",class:[_vm.type, _vm.size]},[(_vm.title)?_c('header',{staticClass:"message-header"},[_c('p',[_vm._v(_vm._s(_vm.title))]),_vm._v(" "),(_vm.closable)?_c('button',{staticClass:"delete",attrs:{"type":"button","aria-label":_vm.ariaCloseLabel},on:{"click":_vm.close}}):_vm._e()]):_vm._e(),_vm._v(" "),_c('section',{staticClass:"message-body"},[_c('div',{staticClass:"media"},[(_vm.computedIcon && _vm.hasIcon)?_c('div',{staticClass:"media-left"},[_c('b-icon',{class:_vm.type,attrs:{"icon":_vm.computedIcon,"pack":_vm.iconPack,"both":"","size":_vm.newIconSize}})],1):_vm._e(),_vm._v(" "),_c('div',{staticClass:"media-content"},[_vm._t("default")],2)])])]):_vm._e()])};
var __vue_staticRenderFns__ = [];
/* style */
const __vue_inject_styles__ = undefined;
/* scoped */
const __vue_scope_id__ = undefined;
/* module identifier */
const __vue_module_identifier__ = undefined;
/* functional template */
const __vue_is_functional_template__ = false;
/* style inject */
/* style inject SSR */
var Message = __chunk_5.__vue_normalize__(
{ render: __vue_render__, staticRenderFns: __vue_staticRenderFns__ },
__vue_inject_styles__,
__vue_script__,
__vue_scope_id__,
__vue_is_functional_template__,
__vue_module_identifier__,
undefined,
undefined
);
var Plugin = {
install: function install(Vue) {
__chunk_5.registerComponent(Vue, Message);
}
};
__chunk_5.use(Plugin);
exports.BMessage = Message;
exports.default = Plugin;
| cdnjs/cdnjs | ajax/libs/buefy/0.8.20/cjs/message.js | JavaScript | mit | 2,270 |
/// <reference path="./subject.ts" />
var Rx;
(function (Rx) {
})(Rx || (Rx = {}));
(function () {
var s = new Rx.AnonymousSubject();
});
//# sourceMappingURL=anonymoussubject.js.map | cyberpuffin/remanddel | node_modules/lite-server/node_modules/browser-sync/node_modules/rx/ts/core/subjects/anonymoussubject.js | JavaScript | mit | 186 |
/**
* @license Highcharts JS v8.2.2 (2020-10-22)
*
* Marker clusters module for Highcharts
*
* (c) 2010-2019 Wojciech Chmiel
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
factory['default'] = factory;
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
define('highcharts/modules/marker-clusters', ['highcharts'], function (Highcharts) {
factory(Highcharts);
factory.Highcharts = Highcharts;
return factory;
});
} else {
factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
}
}(function (Highcharts) {
var _modules = Highcharts ? Highcharts._modules : {};
function _registerModule(obj, path, args, fn) {
if (!obj.hasOwnProperty(path)) {
obj[path] = fn.apply(null, args);
}
}
_registerModule(_modules, 'Extensions/MarkerClusters.js', [_modules['Core/Animation/AnimationUtilities.js'], _modules['Core/Series/Series.js'], _modules['Core/Chart/Chart.js'], _modules['Core/Globals.js'], _modules['Core/Options.js'], _modules['Core/Series/Point.js'], _modules['Core/Renderer/SVG/SVGRenderer.js'], _modules['Core/Utilities.js'], _modules['Core/Axis/Axis.js']], function (A, BaseSeries, Chart, H, O, Point, SVGRenderer, U, Axis) {
/* *
*
* Marker clusters module.
*
* (c) 2010-2020 Torstein Honsi
*
* Author: Wojciech Chmiel
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var animObject = A.animObject;
var defaultOptions = O.defaultOptions;
var addEvent = U.addEvent,
defined = U.defined,
error = U.error,
isArray = U.isArray,
isFunction = U.isFunction,
isObject = U.isObject,
isNumber = U.isNumber,
merge = U.merge,
objectEach = U.objectEach,
relativeLength = U.relativeLength,
syncTimeout = U.syncTimeout;
/**
* Function callback when a cluster is clicked.
*
* @callback Highcharts.MarkerClusterDrillCallbackFunction
*
* @param {Highcharts.Point} this
* The point where the event occured.
*
* @param {Highcharts.PointClickEventObject} event
* Event arguments.
*/
''; // detach doclets from following code
/* eslint-disable no-invalid-this */
var Series = H.Series,
Scatter = BaseSeries.seriesTypes.scatter,
baseGeneratePoints = Series.prototype.generatePoints,
stateIdCounter = 0,
// Points that ids are included in the oldPointsStateId array
// are hidden before animation. Other ones are destroyed.
oldPointsStateId = [];
/**
* Options for marker clusters, the concept of sampling the data
* values into larger blocks in order to ease readability and
* increase performance of the JavaScript charts.
*
* Note: marker clusters module is not working with `boost`
* and `draggable-points` modules.
*
* The marker clusters feature requires the marker-clusters.js
* file to be loaded, found in the modules directory of the download
* package, or online at [code.highcharts.com/modules/marker-clusters.js
* ](code.highcharts.com/modules/marker-clusters.js).
*
* @sample maps/marker-clusters/europe
* Maps marker clusters
* @sample highcharts/marker-clusters/basic
* Scatter marker clusters
* @sample maps/marker-clusters/optimized-kmeans
* Marker clusters with colorAxis
*
* @product highcharts highmaps
* @since 8.0.0
* @optionparent plotOptions.scatter.cluster
*
* @private
*/
var clusterDefaultOptions = {
/**
* Whether to enable the marker-clusters module.
*
* @sample maps/marker-clusters/basic
* Maps marker clusters
* @sample highcharts/marker-clusters/basic
* Scatter marker clusters
*/
enabled: false,
/**
* When set to `false` prevent cluster overlapping - this option
* works only when `layoutAlgorithm.type = "grid"`.
*
* @sample highcharts/marker-clusters/grid
* Prevent overlapping
*/
allowOverlap: true,
/**
* Options for the cluster marker animation.
* @type {boolean|Partial<Highcharts.AnimationOptionsObject>}
* @default { "duration": 500 }
*/
animation: {
/** @ignore-option */
duration: 500
},
/**
* Zoom the plot area to the cluster points range when a cluster is clicked.
*/
drillToCluster: true,
/**
* The minimum amount of points to be combined into a cluster.
* This value has to be greater or equal to 2.
*
* @sample highcharts/marker-clusters/basic
* At least three points in the cluster
*/
minimumClusterSize: 2,
/**
* Options for layout algorithm. Inside there
* are options to change the type of the algorithm,
gridSize,
* distance or iterations.
*/
layoutAlgorithm: {
/**
* Type of the algorithm used to combine points into a cluster.
* There are three available algorithms:
*
* 1) `grid` - grid-based clustering technique. Points are assigned
* to squares of set size depending on their position on the plot
* area. Points inside the grid square are combined into a cluster.
* The grid size can be controlled by `gridSize` property
* (grid size changes at certain zoom levels).
*
* 2) `kmeans` - based on K-Means clustering technique. In the
* first step,
points are divided using the grid method (distance
* property is a grid size) to find the initial amount of clusters.
* Next,
each point is classified by computing the distance between
* each cluster center and that point. When the closest cluster
* distance is lower than distance property set by a user the point
* is added to this cluster otherwise is classified as `noise`. The
* algorithm is repeated until each cluster center not change its
* previous position more than one pixel. This technique is more
* accurate but also more time consuming than the `grid` algorithm,
* especially for big datasets.
*
* 3) `optimizedKmeans` - based on K-Means clustering technique. This
* algorithm uses k-means algorithm only on the chart initialization
* or when chart extremes have greater range than on initialization.
* When a chart is redrawn the algorithm checks only clustered points
* distance from the cluster center and rebuild it when the point is
* spaced enough to be outside the cluster. It provides performance
* improvement and more stable clusters position yet can be used rather
* on small and sparse datasets.
*
* By default,
the algorithm depends on visible quantity of points
* and `kmeansThreshold`. When there are more visible points than the
* `kmeansThreshold` the `grid` algorithm is used,
otherwise `kmeans`.
*
* The custom clustering algorithm can be added by assigning a callback
* function as the type property. This function takes an array of
* `processedXData`,
`processedYData`,
`processedXData` indexes and
* `layoutAlgorithm` options as arguments and should return an object
* with grouped data.
*
* The algorithm should return an object like that:
* <pre>{
* clusterId1: [{
* x: 573,
* y: 285,
* index: 1 // point index in the data array
* }, {
* x: 521,
* y: 197,
* index: 2
* }],
* clusterId2: [{
* ...
* }]
* ...
* }</pre>
*
* `clusterId` (example above - unique id of a cluster or noise)
* is an array of points belonging to a cluster. If the
* array has only one point or fewer points than set in
* `cluster.minimumClusterSize` it won't be combined into a cluster.
*
* @sample maps/marker-clusters/optimized-kmeans
* Optimized K-Means algorithm
* @sample highcharts/marker-clusters/kmeans
* K-Means algorithm
* @sample highcharts/marker-clusters/grid
* Grid algorithm
* @sample maps/marker-clusters/custom-alg
* Custom algorithm
*
* @type {string|Function}
* @see [cluster.minimumClusterSize](#plotOptions.scatter.marker.cluster.minimumClusterSize)
* @apioption plotOptions.scatter.cluster.layoutAlgorithm.type
*/
/**
* When `type` is set to the `grid`,
* `gridSize` is a size of a grid square element either as a number
* defining pixels,
or a percentage defining a percentage
* of the plot area width.
*
* @type {number|string}
*/
gridSize: 50,
/**
* When `type` is set to `kmeans`,
* `iterations` are the number of iterations that this algorithm will be
* repeated to find clusters positions.
*
* @type {number}
* @apioption plotOptions.scatter.cluster.layoutAlgorithm.iterations
*/
/**
* When `type` is set to `kmeans`,
* `distance` is a maximum distance between point and cluster center
* so that this point will be inside the cluster. The distance
* is either a number defining pixels or a percentage
* defining a percentage of the plot area width.
*
* @type {number|string}
*/
distance: 40,
/**
* When `type` is set to `undefined` and there are more visible points
* than the kmeansThreshold the `grid` algorithm is used to find
* clusters,
otherwise `kmeans`. It ensures good performance on
* large datasets and better clusters arrangement after the zoom.
*/
kmeansThreshold: 100
},
/**
* Options for the cluster marker.
* @extends plotOptions.series.marker
* @excluding enabledThreshold,
states
* @type {Highcharts.PointMarkerOptionsObject}
*/
marker: {
/** @internal */
symbol: 'cluster',
/** @internal */
radius: 15,
/** @internal */
lineWidth: 0,
/** @internal */
lineColor: '#ffffff'
},
/**
* Fires when the cluster point is clicked and `drillToCluster` is enabled.
* One parameter,
`event`,
is passed to the function. The default action
* is to zoom to the cluster points range. This can be prevented
* by calling `event.preventDefault()`.
*
* @type {Highcharts.MarkerClusterDrillCallbackFunction}
* @product highcharts highmaps
* @see [cluster.drillToCluster](#plotOptions.scatter.marker.cluster.drillToCluster)
* @apioption plotOptions.scatter.cluster.events.drillToCluster
*/
/**
* An array defining zones within marker clusters.
*
* In styled mode,
the color zones are styled with the
* `.highcharts-cluster-zone-{n}` class,
or custom
* classed from the `className`
* option.
*
* @sample highcharts/marker-clusters/basic
* Marker clusters zones
* @sample maps/marker-clusters/custom-alg
* Zones on maps
*
* @type {Array<*>}
* @product highcharts highmaps
* @apioption plotOptions.scatter.cluster.zones
*/
/**
* Styled mode only. A custom class name for the zone.
*
* @sample highcharts/css/color-zones/
* Zones styled by class name
*
* @type {string}
* @apioption plotOptions.scatter.cluster.zones.className
*/
/**
* Settings for the cluster marker belonging to the zone.
*
* @see [cluster.marker](#plotOptions.scatter.cluster.marker)
* @extends plotOptions.scatter.cluster.marker
* @product highcharts highmaps
* @apioption plotOptions.scatter.cluster.zones.marker
*/
/**
* The value where the zone starts.
*
* @type {number}
* @product highcharts highmaps
* @apioption plotOptions.scatter.cluster.zones.from
*/
/**
* The value where the zone ends.
*
* @type {number}
* @product highcharts highmaps
* @apioption plotOptions.scatter.cluster.zones.to
*/
/**
* The fill color of the cluster marker in hover state. When
* `undefined`,
the series' or point's fillColor for normal
* state is used.
*
* @type {Highcharts.ColorType}
* @apioption plotOptions.scatter.cluster.states.hover.fillColor
*/
/**
* Options for the cluster data labels.
* @type {Highcharts.DataLabelsOptions}
*/
dataLabels: {
/** @internal */
enabled: true,
/** @internal */
format: '{point.clusterPointsAmount}',
/** @internal */
verticalAlign: 'middle',
/** @internal */
align: 'center',
/** @internal */
style: {
color: 'contrast'
},
/** @internal */
inside: true
}
};
(defaultOptions.plotOptions || {}).series = merge((defaultOptions.plotOptions || {}).series, {
cluster: clusterDefaultOptions,
tooltip: {
/**
* The HTML of the cluster point's in the tooltip. Works only with
* marker-clusters module and analogously to
* [pointFormat](#tooltip.pointFormat).
*
* The cluster tooltip can be also formatted using
* `tooltip.formatter` callback function and `point.isCluster` flag.
*
* @sample highcharts/marker-clusters/grid
* Format tooltip for cluster points.
*
* @sample maps/marker-clusters/europe/
* Format tooltip for clusters using tooltip.formatter
*
* @apioption tooltip.clusterFormat
*/
clusterFormat: '<span>Clustered points: ' +
'{point.clusterPointsAmount}</span><br/>'
}
});
// Utils.
/* eslint-disable require-jsdoc */
function getClusterPosition(points) {
var pointsLen = points.length,
sumX = 0,
sumY = 0,
i;
for (i = 0; i < pointsLen; i++) {
sumX += points[i].x;
sumY += points[i].y;
}
return {
x: sumX / pointsLen,
y: sumY / pointsLen
};
}
// Prepare array with sorted data objects to be
// compared in getPointsState method.
function getDataState(clusteredData, stateDataLen) {
var state = [];
state.length = stateDataLen;
clusteredData.clusters.forEach(function (cluster) {
cluster.data.forEach(function (elem) {
state[elem.dataIndex] = elem;
});
});
clusteredData.noise.forEach(function (noise) {
state[noise.data[0].dataIndex] = noise.data[0];
});
return state;
}
function fadeInElement(elem, opacity, animation) {
elem
.attr({
opacity: opacity
})
.animate({
opacity: 1
}, animation);
}
function fadeInStatePoint(stateObj, opacity, animation, fadeinGraphic, fadeinDataLabel) {
if (stateObj.point) {
if (fadeinGraphic && stateObj.point.graphic) {
stateObj.point.graphic.show();
fadeInElement(stateObj.point.graphic, opacity, animation);
}
if (fadeinDataLabel && stateObj.point.dataLabel) {
stateObj.point.dataLabel.show();
fadeInElement(stateObj.point.dataLabel, opacity, animation);
}
}
}
function hideStatePoint(stateObj, hideGraphic, hideDataLabel) {
if (stateObj.point) {
if (hideGraphic && stateObj.point.graphic) {
stateObj.point.graphic.hide();
}
if (hideDataLabel && stateObj.point.dataLabel) {
stateObj.point.dataLabel.hide();
}
}
}
function destroyOldPoints(oldState) {
if (oldState) {
objectEach(oldState, function (state) {
if (state.point && state.point.destroy) {
state.point.destroy();
}
});
}
}
function fadeInNewPointAndDestoryOld(newPointObj, oldPoints, animation, opacity) {
// Fade in new point.
fadeInStatePoint(newPointObj, opacity, animation, true, true);
// Destroy old animated points.
oldPoints.forEach(function (p) {
if (p.point && p.point.destroy) {
p.point.destroy();
}
});
}
// Generate unique stateId for a state element.
function getStateId() {
return Math.random().toString(36).substring(2, 7) + '-' + stateIdCounter++;
}
// Useful for debugging.
// function drawGridLines(
// series: Highcharts.Series,
// options: Highcharts.MarkerClusterLayoutAlgorithmOptions
// ): void {
// var chart = series.chart,
// xAxis = series.xAxis,
// yAxis = series.yAxis,
// xAxisLen = series.xAxis.len,
// yAxisLen = series.yAxis.len,
// i, j, elem, text,
// currentX = 0,
// currentY = 0,
// scaledGridSize = 50,
// gridX = 0,
// gridY = 0,
// gridOffset = series.getGridOffset(),
// mapXSize, mapYSize;
// if (series.debugGridLines && series.debugGridLines.length) {
// series.debugGridLines.forEach(function (gridItem): void {
// if (gridItem && gridItem.destroy) {
// gridItem.destroy();
// }
// });
// }
// series.debugGridLines = [];
// scaledGridSize = series.getScaledGridSize(options);
// mapXSize = Math.abs(
// xAxis.toPixels(xAxis.dataMax || 0) -
// xAxis.toPixels(xAxis.dataMin || 0)
// );
// mapYSize = Math.abs(
// yAxis.toPixels(yAxis.dataMax || 0) -
// yAxis.toPixels(yAxis.dataMin || 0)
// );
// gridX = Math.ceil(mapXSize / scaledGridSize);
// gridY = Math.ceil(mapYSize / scaledGridSize);
// for (i = 0; i < gridX; i++) {
// currentX = i * scaledGridSize;
// if (
// gridOffset.plotLeft + currentX >= 0 &&
// gridOffset.plotLeft + currentX < xAxisLen
// ) {
// for (j = 0; j < gridY; j++) {
// currentY = j * scaledGridSize;
// if (
// gridOffset.plotTop + currentY >= 0 &&
// gridOffset.plotTop + currentY < yAxisLen
// ) {
// if (j % 2 === 0 && i % 2 === 0) {
// var rect = chart.renderer
// .rect(
// gridOffset.plotLeft + currentX,
// gridOffset.plotTop + currentY,
// scaledGridSize * 2,
// scaledGridSize * 2
// )
// .attr({
// stroke: series.color,
// 'stroke-width': '2px'
// })
// .add()
// .toFront();
// series.debugGridLines.push(rect);
// }
// elem = chart.renderer
// .rect(
// gridOffset.plotLeft + currentX,
// gridOffset.plotTop + currentY,
// scaledGridSize,
// scaledGridSize
// )
// .attr({
// stroke: series.color,
// opacity: 0.3,
// 'stroke-width': '1px'
// })
// .add()
// .toFront();
// text = chart.renderer
// .text(
// j + '-' + i,
// gridOffset.plotLeft + currentX + 2,
// gridOffset.plotTop + currentY + 7
// )
// .css({
// fill: 'rgba(0, 0, 0, 0.7)',
// fontSize: '7px'
// })
// .add()
// .toFront();
// series.debugGridLines.push(elem);
// series.debugGridLines.push(text);
// }
// }
// }
// }
// }
/* eslint-enable require-jsdoc */
// Cluster symbol.
SVGRenderer.prototype.symbols.cluster = function (x, y, width, height) {
var w = width / 2,
h = height / 2,
outerWidth = 1,
space = 1,
inner,
outer1,
outer2;
inner = this.arc(x + w, y + h, w - space * 4, h - space * 4, {
start: Math.PI * 0.5,
end: Math.PI * 2.5,
open: false
});
outer1 = this.arc(x + w, y + h, w - space * 3, h - space * 3, {
start: Math.PI * 0.5,
end: Math.PI * 2.5,
innerR: w - outerWidth * 2,
open: false
});
outer2 = this.arc(x + w, y + h, w - space, h - space, {
start: Math.PI * 0.5,
end: Math.PI * 2.5,
innerR: w,
open: false
});
return outer2.concat(outer1, inner);
};
Scatter.prototype.animateClusterPoint = function (clusterObj) {
var series = this,
xAxis = series.xAxis,
yAxis = series.yAxis,
chart = series.chart,
clusterOptions = series.options.cluster,
animation = animObject((clusterOptions || {}).animation),
animDuration = animation.duration || 500,
pointsState = (series.markerClusterInfo || {}).pointsState,
newState = (pointsState || {}).newState,
oldState = (pointsState || {}).oldState,
parentId,
oldPointObj,
newPointObj,
oldPoints = [],
newPointBBox,
offset = 0,
newX = 0,
newY = 0,
isOldPointGrahic = false,
isCbHandled = false;
if (oldState && newState) {
newPointObj = newState[clusterObj.stateId];
newX = xAxis.toPixels(newPointObj.x) - chart.plotLeft;
newY = yAxis.toPixels(newPointObj.y) - chart.plotTop;
// Point has one ancestor.
if (newPointObj.parentsId.length === 1) {
parentId = (newState || {})[clusterObj.stateId].parentsId[0];
oldPointObj = oldState[parentId];
// If old and new poistions are the same do not animate.
if (newPointObj.point &&
newPointObj.point.graphic &&
oldPointObj &&
oldPointObj.point &&
oldPointObj.point.plotX &&
oldPointObj.point.plotY &&
oldPointObj.point.plotX !== newPointObj.point.plotX &&
oldPointObj.point.plotY !== newPointObj.point.plotY) {
newPointBBox = newPointObj.point.graphic.getBBox();
offset = newPointBBox.width / 2;
newPointObj.point.graphic.attr({
x: oldPointObj.point.plotX - offset,
y: oldPointObj.point.plotY - offset
});
newPointObj.point.graphic.animate({
x: newX - (newPointObj.point.graphic.radius || 0),
y: newY - (newPointObj.point.graphic.radius || 0)
}, animation, function () {
isCbHandled = true;
// Destroy old point.
if (oldPointObj.point && oldPointObj.point.destroy) {
oldPointObj.point.destroy();
}
});
// Data label animation.
if (newPointObj.point.dataLabel &&
newPointObj.point.dataLabel.alignAttr &&
oldPointObj.point.dataLabel &&
oldPointObj.point.dataLabel.alignAttr) {
newPointObj.point.dataLabel.attr({
x: oldPointObj.point.dataLabel.alignAttr.x,
y: oldPointObj.point.dataLabel.alignAttr.y
});
newPointObj.point.dataLabel.animate({
x: newPointObj.point.dataLabel.alignAttr.x,
y: newPointObj.point.dataLabel.alignAttr.y
}, animation);
}
}
}
else if (newPointObj.parentsId.length === 0) {
// Point has no ancestors - new point.
// Hide new point.
hideStatePoint(newPointObj, true, true);
syncTimeout(function () {
// Fade in new point.
fadeInStatePoint(newPointObj, 0.1, animation, true, true);
}, animDuration / 2);
}
else {
// Point has many ancestors.
// Hide new point before animation.
hideStatePoint(newPointObj, true, true);
newPointObj.parentsId.forEach(function (elem) {
if (oldState && oldState[elem]) {
oldPointObj = oldState[elem];
oldPoints.push(oldPointObj);
if (oldPointObj.point &&
oldPointObj.point.graphic) {
isOldPointGrahic = true;
oldPointObj.point.graphic.show();
oldPointObj.point.graphic.animate({
x: newX - (oldPointObj.point.graphic.radius || 0),
y: newY - (oldPointObj.point.graphic.radius || 0),
opacity: 0.4
}, animation, function () {
isCbHandled = true;
fadeInNewPointAndDestoryOld(newPointObj, oldPoints, animation, 0.7);
});
if (oldPointObj.point.dataLabel &&
oldPointObj.point.dataLabel.y !== -9999 &&
newPointObj.point &&
newPointObj.point.dataLabel &&
newPointObj.point.dataLabel.alignAttr) {
oldPointObj.point.dataLabel.show();
oldPointObj.point.dataLabel.animate({
x: newPointObj.point.dataLabel.alignAttr.x,
y: newPointObj.point.dataLabel.alignAttr.y,
opacity: 0.4
}, animation);
}
}
}
});
// Make sure point is faded in.
syncTimeout(function () {
if (!isCbHandled) {
fadeInNewPointAndDestoryOld(newPointObj, oldPoints, animation, 0.85);
}
}, animDuration);
if (!isOldPointGrahic) {
syncTimeout(function () {
fadeInNewPointAndDestoryOld(newPointObj, oldPoints, animation, 0.1);
}, animDuration / 2);
}
}
}
};
Scatter.prototype.getGridOffset = function () {
var series = this,
chart = series.chart,
xAxis = series.xAxis,
yAxis = series.yAxis,
plotLeft = 0,
plotTop = 0;
if (series.dataMinX && series.dataMaxX) {
plotLeft = xAxis.reversed ?
xAxis.toPixels(series.dataMaxX) : xAxis.toPixels(series.dataMinX);
}
else {
plotLeft = chart.plotLeft;
}
if (series.dataMinY && series.dataMaxY) {
plotTop = yAxis.reversed ?
yAxis.toPixels(series.dataMinY) : yAxis.toPixels(series.dataMaxY);
}
else {
plotTop = chart.plotTop;
}
return { plotLeft: plotLeft, plotTop: plotTop };
};
Scatter.prototype.getScaledGridSize = function (options) {
var series = this,
xAxis = series.xAxis,
search = true,
k = 1,
divider = 1,
processedGridSize = options.processedGridSize ||
clusterDefaultOptions.layoutAlgorithm.gridSize,
gridSize,
scale,
level;
if (!series.gridValueSize) {
series.gridValueSize = Math.abs(xAxis.toValue(processedGridSize) - xAxis.toValue(0));
}
gridSize = xAxis.toPixels(series.gridValueSize) - xAxis.toPixels(0);
scale = +(processedGridSize / gridSize).toFixed(14);
// Find the level and its divider.
while (search && scale !== 1) {
level = Math.pow(2, k);
if (scale > 0.75 && scale < 1.25) {
search = false;
}
else if (scale >= (1 / level) && scale < 2 * (1 / level)) {
search = false;
divider = level;
}
else if (scale <= level && scale > level / 2) {
search = false;
divider = 1 / level;
}
k++;
}
return (processedGridSize / divider) / scale;
};
Scatter.prototype.getRealExtremes = function () {
var _a,
_b;
var series = this,
chart = series.chart,
xAxis = series.xAxis,
yAxis = series.yAxis,
realMinX = xAxis ? xAxis.toValue(chart.plotLeft) : 0,
realMaxX = xAxis ?
xAxis.toValue(chart.plotLeft + chart.plotWidth) : 0,
realMinY = yAxis ? yAxis.toValue(chart.plotTop) : 0,
realMaxY = yAxis ?
yAxis.toValue(chart.plotTop + chart.plotHeight) : 0;
if (realMinX > realMaxX) {
_a = [realMinX, realMaxX], realMaxX = _a[0], realMinX = _a[1];
}
if (realMinY > realMaxY) {
_b = [realMinY, realMaxY], realMaxY = _b[0], realMinY = _b[1];
}
return {
minX: realMinX,
maxX: realMaxX,
minY: realMinY,
maxY: realMaxY
};
};
Scatter.prototype.onDrillToCluster = function (event) {
var point = event.point || event.target;
point.firePointEvent('drillToCluster', event, function (e) {
var _a,
_b;
var point = e.point || e.target,
series = point.series,
xAxis = point.series.xAxis,
yAxis = point.series.yAxis,
chart = point.series.chart,
clusterOptions = series.options.cluster,
drillToCluster = (clusterOptions || {}).drillToCluster,
offsetX,
offsetY,
sortedDataX,
sortedDataY,
minX,
minY,
maxX,
maxY;
if (drillToCluster && point.clusteredData) {
sortedDataX = point.clusteredData.map(function (data) {
return data.x;
}).sort(function (a, b) { return a - b; });
sortedDataY = point.clusteredData.map(function (data) {
return data.y;
}).sort(function (a, b) { return a - b; });
minX = sortedDataX[0];
maxX = sortedDataX[sortedDataX.length - 1];
minY = sortedDataY[0];
maxY = sortedDataY[sortedDataY.length - 1];
offsetX = Math.abs((maxX - minX) * 0.1);
offsetY = Math.abs((maxY - minY) * 0.1);
chart.pointer.zoomX = true;
chart.pointer.zoomY = true;
// Swap when minus values.
if (minX > maxX) {
_a = [maxX, minX], minX = _a[0], maxX = _a[1];
}
if (minY > maxY) {
_b = [maxY, minY], minY = _b[0], maxY = _b[1];
}
chart.zoom({
originalEvent: e,
xAxis: [{
axis: xAxis,
min: minX - offsetX,
max: maxX + offsetX
}],
yAxis: [{
axis: yAxis,
min: minY - offsetY,
max: maxY + offsetY
}]
});
}
});
};
Scatter.prototype.getClusterDistancesFromPoint = function (clusters, pointX, pointY) {
var series = this,
xAxis = series.xAxis,
yAxis = series.yAxis,
pointClusterDistance = [],
j,
distance;
for (j = 0; j < clusters.length; j++) {
distance = Math.sqrt(Math.pow(xAxis.toPixels(pointX) -
xAxis.toPixels(clusters[j].posX), 2) +
Math.pow(yAxis.toPixels(pointY) -
yAxis.toPixels(clusters[j].posY), 2));
pointClusterDistance.push({
clusterIndex: j,
distance: distance
});
}
return pointClusterDistance.sort(function (a, b) { return a.distance - b.distance; });
};
// Point state used when animation is enabled to compare
// and bind old points with new ones.
Scatter.prototype.getPointsState = function (clusteredData, oldMarkerClusterInfo, dataLength) {
var oldDataStateArr = oldMarkerClusterInfo ?
getDataState(oldMarkerClusterInfo,
dataLength) : [],
newDataStateArr = getDataState(clusteredData,
dataLength),
state = {},
newState,
oldState,
i;
// Clear global array before populate with new ids.
oldPointsStateId = [];
// Build points state structure.
clusteredData.clusters.forEach(function (cluster) {
state[cluster.stateId] = {
x: cluster.x,
y: cluster.y,
id: cluster.stateId,
point: cluster.point,
parentsId: []
};
});
clusteredData.noise.forEach(function (noise) {
state[noise.stateId] = {
x: noise.x,
y: noise.y,
id: noise.stateId,
point: noise.point,
parentsId: []
};
});
// Bind new and old state.
for (i = 0; i < newDataStateArr.length; i++) {
newState = newDataStateArr[i];
oldState = oldDataStateArr[i];
if (newState &&
oldState &&
newState.parentStateId &&
oldState.parentStateId &&
state[newState.parentStateId] &&
state[newState.parentStateId].parentsId.indexOf(oldState.parentStateId) === -1) {
state[newState.parentStateId].parentsId.push(oldState.parentStateId);
if (oldPointsStateId.indexOf(oldState.parentStateId) === -1) {
oldPointsStateId.push(oldState.parentStateId);
}
}
}
return state;
};
Scatter.prototype.markerClusterAlgorithms = {
grid: function (dataX, dataY, dataIndexes, options) {
var series = this,
xAxis = series.xAxis,
yAxis = series.yAxis,
grid = {},
gridOffset = series.getGridOffset(),
scaledGridSize,
x,
y,
gridX,
gridY,
key,
i;
// drawGridLines(series, options);
scaledGridSize = series.getScaledGridSize(options);
for (i = 0; i < dataX.length; i++) {
x = xAxis.toPixels(dataX[i]) - gridOffset.plotLeft;
y = yAxis.toPixels(dataY[i]) - gridOffset.plotTop;
gridX = Math.floor(x / scaledGridSize);
gridY = Math.floor(y / scaledGridSize);
key = gridY + '-' + gridX;
if (!grid[key]) {
grid[key] = [];
}
grid[key].push({
dataIndex: dataIndexes[i],
x: dataX[i],
y: dataY[i]
});
}
return grid;
},
kmeans: function (dataX, dataY, dataIndexes, options) {
var series = this,
clusters = [],
noise = [],
group = {},
pointMaxDistance = options.processedDistance ||
clusterDefaultOptions.layoutAlgorithm.distance,
iterations = options.iterations,
// Max pixel difference beetwen new and old cluster position.
maxClusterShift = 1,
currentIteration = 0,
repeat = true,
pointX = 0,
pointY = 0,
tempPos,
pointClusterDistance = [],
groupedData,
key,
i,
j;
options.processedGridSize = options.processedDistance;
// Use grid method to get groupedData object.
groupedData = series.markerClusterAlgorithms ?
series.markerClusterAlgorithms.grid.call(series, dataX, dataY, dataIndexes, options) : {};
// Find clusters amount and its start positions
// based on grid grouped data.
for (key in groupedData) {
if (groupedData[key].length > 1) {
tempPos = getClusterPosition(groupedData[key]);
clusters.push({
posX: tempPos.x,
posY: tempPos.y,
oldX: 0,
oldY: 0,
startPointsLen: groupedData[key].length,
points: []
});
}
}
// Start kmeans iteration process.
while (repeat) {
clusters.map(function (c) {
c.points.length = 0;
return c;
});
noise.length = 0;
for (i = 0; i < dataX.length; i++) {
pointX = dataX[i];
pointY = dataY[i];
pointClusterDistance = series.getClusterDistancesFromPoint(clusters, pointX, pointY);
if (pointClusterDistance.length &&
pointClusterDistance[0].distance < pointMaxDistance) {
clusters[pointClusterDistance[0].clusterIndex].points.push({
x: pointX,
y: pointY,
dataIndex: dataIndexes[i]
});
}
else {
noise.push({
x: pointX,
y: pointY,
dataIndex: dataIndexes[i]
});
}
}
// When cluster points array has only one point the
// point should be classified again.
for (j = 0; j < clusters.length; j++) {
if (clusters[j].points.length === 1) {
pointClusterDistance = series.getClusterDistancesFromPoint(clusters, clusters[j].points[0].x, clusters[j].points[0].y);
if (pointClusterDistance[1].distance < pointMaxDistance) {
// Add point to the next closest cluster.
clusters[pointClusterDistance[1].clusterIndex].points
.push(clusters[j].points[0]);
// Clear points array.
clusters[pointClusterDistance[0].clusterIndex]
.points.length = 0;
}
}
}
// Compute a new clusters position and check if it
// is different than the old one.
repeat = false;
for (j = 0; j < clusters.length; j++) {
tempPos = getClusterPosition(clusters[j].points);
clusters[j].oldX = clusters[j].posX;
clusters[j].oldY = clusters[j].posY;
clusters[j].posX = tempPos.x;
clusters[j].posY = tempPos.y;
// Repeat the algorithm if at least one cluster
// is shifted more than maxClusterShift property.
if (clusters[j].posX > clusters[j].oldX + maxClusterShift ||
clusters[j].posX < clusters[j].oldX - maxClusterShift ||
clusters[j].posY > clusters[j].oldY + maxClusterShift ||
clusters[j].posY < clusters[j].oldY - maxClusterShift) {
repeat = true;
}
}
// If iterations property is set repeat the algorithm
// specified amount of times.
if (iterations) {
repeat = currentIteration < iterations - 1;
}
currentIteration++;
}
clusters.forEach(function (cluster, i) {
group['cluster' + i] = cluster.points;
});
noise.forEach(function (noise, i) {
group['noise' + i] = [noise];
});
return group;
},
optimizedKmeans: function (processedXData, processedYData, dataIndexes, options) {
var series = this,
xAxis = series.xAxis,
yAxis = series.yAxis,
pointMaxDistance = options.processedDistance ||
clusterDefaultOptions.layoutAlgorithm.gridSize,
group = {},
extremes = series.getRealExtremes(),
clusterMarkerOptions = (series.options.cluster || {}).marker,
offset,
distance,
radius;
if (!series.markerClusterInfo || (series.initMaxX && series.initMaxX < extremes.maxX ||
series.initMinX && series.initMinX > extremes.minX ||
series.initMaxY && series.initMaxY < extremes.maxY ||
series.initMinY && series.initMinY > extremes.minY)) {
series.initMaxX = extremes.maxX;
series.initMinX = extremes.minX;
series.initMaxY = extremes.maxY;
series.initMinY = extremes.minY;
group = series.markerClusterAlgorithms ?
series.markerClusterAlgorithms.kmeans.call(series, processedXData, processedYData, dataIndexes, options) : {};
series.baseClusters = null;
}
else {
if (!series.baseClusters) {
series.baseClusters = {
clusters: series.markerClusterInfo.clusters,
noise: series.markerClusterInfo.noise
};
}
series.baseClusters.clusters.forEach(function (cluster) {
cluster.pointsOutside = [];
cluster.pointsInside = [];
cluster.data.forEach(function (dataPoint) {
distance = Math.sqrt(Math.pow(xAxis.toPixels(dataPoint.x) -
xAxis.toPixels(cluster.x), 2) +
Math.pow(yAxis.toPixels(dataPoint.y) -
yAxis.toPixels(cluster.y), 2));
if (cluster.clusterZone &&
cluster.clusterZone.marker &&
cluster.clusterZone.marker.radius) {
radius = cluster.clusterZone.marker.radius;
}
else if (clusterMarkerOptions &&
clusterMarkerOptions.radius) {
radius = clusterMarkerOptions.radius;
}
else {
radius = clusterDefaultOptions.marker.radius;
}
offset = pointMaxDistance - radius >= 0 ?
pointMaxDistance - radius : radius;
if (distance > radius + offset &&
defined(cluster.pointsOutside)) {
cluster.pointsOutside.push(dataPoint);
}
else if (defined(cluster.pointsInside)) {
cluster.pointsInside.push(dataPoint);
}
});
if (cluster.pointsInside.length) {
group[cluster.id] = cluster.pointsInside;
}
cluster.pointsOutside.forEach(function (p, i) {
group[cluster.id + '_noise' + i] = [p];
});
});
series.baseClusters.noise.forEach(function (noise) {
group[noise.id] = noise.data;
});
}
return group;
}
};
Scatter.prototype.preventClusterCollisions = function (props) {
var series = this,
xAxis = series.xAxis,
yAxis = series.yAxis,
_a = props.key.split('-').map(parseFloat),
gridY = _a[0],
gridX = _a[1],
gridSize = props.gridSize,
groupedData = props.groupedData,
defaultRadius = props.defaultRadius,
clusterRadius = props.clusterRadius,
gridXPx = gridX * gridSize,
gridYPx = gridY * gridSize,
xPixel = xAxis.toPixels(props.x),
yPixel = yAxis.toPixels(props.y),
gridsToCheckCollision = [],
pointsLen = 0,
radius = 0,
clusterMarkerOptions = (series.options.cluster || {}).marker,
zoneOptions = (series.options.cluster || {}).zones,
gridOffset = series.getGridOffset(),
nextXPixel,
nextYPixel,
signX,
signY,
cornerGridX,
cornerGridY,
i,
j,
itemX,
itemY,
nextClusterPos,
maxDist,
keys,
x,
y;
// Distance to the grid start.
xPixel -= gridOffset.plotLeft;
yPixel -= gridOffset.plotTop;
for (i = 1; i < 5; i++) {
signX = i % 2 ? -1 : 1;
signY = i < 3 ? -1 : 1;
cornerGridX = Math.floor((xPixel + signX * clusterRadius) / gridSize);
cornerGridY = Math.floor((yPixel + signY * clusterRadius) / gridSize);
keys = [
cornerGridY + '-' + cornerGridX,
cornerGridY + '-' + gridX,
gridY + '-' + cornerGridX
];
for (j = 0; j < keys.length; j++) {
if (gridsToCheckCollision.indexOf(keys[j]) === -1 &&
keys[j] !== props.key) {
gridsToCheckCollision.push(keys[j]);
}
}
}
gridsToCheckCollision.forEach(function (item) {
var _a;
if (groupedData[item]) {
// Cluster or noise position is already computed.
if (!groupedData[item].posX) {
nextClusterPos = getClusterPosition(groupedData[item]);
groupedData[item].posX = nextClusterPos.x;
groupedData[item].posY = nextClusterPos.y;
}
nextXPixel = xAxis.toPixels(groupedData[item].posX || 0) -
gridOffset.plotLeft;
nextYPixel = yAxis.toPixels(groupedData[item].posY || 0) -
gridOffset.plotTop;
_a = item.split('-').map(parseFloat), itemY = _a[0], itemX = _a[1];
if (zoneOptions) {
pointsLen = groupedData[item].length;
for (i = 0; i < zoneOptions.length; i++) {
if (pointsLen >= zoneOptions[i].from &&
pointsLen <= zoneOptions[i].to) {
if (defined((zoneOptions[i].marker || {}).radius)) {
radius = zoneOptions[i].marker.radius || 0;
}
else if (clusterMarkerOptions &&
clusterMarkerOptions.radius) {
radius = clusterMarkerOptions.radius;
}
else {
radius = clusterDefaultOptions.marker.radius;
}
}
}
}
if (groupedData[item].length > 1 &&
radius === 0 &&
clusterMarkerOptions &&
clusterMarkerOptions.radius) {
radius = clusterMarkerOptions.radius;
}
else if (groupedData[item].length === 1) {
radius = defaultRadius;
}
maxDist = clusterRadius + radius;
radius = 0;
if (itemX !== gridX &&
Math.abs(xPixel - nextXPixel) < maxDist) {
xPixel = itemX - gridX < 0 ? gridXPx + clusterRadius :
gridXPx + gridSize - clusterRadius;
}
if (itemY !== gridY &&
Math.abs(yPixel - nextYPixel) < maxDist) {
yPixel = itemY - gridY < 0 ? gridYPx + clusterRadius :
gridYPx + gridSize - clusterRadius;
}
}
});
x = xAxis.toValue(xPixel + gridOffset.plotLeft);
y = yAxis.toValue(yPixel + gridOffset.plotTop);
groupedData[props.key].posX = x;
groupedData[props.key].posY = y;
return { x: x, y: y };
};
// Check if user algorithm result is valid groupedDataObject.
Scatter.prototype.isValidGroupedDataObject = function (groupedData) {
var result = false,
i;
if (!isObject(groupedData)) {
return false;
}
objectEach(groupedData, function (elem) {
result = true;
if (!isArray(elem) || !elem.length) {
result = false;
return;
}
for (i = 0; i < elem.length; i++) {
if (!isObject(elem[i]) || (!elem[i].x || !elem[i].y)) {
result = false;
return;
}
}
});
return result;
};
Scatter.prototype.getClusteredData = function (groupedData, options) {
var series = this,
groupedXData = [],
groupedYData = [],
clusters = [], // Container for clusters.
noise = [], // Container for points not belonging to any cluster.
groupMap = [],
index = 0,
// Prevent minimumClusterSize lower than 2.
minimumClusterSize = Math.max(2,
options.minimumClusterSize || 2),
stateId,
point,
points,
pointUserOptions,
pointsLen,
marker,
clusterPos,
pointOptions,
clusterTempPos,
zoneOptions,
clusterZone,
clusterZoneClassName,
i,
k;
// Check if groupedData is valid when user uses a custom algorithm.
if (isFunction(options.layoutAlgorithm.type) &&
!series.isValidGroupedDataObject(groupedData)) {
error('Highcharts marker-clusters module: ' +
'The custom algorithm result is not valid!', false, series.chart);
return false;
}
for (k in groupedData) {
if (groupedData[k].length >= minimumClusterSize) {
points = groupedData[k];
stateId = getStateId();
pointsLen = points.length;
// Get zone options for cluster.
if (options.zones) {
for (i = 0; i < options.zones.length; i++) {
if (pointsLen >= options.zones[i].from &&
pointsLen <= options.zones[i].to) {
clusterZone = options.zones[i];
clusterZone.zoneIndex = i;
zoneOptions = options.zones[i].marker;
clusterZoneClassName = options.zones[i].className;
}
}
}
clusterTempPos = getClusterPosition(points);
if (options.layoutAlgorithm.type === 'grid' &&
!options.allowOverlap) {
marker = series.options.marker || {};
clusterPos = series.preventClusterCollisions({
x: clusterTempPos.x,
y: clusterTempPos.y,
key: k,
groupedData: groupedData,
gridSize: series.getScaledGridSize(options.layoutAlgorithm),
defaultRadius: marker.radius || 3 + (marker.lineWidth || 0),
clusterRadius: (zoneOptions && zoneOptions.radius) ?
zoneOptions.radius :
(options.marker || {}).radius ||
clusterDefaultOptions.marker.radius
});
}
else {
clusterPos = {
x: clusterTempPos.x,
y: clusterTempPos.y
};
}
for (i = 0; i < pointsLen; i++) {
points[i].parentStateId = stateId;
}
clusters.push({
x: clusterPos.x,
y: clusterPos.y,
id: k,
stateId: stateId,
index: index,
data: points,
clusterZone: clusterZone,
clusterZoneClassName: clusterZoneClassName
});
groupedXData.push(clusterPos.x);
groupedYData.push(clusterPos.y);
groupMap.push({
options: {
formatPrefix: 'cluster',
dataLabels: options.dataLabels,
marker: merge(options.marker, {
states: options.states
}, zoneOptions || {})
}
});
// Save cluster data points options.
if (series.options.data && series.options.data.length) {
for (i = 0; i < pointsLen; i++) {
if (isObject(series.options.data[points[i].dataIndex])) {
points[i].options =
series.options.data[points[i].dataIndex];
}
}
}
index++;
zoneOptions = null;
}
else {
for (i = 0; i < groupedData[k].length; i++) {
// Points not belonging to any cluster.
point = groupedData[k][i];
stateId = getStateId();
pointOptions = null;
pointUserOptions =
((series.options || {}).data || [])[point.dataIndex];
groupedXData.push(point.x);
groupedYData.push(point.y);
point.parentStateId = stateId;
noise.push({
x: point.x,
y: point.y,
id: k,
stateId: stateId,
index: index,
data: groupedData[k]
});
if (pointUserOptions &&
typeof pointUserOptions === 'object' &&
!isArray(pointUserOptions)) {
pointOptions = merge(pointUserOptions, { x: point.x, y: point.y });
}
else {
pointOptions = {
userOptions: pointUserOptions,
x: point.x,
y: point.y
};
}
groupMap.push({ options: pointOptions });
index++;
}
}
}
return {
clusters: clusters,
noise: noise,
groupedXData: groupedXData,
groupedYData: groupedYData,
groupMap: groupMap
};
};
// Destroy clustered data points.
Scatter.prototype.destroyClusteredData = function () {
var clusteredSeriesData = this.markerClusterSeriesData;
// Clear previous groups.
(clusteredSeriesData || []).forEach(function (point) {
if (point && point.destroy) {
point.destroy();
}
});
this.markerClusterSeriesData = null;
};
// Hide clustered data points.
Scatter.prototype.hideClusteredData = function () {
var series = this,
clusteredSeriesData = this.markerClusterSeriesData,
oldState = ((series.markerClusterInfo || {}).pointsState || {}).oldState || {},
oldPointsId = oldPointsStateId.map(function (elem) {
return (oldState[elem].point || {}).id || '';
});
(clusteredSeriesData || []).forEach(function (point) {
// If an old point is used in animation hide it, otherwise destroy.
if (point &&
oldPointsId.indexOf(point.id) !== -1) {
if (point.graphic) {
point.graphic.hide();
}
if (point.dataLabel) {
point.dataLabel.hide();
}
}
else {
if (point && point.destroy) {
point.destroy();
}
}
});
};
// Override the generatePoints method by adding a reference to grouped data.
Scatter.prototype.generatePoints = function () {
var series = this,
chart = series.chart,
xAxis = series.xAxis,
yAxis = series.yAxis,
clusterOptions = series.options.cluster,
realExtremes = series.getRealExtremes(),
visibleXData = [],
visibleYData = [],
visibleDataIndexes = [],
oldPointsState,
oldDataLen,
oldMarkerClusterInfo,
kmeansThreshold,
cropDataOffsetX,
cropDataOffsetY,
seriesMinX,
seriesMaxX,
seriesMinY,
seriesMaxY,
type,
algorithm,
clusteredData,
groupedData,
layoutAlgOptions,
point,
i;
if (clusterOptions &&
clusterOptions.enabled &&
series.xData &&
series.yData &&
!chart.polar) {
type = clusterOptions.layoutAlgorithm.type;
layoutAlgOptions = clusterOptions.layoutAlgorithm;
// Get processed algorithm properties.
layoutAlgOptions.processedGridSize = relativeLength(layoutAlgOptions.gridSize ||
clusterDefaultOptions.layoutAlgorithm.gridSize, chart.plotWidth);
layoutAlgOptions.processedDistance = relativeLength(layoutAlgOptions.distance ||
clusterDefaultOptions.layoutAlgorithm.distance, chart.plotWidth);
kmeansThreshold = layoutAlgOptions.kmeansThreshold ||
clusterDefaultOptions.layoutAlgorithm.kmeansThreshold;
// Offset to prevent cluster size changes.
cropDataOffsetX = Math.abs(xAxis.toValue(layoutAlgOptions.processedGridSize / 2) -
xAxis.toValue(0));
cropDataOffsetY = Math.abs(yAxis.toValue(layoutAlgOptions.processedGridSize / 2) -
yAxis.toValue(0));
// Get only visible data.
for (i = 0; i < series.xData.length; i++) {
if (!series.dataMaxX) {
if (!defined(seriesMaxX) ||
!defined(seriesMinX) ||
!defined(seriesMaxY) ||
!defined(seriesMinY)) {
seriesMaxX = seriesMinX = series.xData[i];
seriesMaxY = seriesMinY = series.yData[i];
}
else if (isNumber(series.yData[i]) &&
isNumber(seriesMaxY) &&
isNumber(seriesMinY)) {
seriesMaxX = Math.max(series.xData[i], seriesMaxX);
seriesMinX = Math.min(series.xData[i], seriesMinX);
seriesMaxY = Math.max(series.yData[i] || seriesMaxY, seriesMaxY);
seriesMinY = Math.min(series.yData[i] || seriesMinY, seriesMinY);
}
}
// Crop data to visible ones with appropriate offset to prevent
// cluster size changes on the edge of the plot area.
if (series.xData[i] >= (realExtremes.minX - cropDataOffsetX) &&
series.xData[i] <= (realExtremes.maxX + cropDataOffsetX) &&
(series.yData[i] || realExtremes.minY) >=
(realExtremes.minY - cropDataOffsetY) &&
(series.yData[i] || realExtremes.maxY) <=
(realExtremes.maxY + cropDataOffsetY)) {
visibleXData.push(series.xData[i]);
visibleYData.push(series.yData[i]);
visibleDataIndexes.push(i);
}
}
// Save data max values.
if (defined(seriesMaxX) && defined(seriesMinX) &&
isNumber(seriesMaxY) && isNumber(seriesMinY)) {
series.dataMaxX = seriesMaxX;
series.dataMinX = seriesMinX;
series.dataMaxY = seriesMaxY;
series.dataMinY = seriesMinY;
}
if (isFunction(type)) {
algorithm = type;
}
else if (series.markerClusterAlgorithms) {
if (type && series.markerClusterAlgorithms[type]) {
algorithm = series.markerClusterAlgorithms[type];
}
else {
algorithm = visibleXData.length < kmeansThreshold ?
series.markerClusterAlgorithms.kmeans :
series.markerClusterAlgorithms.grid;
}
}
else {
algorithm = function () {
return false;
};
}
groupedData = algorithm.call(this, visibleXData, visibleYData, visibleDataIndexes, layoutAlgOptions);
clusteredData = groupedData ? series.getClusteredData(groupedData, clusterOptions) : groupedData;
// When animation is enabled get old points state.
if (clusterOptions.animation &&
series.markerClusterInfo &&
series.markerClusterInfo.pointsState &&
series.markerClusterInfo.pointsState.oldState) {
// Destroy old points.
destroyOldPoints(series.markerClusterInfo.pointsState.oldState);
oldPointsState = series.markerClusterInfo.pointsState.newState;
}
else {
oldPointsState = {};
}
// Save points old state info.
oldDataLen = series.xData.length;
oldMarkerClusterInfo = series.markerClusterInfo;
if (clusteredData) {
series.processedXData = clusteredData.groupedXData;
series.processedYData = clusteredData.groupedYData;
series.hasGroupedData = true;
series.markerClusterInfo = clusteredData;
series.groupMap = clusteredData.groupMap;
}
baseGeneratePoints.apply(this);
if (clusteredData && series.markerClusterInfo) {
// Mark cluster points. Safe point reference in the cluster object.
(series.markerClusterInfo.clusters || []).forEach(function (cluster) {
point = series.points[cluster.index];
point.isCluster = true;
point.clusteredData = cluster.data;
point.clusterPointsAmount = cluster.data.length;
cluster.point = point;
// Add zoom to cluster range.
addEvent(point, 'click', series.onDrillToCluster);
});
// Safe point reference in the noise object.
(series.markerClusterInfo.noise || []).forEach(function (noise) {
noise.point = series.points[noise.index];
});
// When animation is enabled save points state.
if (clusterOptions.animation &&
series.markerClusterInfo) {
series.markerClusterInfo.pointsState = {
oldState: oldPointsState,
newState: series.getPointsState(clusteredData, oldMarkerClusterInfo, oldDataLen)
};
}
// Record grouped data in order to let it be destroyed the next time
// processData runs.
if (!clusterOptions.animation) {
this.destroyClusteredData();
}
else {
this.hideClusteredData();
}
this.markerClusterSeriesData =
this.hasGroupedData ? this.points : null;
}
}
else {
baseGeneratePoints.apply(this);
}
};
// Handle animation.
addEvent(Chart, 'render', function () {
var chart = this;
(chart.series || []).forEach(function (series) {
if (series.markerClusterInfo) {
var options = series.options.cluster,
pointsState = (series.markerClusterInfo || {}).pointsState,
oldState = (pointsState || {}).oldState;
if ((options || {}).animation &&
series.markerClusterInfo &&
series.chart.pointer.pinchDown.length === 0 &&
(series.xAxis.eventArgs || {}).trigger !== 'pan' &&
oldState &&
Object.keys(oldState).length) {
series.markerClusterInfo.clusters.forEach(function (cluster) {
series.animateClusterPoint(cluster);
});
series.markerClusterInfo.noise.forEach(function (noise) {
series.animateClusterPoint(noise);
});
}
}
});
});
// Override point prototype to throw a warning when trying to update
// clustered point.
addEvent(Point, 'update', function () {
if (this.dataGroup) {
error('Highcharts marker-clusters module: ' +
'Running `Point.update` when point belongs to clustered series' +
' is not supported.', false, this.series.chart);
return false;
}
});
// Destroy grouped data on series destroy.
addEvent(Series, 'destroy', Scatter.prototype.destroyClusteredData);
// Add classes, change mouse cursor.
addEvent(Series, 'afterRender', function () {
var series = this,
clusterZoomEnabled = (series.options.cluster || {}).drillToCluster;
if (series.markerClusterInfo && series.markerClusterInfo.clusters) {
series.markerClusterInfo.clusters.forEach(function (cluster) {
if (cluster.point && cluster.point.graphic) {
cluster.point.graphic.addClass('highcharts-cluster-point');
// Change cursor to pointer when drillToCluster is enabled.
if (clusterZoomEnabled && cluster.point) {
cluster.point.graphic.css({
cursor: 'pointer'
});
if (cluster.point.dataLabel) {
cluster.point.dataLabel.css({
cursor: 'pointer'
});
}
}
if (defined(cluster.clusterZone)) {
cluster.point.graphic.addClass(cluster.clusterZoneClassName ||
'highcharts-cluster-zone-' +
cluster.clusterZone.zoneIndex);
}
}
});
}
});
addEvent(Point, 'drillToCluster', function (event) {
var point = event.point || event.target,
series = point.series,
clusterOptions = series.options.cluster,
onDrillToCluster = ((clusterOptions || {}).events || {}).drillToCluster;
if (isFunction(onDrillToCluster)) {
onDrillToCluster.call(this, event);
}
});
// Destroy the old tooltip after zoom.
addEvent(Axis, 'setExtremes', function () {
var chart = this.chart,
animationDuration = 0,
animation;
chart.series.forEach(function (series) {
if (series.markerClusterInfo) {
animation = animObject((series.options.cluster || {}).animation);
animationDuration = animation.duration || 0;
}
});
syncTimeout(function () {
if (chart.tooltip) {
chart.tooltip.destroy();
}
}, animationDuration);
});
});
_registerModule(_modules, 'masters/modules/marker-clusters.src.js', [], function () {
});
})); | cdnjs/cdnjs | ajax/libs/highcharts/8.2.2/modules/marker-clusters.src.js | JavaScript | mit | 81,899 |
/**
* WonderPlugin Carousel Skin Options
* Copyright 2014 Magic Hills Pty Ltd - http://www.wonderplugin.com
*/
var WONDERPLUGIN_CAROUSEL_SKIN_OPTIONS = {
classic : {
width:240,
height:180,
skinsfoldername:"",
arrowhideonmouseleave:1000,
itembottomshadowimagetop:100,
navheight:16,
random:false,
showbottomshadow:false,
arrowheight:32,
itembackgroundimagewidth:100,
skin:"classic",
responsive:true,
bottomshadowimage:"bottomshadow-110-95-0.png",
enabletouchswipe:true,
navstyle:"bullets",
backgroundimagetop:-40,
arrowstyle:"always",
bottomshadowimagetop:95,
hoveroverlayimage:"hoveroverlay-64-64-3.png",
itembottomshadowimage:"itembottomshadow-100-100-5.png",
showitembottomshadow:false,
transitioneasing:"easeOutExpo",
showitembackgroundimage:false,
itembackgroundimage:"",
playvideoimagepos:"center",
circular:true,
arrowimage:"arrows-32-32-2.png",
direction:"horizontal",
navimage:"bullet-16-16-0.png",
itembackgroundimagetop:0,
showbackgroundimage:false,
lightboxbarheight:48,
showplayvideo:true,
spacing:18,
scrollitems:1,
showhoveroverlay:true,
scrollmode:"page",
navdirection:"horizontal",
itembottomshadowimagewidth:100,
backgroundimage:"",
autoplay:true,
arrowwidth:32,
pauseonmouseover:true,
navmode:"page",
interval:3000,
backgroundimagewidth:110,
navspacing:8,
playvideoimage:"playvideo-64-64-0.png",
visibleitems:3,
navswitchonmouseover:false,
bottomshadowimagewidth:110,
screenquery:'{\n "tablet": {\n "screenwidth": 900,\n "visibleitems": 2\n },\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}',
navwidth:16,
loop:0,
transitionduration:1000
},
gallery: {
width:240,
height:180,
skinsfoldername:"",
arrowhideonmouseleave:1000,
itembottomshadowimagetop:99,
navheight:16,
random:false,
showbottomshadow:false,
arrowheight:48,
itembackgroundimagewidth:100,
skin:"gallery",
responsive:true,
bottomshadowimage:"bottomshadow-110-95-0.png",
enabletouchswipe:true,
navstyle:"bullets",
backgroundimagetop:-40,
arrowstyle:"always",
bottomshadowimagetop:95,
hoveroverlayimage:"hoveroverlay-64-64-5.png",
itembottomshadowimage:"itembottomshadow-100-98-3.png",
showitembottomshadow:false,
transitioneasing:"easeOutExpo",
showitembackgroundimage:false,
itembackgroundimage:"",
playvideoimagepos:"center",
circular:true,
arrowimage:"arrows-48-48-2.png",
direction:"horizontal",
navimage:"bullet-16-16-0.png",
itembackgroundimagetop:0,
showbackgroundimage:false,
lightboxbarheight:48,
showplayvideo:true,
spacing:4,
scrollitems:1,
showhoveroverlay:true,
scrollmode:"page",
navdirection:"horizontal",
itembottomshadowimagewidth:100,
backgroundimage:"",
autoplay:true,
arrowwidth:48,
pauseonmouseover:true,
navmode:"page",
interval:3000,
backgroundimagewidth:110,
navspacing:8,
playvideoimage:"playvideo-64-64-0.png",
visibleitems:3,
navswitchonmouseover:false,
bottomshadowimagewidth:110,
screenquery:'{\n "tablet": {\n "screenwidth": 900,\n "visibleitems": 2\n },\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}',
navwidth:16,
loop:0,
transitionduration:1000
},
highlight: {
width:240,
height:180,
skinsfoldername:"",
arrowhideonmouseleave:1000,
itembottomshadowimagetop:99,
navheight:16,
random:false,
showbottomshadow:false,
arrowheight:48,
itembackgroundimagewidth:100,
skin:"highlight",
responsive:true,
bottomshadowimage:"bottomshadow-110-95-0.png",
enabletouchswipe:true,
navstyle:"bullets",
backgroundimagetop:-40,
arrowstyle:"always",
bottomshadowimagetop:95,
hoveroverlayimage:"hoveroverlay-64-64-5.png",
itembottomshadowimage:"itembottomshadow-100-98-3.png",
showitembottomshadow:true,
transitioneasing:"easeOutExpo",
showitembackgroundimage:false,
itembackgroundimage:"",
playvideoimagepos:"center",
circular:true,
arrowimage:"arrows-48-48-2.png",
direction:"horizontal",
navimage:"bullet-16-16-0.png",
itembackgroundimagetop:0,
showbackgroundimage:false,
lightboxbarheight:48,
showplayvideo:true,
spacing:4,
scrollitems:1,
showhoveroverlay:true,
scrollmode:"page",
navdirection:"horizontal",
itembottomshadowimagewidth:100,
backgroundimage:"",
autoplay:true,
arrowwidth:48,
pauseonmouseover:true,
navmode:"page",
interval:3000,
backgroundimagewidth:110,
navspacing:8,
playvideoimage:"playvideo-64-64-0.png",
visibleitems:3,
navswitchonmouseover:false,
bottomshadowimagewidth:110,
screenquery:'{\n "tablet": {\n "screenwidth": 900,\n "visibleitems": 2\n },\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}',
navwidth:16,
loop:0,
transitionduration:1000
},
list: {
width:240,
height:180,
skinsfoldername:"",
arrowhideonmouseleave:1000,
itembottomshadowimagetop:99,
navheight:12,
random:false,
showbottomshadow:false,
arrowheight:28,
itembackgroundimagewidth:100,
skin:"list",
responsive:true,
bottomshadowimage:"bottomshadow-110-95-0.png",
enabletouchswipe:true,
navstyle:"bullets",
backgroundimagetop:-40,
arrowstyle:"always",
bottomshadowimagetop:95,
hoveroverlayimage:"hoveroverlay-64-64-5.png",
itembottomshadowimage:"itembottomshadow-100-98-3.png",
showitembottomshadow:false,
transitioneasing:"easeOutExpo",
showitembackgroundimage:false,
itembackgroundimage:"",
playvideoimagepos:"center",
circular:true,
arrowimage:"arrows-28-28-0.png",
direction:"vertical",
navimage:"bullet-12-12-1.png",
itembackgroundimagetop:0,
showbackgroundimage:false,
lightboxbarheight:48,
showplayvideo:true,
spacing:8,
scrollitems:1,
showhoveroverlay:true,
scrollmode:"page",
navdirection:"horizontal",
itembottomshadowimagewidth:100,
backgroundimage:"",
autoplay:true,
arrowwidth:28,
pauseonmouseover:true,
navmode:"page",
interval:3000,
backgroundimagewidth:110,
navspacing:4,
playvideoimage:"playvideo-64-64-0.png",
visibleitems:3,
navswitchonmouseover:false,
bottomshadowimagewidth:110,
screenquery:'{\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}',
navwidth:12,
loop:0,
transitionduration:1000
},
navigator: {
width:240,
height:180,
skinsfoldername:"",
arrowhideonmouseleave:1000,
itembottomshadowimagetop:99,
navheight:12,
random:false,
showbottomshadow:false,
arrowheight:28,
itembackgroundimagewidth:100,
skin:"navigator",
responsive:true,
bottomshadowimage:"bottomshadow-110-95-0.png",
enabletouchswipe:true,
navstyle:"bullets",
backgroundimagetop:-40,
arrowstyle:"always",
bottomshadowimagetop:95,
hoveroverlayimage:"hoveroverlay-64-64-5.png",
itembottomshadowimage:"itembottomshadow-100-98-3.png",
showitembottomshadow:false,
transitioneasing:"easeOutExpo",
showitembackgroundimage:false,
itembackgroundimage:"",
playvideoimagepos:"center",
circular:true,
arrowimage:"arrows-28-28-0.png",
direction:"horizontal",
navimage:"bullet-12-12-1.png",
itembackgroundimagetop:0,
showbackgroundimage:false,
lightboxbarheight:48,
showplayvideo:true,
spacing:4,
scrollitems:1,
showhoveroverlay:true,
scrollmode:"page",
navdirection:"horizontal",
itembottomshadowimagewidth:100,
backgroundimage:"",
autoplay:true,
arrowwidth:28,
pauseonmouseover:true,
navmode:"page",
interval:3000,
backgroundimagewidth:110,
navspacing:4,
playvideoimage:"playvideo-64-64-0.png",
visibleitems:2,
navswitchonmouseover:false,
bottomshadowimagewidth:110,
screenquery:'{\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}',
navwidth:12,
loop:0,
transitionduration:1000
},
showcase: {
width:240,
height:180,
skinsfoldername:"",
arrowhideonmouseleave:1000,
itembottomshadowimagetop:99,
navheight:16,
random:false,
showbottomshadow:false,
arrowheight:32,
itembackgroundimagewidth:100,
skin:"showcase",
responsive:true,
bottomshadowimage:"bottomshadow-110-95-0.png",
enabletouchswipe:true,
navstyle:"bullets",
backgroundimagetop:-40,
arrowstyle:"none",
bottomshadowimagetop:95,
hoveroverlayimage:"hoveroverlay-64-64-5.png",
itembottomshadowimage:"itembottomshadow-100-98-3.png",
showitembottomshadow:false,
transitioneasing:"easeOutExpo",
showitembackgroundimage:false,
itembackgroundimage:"",
playvideoimagepos:"center",
circular:true,
arrowimage:"arrows-32-32-4.png",
direction:"vertical",
navimage:"bullet-16-16-0.png",
itembackgroundimagetop:0,
showbackgroundimage:false,
lightboxbarheight:48,
showplayvideo:true,
spacing:8,
scrollitems:1,
showhoveroverlay:true,
scrollmode:"page",
navdirection:"vertical",
itembottomshadowimagewidth:100,
backgroundimage:"",
autoplay:true,
arrowwidth:32,
pauseonmouseover:true,
navmode:"page",
interval:3000,
backgroundimagewidth:110,
navspacing:8,
playvideoimage:"playvideo-64-64-0.png",
visibleitems:1,
navswitchonmouseover:true,
bottomshadowimagewidth:110,
screenquery:'{\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}',
navwidth:16,
loop:0,
transitionduration:1000
},
simplicity: {
width:240,
height:180,
skinsfoldername:"",
arrowhideonmouseleave:1000,
itembottomshadowimagetop:100,
navheight:16,
random:false,
showbottomshadow:false,
arrowheight:32,
itembackgroundimagewidth:100,
skin:"simplicity",
responsive:true,
bottomshadowimage:"bottomshadow-110-95-0.png",
enabletouchswipe:true,
navstyle:"none",
backgroundimagetop:-40,
arrowstyle:"always",
bottomshadowimagetop:95,
hoveroverlayimage:"hoveroverlay-64-64-6.png",
itembottomshadowimage:"itembottomshadow-100-100-5.png",
showitembottomshadow:false,
transitioneasing:"easeOutExpo",
showitembackgroundimage:false,
itembackgroundimage:"",
playvideoimagepos:"center",
circular:true,
arrowimage:"arrows-32-32-1.png",
direction:"horizontal",
navimage:"bullet-16-16-0.png",
itembackgroundimagetop:0,
showbackgroundimage:false,
lightboxbarheight:48,
showplayvideo:true,
spacing:4,
scrollitems:1,
showhoveroverlay:true,
scrollmode:"page",
navdirection:"horizontal",
itembottomshadowimagewidth:100,
backgroundimage:"",
autoplay:true,
arrowwidth:32,
pauseonmouseover:true,
navmode:"page",
interval:3000,
backgroundimagewidth:110,
navspacing:8,
playvideoimage:"playvideo-64-64-0.png",
visibleitems:3,
navswitchonmouseover:false,
bottomshadowimagewidth:110,
screenquery:'{\n "tablet": {\n "screenwidth": 900,\n "visibleitems": 2\n },\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}',
navwidth:16,
loop:0,
transitionduration:1000
},
stylish: {
width:240,
height:180,
skinsfoldername:"",
arrowhideonmouseleave:1000,
itembottomshadowimagetop:100,
navheight:24,
random:false,
showbottomshadow:true,
arrowheight:32,
itembackgroundimagewidth:100,
skin:"stylish",
responsive:true,
bottomshadowimage:"bottomshadow-110-100-5.png",
enabletouchswipe:false,
navstyle:"bullets",
backgroundimagetop:-40,
arrowstyle:"always",
bottomshadowimagetop:100,
hoveroverlayimage:"hoveroverlay-64-64-4.png",
itembottomshadowimage:"itembottomshadow-100-100-5.png",
showitembottomshadow:false,
transitioneasing:"easeOutExpo",
showitembackgroundimage:false,
itembackgroundimage:"",
playvideoimagepos:"center",
circular:true,
arrowimage:"arrows-32-32-0.png",
direction:"horizontal",
navimage:"bullet-24-24-0.png",
itembackgroundimagetop:0,
showbackgroundimage:false,
lightboxbarheight:48,
showplayvideo:true,
spacing:8,
scrollitems:1,
showhoveroverlay:true,
scrollmode:"page",
navdirection:"horizontal",
itembottomshadowimagewidth:100,
backgroundimage:"",
autoplay:true,
arrowwidth:32,
pauseonmouseover:true,
navmode:"page",
interval:3000,
backgroundimagewidth:110,
navspacing:4,
playvideoimage:"playvideo-64-64-0.png",
visibleitems:3,
navswitchonmouseover:false,
bottomshadowimagewidth:110,
screenquery:'{\n "tablet": {\n "screenwidth": 900,\n "visibleitems": 2\n },\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}',
navwidth:24,
loop:0,
transitionduration:1000
},
thumbnail: {
width:240,
height:180,
skinsfoldername:"",
arrowhideonmouseleave:1000,
itembottomshadowimagetop:99,
navheight:16,
random:false,
showbottomshadow:false,
arrowheight:28,
itembackgroundimagewidth:100,
skin:"thumbnail",
responsive:true,
bottomshadowimage:"bottomshadow-110-95-0.png",
enabletouchswipe:true,
navstyle:"none",
backgroundimagetop:-40,
arrowstyle:"always",
bottomshadowimagetop:95,
hoveroverlayimage:"hoveroverlay-64-64-5.png",
itembottomshadowimage:"itembottomshadow-100-98-3.png",
showitembottomshadow:false,
transitioneasing:"easeOutExpo",
showitembackgroundimage:false,
itembackgroundimage:"",
playvideoimagepos:"center",
circular:true,
arrowimage:"arrows-28-28-0.png",
direction:"horizontal",
navimage:"bullet-16-16-0.png",
itembackgroundimagetop:0,
showbackgroundimage:false,
lightboxbarheight:48,
showplayvideo:true,
spacing:8,
scrollitems:1,
showhoveroverlay:true,
scrollmode:"page",
navdirection:"horizontal",
itembottomshadowimagewidth:100,
backgroundimage:"",
autoplay:true,
arrowwidth:28,
pauseonmouseover:true,
navmode:"page",
interval:3000,
backgroundimagewidth:110,
navspacing:8,
playvideoimage:"playvideo-64-64-0.png",
visibleitems:1,
navswitchonmouseover:false,
bottomshadowimagewidth:110,
screenquery:'{\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}',
navwidth:16,
loop:0,
transitionduration:750
},
vertical: {
width:240,
height:180,
skinsfoldername:"",
arrowhideonmouseleave:1000,
itembottomshadowimagetop:100,
navheight:24,
random:false,
showbottomshadow:false,
arrowheight:32,
itembackgroundimagewidth:100,
skin:"vertical",
responsive:true,
bottomshadowimage:"bottomshadow-110-100-5.png",
enabletouchswipe:true,
navstyle:"none",
backgroundimagetop:-40,
arrowstyle:"always",
bottomshadowimagetop:100,
hoveroverlayimage:"hoveroverlay-64-64-4.png",
itembottomshadowimage:"itembottomshadow-100-100-5.png",
showitembottomshadow:false,
transitioneasing:"easeOutExpo",
showitembackgroundimage:false,
itembackgroundimage:"",
playvideoimagepos:"center",
circular:true,
arrowimage:"arrows-32-32-4.png",
direction:"vertical",
navimage:"bullet-24-24-0.png",
itembackgroundimagetop:0,
showbackgroundimage:false,
lightboxbarheight:48,
showplayvideo:true,
spacing:12,
scrollitems:1,
showhoveroverlay:true,
scrollmode:"page",
navdirection:"vertical",
itembottomshadowimagewidth:100,
backgroundimage:"",
autoplay:true,
arrowwidth:32,
pauseonmouseover:true,
navmode:"page",
interval:3000,
backgroundimagewidth:110,
navspacing:4,
playvideoimage:"playvideo-64-64-0.png",
visibleitems:2,
navswitchonmouseover:false,
bottomshadowimagewidth:110,
screenquery:'{\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}',
navwidth:24,
loop:0,
transitionduration:1000
},
testimonial: {
width:360,
height:270,
skinsfoldername:"",
arrowhideonmouseleave:1000,
itembottomshadowimagetop:99,
donotcrop:false,
navheight:12,
random:false,
showhoveroverlay:true,
height:270,
arrowheight:32,
itembackgroundimagewidth:100,
skin:"testimonial",
responsive:true,
bottomshadowimage:"bottomshadow-110-95-0.png",
navstyle:"none",
enabletouchswipe:true,
backgroundimagetop:-40,
arrowstyle:"mouseover",
bottomshadowimagetop:95,
transitionduration:1000,
lightboxshowtitle:true,
hoveroverlayimage:"hoveroverlay-64-64-5.png",
itembottomshadowimage:"itembottomshadow-100-98-3.png",
lightboxshowdescription:false,
width:360,
showitembottomshadow:false,
showhoveroverlayalways:false,
navimage:"bullet-12-12-1.png",
lightboxtitlebottomcss:"{color:#333; font-size:14px; font-family:Armata,sans-serif,Arial; overflow:hidden; text-align:left;}",
lightboxshownavigation:false,
showitembackgroundimage:false,
itembackgroundimage:"",
backgroundimagewidth:110,
playvideoimagepos:"center",
circular:true,
arrowimage:"arrows-32-32-2.png",
scrollitems:1,
showbottomshadow:false,
lightboxdescriptionbottomcss:"{color:#333; font-size:12px; font-family:Arial,Helvetica,sans-serif; overflow:hidden; text-align:left; margin:4px 0px 0px; padding: 0px;}",
supportiframe:false,
transitioneasing:"easeOutExpo",
itembackgroundimagetop:0,
showbackgroundimage:false,
lightboxbarheight:64,
showplayvideo:true,
spacing:4,
lightboxthumbwidth:80,
scrollmode:"item",
navdirection:"horizontal",
itembottomshadowimagewidth:100,
backgroundimage:"",
lightboxthumbtopmargin:12,
arrowwidth:32,
transparent:false,
navmode:"page",
lightboxthumbbottommargin:8,
interval:2000,
lightboxthumbheight:60,
navspacing:4,
pauseonmouseover:false,
imagefillcolor:"FFFFFF",
playvideoimage:"playvideo-64-64-0.png",
visibleitems:1,
navswitchonmouseover:false,
direction:"horizontal",
usescreenquery:false,
bottomshadowimagewidth:110,
screenquery:'{\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}',
navwidth:12,
loop:0,
autoplay:true
},
fashion: {
width:300,
height:300,
skinsfoldername:"",
arrowhideonmouseleave:1000,
itembottomshadowimagetop:100,
donotcrop:false,
navheight:16,
random:false,
showhoveroverlay:false,
height:300,
arrowheight:60,
itembackgroundimagewidth:100,
skin:"fashion",
responsive:true,
bottomshadowimage:"bottomshadow-110-95-0.png",
navstyle:"bullets",
enabletouchswipe:true,
backgroundimagetop:-40,
arrowstyle:"mouseover",
bottomshadowimagetop:95,
transitionduration:1000,
lightboxshowtitle:true,
hoveroverlayimage:"hoveroverlay-64-64-4.png",
itembottomshadowimage:"itembottomshadow-100-100-5.png",
lightboxshowdescription:false,
width:300,
showitembottomshadow:false,
showhoveroverlayalways:false,
navimage:"bullet-16-16-1.png",
lightboxtitlebottomcss:"{color:#333; font-size:14px; font-family:Armata,sans-serif,Arial; overflow:hidden; text-align:left;}",
lightboxshownavigation:false,
showitembackgroundimage:false,
itembackgroundimage:"",
backgroundimagewidth:110,
playvideoimagepos:"center",
circular:true,
arrowimage:"arrows-42-60-0.png",
scrollitems:1,
showbottomshadow:false,
lightboxdescriptionbottomcss:"{color:#333; font-size:12px; font-family:Arial,Helvetica,sans-serif; overflow:hidden; text-align:left; margin:4px 0px 0px; padding: 0px;}",
supportiframe:false,
transitioneasing:"easeOutExpo",
itembackgroundimagetop:0,
showbackgroundimage:false,
lightboxbarheight:64,
showplayvideo:true,
spacing:0,
lightboxthumbwidth:80,
scrollmode:"page",
navdirection:"horizontal",
itembottomshadowimagewidth:100,
backgroundimage:"",
lightboxthumbtopmargin:12,
arrowwidth:42,
transparent:false,
navmode:"page",
lightboxthumbbottommargin:8,
interval:3000,
lightboxthumbheight:60,
navspacing:8,
pauseonmouseover:true,
imagefillcolor:"FFFFFF",
playvideoimage:"playvideo-64-64-0.png",
visibleitems:3,
navswitchonmouseover:false,
direction:"horizontal",
usescreenquery:false,
bottomshadowimagewidth:110,
screenquery:'{\n "tablet": {\n "screenwidth": 900,\n "visibleitems": 2\n },\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}',
navwidth:16,
loop:0,
autoplay:true
},
rotator: {
width:200,
height:200,
skinsfoldername:"",
interval:3000,
itembottomshadowimagetop:100,
donotcrop:false,
random:false,
showhoveroverlay:true,
arrowheight:36,
showbottomshadow:false,
itembackgroundimagewidth:100,
skin:"Rotator",
responsive:true,
lightboxtitlebottomcss:"{color:#333; font-size:14px; font-family:Armata,sans-serif,Arial; overflow:hidden; text-align:left;}",
enabletouchswipe:true,
navstyle:"none",
backgroundimagetop:-40,
arrowstyle:"mouseover",
bottomshadowimagetop:100,
transitionduration:1000,
itembackgroundimagetop:0,
hoveroverlayimage:"hoveroverlay-64-64-9.png",
itembottomshadowimage:"itembottomshadow-100-100-5.png",
lightboxshowdescription:false,
navswitchonmouseover:false,
showhoveroverlayalways:false,
transitioneasing:"easeOutExpo",
lightboxshownavigation:false,
showitembackgroundimage:false,
itembackgroundimage:"",
playvideoimagepos:"center",
circular:true,
arrowimage:"arrows-36-36-1.png",
scrollitems:1,
direction:"vertical",
lightboxdescriptionbottomcss:"{color:#333; font-size:12px; font-family:Arial,Helvetica,sans-serif; overflow:hidden; text-align:left; margin:4px 0px 0px; padding: 0px;}",
supportiframe:false,
navimage:"bullet-24-24-0.png",
backgroundimagewidth:110,
showbackgroundimage:false,
lightboxbarheight:64,
showplayvideo:true,
spacing:8,
lightboxthumbwidth:80,
navdirection:"vertical",
itembottomshadowimagewidth:100,
backgroundimage:"",
lightboxthumbtopmargin:12,
autoplay:true,
arrowwidth:36,
transparent:false,
bottomshadowimage:"bottomshadow-110-100-5.png",
scrollmode:"page",
navmode:"page",
lightboxshowtitle:true,
lightboxthumbbottommargin:8,
arrowhideonmouseleave:1000,
showitembottomshadow:false,
lightboxthumbheight:60,
navspacing:4,
pauseonmouseover:true,
imagefillcolor:"FFFFFF",
playvideoimage:"playvideo-64-64-0.png",
visibleitems:2,
usescreenquery:false,
bottomshadowimagewidth:110,
screenquery:'{\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}',
navwidth:24,
loop:0,
navheight:24
},
testimonialcarousel: {
width:280,
height:240,
skinsfoldername:"",
interval:3000,
itembottomshadowimagetop:99,
donotcrop:false,
random:false,
showhoveroverlay:false,
arrowheight:32,
showbottomshadow:false,
itembackgroundimagewidth:100,
skin:"TestimonialCarousel",
responsive:true,
lightboxtitlebottomcss:"{color:#333; font-size:14px; font-family:Armata,sans-serif,Arial; overflow:hidden; text-align:left;}",
enabletouchswipe:true,
navstyle:"bullets",
backgroundimagetop:-40,
arrowstyle:"mouseover",
bottomshadowimagetop:95,
transitionduration:1000,
itembackgroundimagetop:0,
hoveroverlayimage:"hoveroverlay-64-64-9.png",
itembottomshadowimage:"itembottomshadow-100-98-3.png",
lightboxshowdescription:false,
navswitchonmouseover:false,
showhoveroverlayalways:false,
transitioneasing:"easeOutExpo",
lightboxshownavigation:false,
showitembackgroundimage:false,
itembackgroundimage:"",
playvideoimagepos:"center",
circular:true,
arrowimage:"arrows-32-32-2.png",
scrollitems:1,
direction:"horizontal",
lightboxdescriptionbottomcss:"{color:#333; font-size:12px; font-family:Arial,Helvetica,sans-serif; overflow:hidden; text-align:left; margin:4px 0px 0px; padding: 0px;}",
supportiframe:false,
navimage:"bullet-16-16-1.png",
backgroundimagewidth:110,
showbackgroundimage:false,
lightboxbarheight:64,
showplayvideo:true,
spacing:4,
lightboxthumbwidth:80,
navdirection:"horizontal",
itembottomshadowimagewidth:100,
backgroundimage:"",
lightboxthumbtopmargin:12,
autoplay:true,
arrowwidth:32,
transparent:false,
bottomshadowimage:"bottomshadow-110-95-0.png",
scrollmode:"page",
navmode:"page",
lightboxshowtitle:true,
lightboxthumbbottommargin:8,
arrowhideonmouseleave:600,
showitembottomshadow:false,
lightboxthumbheight:60,
navspacing:4,
pauseonmouseover:false,
imagefillcolor:"FFFFFF",
playvideoimage:"playvideo-64-64-0.png",
visibleitems:3,
usescreenquery:false,
bottomshadowimagewidth:110,
screenquery:'{\n "tablet": {\n "screenwidth": 900,\n "visibleitems": 2\n },\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}',
navwidth:16,
loop:0,
navheight:16
}
}; | master777/tap | wp-content/plugins/wonderplugin-carousel/engine/wonderplugincarouselskins.js | JavaScript | gpl-2.0 | 28,810 |
(function ($, Drupal) {
'use strict';
Drupal.behaviors.chosen = {
attach: function (context, settings) {
settings.chosen = settings.chosen || drupalSettings.chosen;
// Prepare selector and add unwantend selectors.
var selector = settings.chosen.selector;
var options;
// Function to prepare all the options together for the chosen() call.
var getElementOptions = function (element) {
options = $.extend({}, settings.chosen.options);
// The width default option is considered the minimum width, so this
// must be evaluated for every option.
if (settings.chosen.minimum_width > 0) {
if ($(element).width() < settings.chosen.minimum_width) {
options.width = settings.chosen.minimum_width + 'px';
}
else {
options.width = $(element).width() + 'px';
}
}
// Some field widgets have cardinality, so we must respect that.
// @see chosen_pre_render_select()
if ($(element).attr('multiple') && $(element).data('cardinality')) {
options.max_selected_options = $(element).data('cardinality');
}
return options;
};
// Process elements that have opted-in for Chosen.
$('select.chosen-enable', context).once('chosen').each(function () {
options = getElementOptions(this);
$(this).chosen(options);
});
$(selector, context)
// Disabled on:
// - Field UI
// - WYSIWYG elements
// - Tabledrag weights
// - Elements that have opted-out of Chosen
// - Elements already processed by Chosen
.not('#field-ui-field-storage-add-form select, #entity-form-display-edit-form select, #entity-view-display-edit-form select, .wysiwyg, .draggable select[name$="[weight]"], .draggable select[name$="[position]"], .locale-translate-filter-form select, .chosen-disable, .chosen-processed')
.filter(function () {
// Filter out select widgets that do not meet the minimum number of
// options.
var minOptions = $(this).attr('multiple') ? settings.chosen.minimum_multiple : settings.chosen.minimum_single;
if (!minOptions) {
// Zero value means no minimum.
return true;
}
else {
return $(this).find('option').length >= minOptions;
}
})
.once('chosen').each(function () {
options = getElementOptions(this);
$(this).chosen(options);
});
}
};
})(jQuery, Drupal);
| SeeyaSia/www | web/modules/contrib/chosen/js/chosen.js | JavaScript | gpl-2.0 | 2,592 |
/**
* Desarrollado por: Judelvis Antonio Rivas Perdomo
* Fecha Creacion: 09 de Noviembre de 2014
*/
$(function() {
$('#tabs').tabs();
listar_pendientes();
listar_procesando();
listar_procesado();
listar_rechazo_cliente();
listar_rechazo_admin();
});
function listar_pendientes(){
var datos = "estatus=0&panel=1";
$("#resp1").html('');
alert(sUrlP);
$.ajax({
url : sUrlP + "listar_pedidos_pendientes",
data: datos,
type : "POST",
dataType : "json",
success : function(json) {//alert(json);
if(json['resp']==1){
var Grid1 = new TGrid(json, 'resp1','Pedidos Pendientes por Depositar');
Grid1.SetNumeracion(true);
Grid1.SetName("PDepositar");
Grid1.SetDetalle();
Grid1.Generar();
}else $("#resp1").html("No posee Pedidos Pendientes por Depositar");
}
});
}
function listar_procesando(){
var datos = "estatus=1";
$("#resp2").html('');
//alert(sUrlP + "listar_pedidos_cliente");
$.ajax({
url : sUrlP + "listar_pedidos_cliente",
data: datos,
type : "POST",
dataType : "json",
success : function(json) {//alert(json);
if(json['resp']==1){
var Grid2 = new TGrid(json, 'resp2','Pedidos Pendientes por Aprobar');
Grid2.SetNumeracion(true);
Grid2.SetName("procesando");
Grid2.SetDetalle();
Grid2.Generar();
}else $("#resp2").html("No posee Pedidos Pendientes por Aprobar");
}
});
}
function listar_procesado(){
var datos = "estatus=2";
$("#resp3").html('');
alert(sUrlP);
$.ajax({
url : sUrlP + "listar_pedidos_cliente",
data: datos,
type : "POST",
dataType : "json",
success : function(json) {//alert(json);
if(json['resp']==1){
var Grid3 = new TGrid(json, 'resp3','Pedidos Aprobados');
Grid3.SetNumeracion(true);
Grid3.SetName("Procesado");
Grid3.SetDetalle();
Grid3.Generar();
}else $("#resp3").html("No posee Pedidos Aprobados");
}
});
}
function listar_rechazo_cliente(){
var datos = "estatus=3";
$("#resp4").html('');
$.ajax({
url : sUrlP + "listar_pedidos_cliente",
data: datos,
type : "POST",
dataType : "json",
success : function(json) {//alert(json);
if(json['resp']==1){
var Grid4 = new TGrid(json, 'resp4','Pedidos Rechazados Por Cliente');
Grid4.SetNumeracion(true);
Grid4.SetName("Rcliente");
Grid4.SetDetalle();
Grid4.Generar();
}else $("#resp4").html("No posee Pedidos Rechazados por Cliente");
}
});
}
function listar_rechazo_admin(){
var datos = "estatus=4";
$("#resp5").html('');
$.ajax({
url : sUrlP + "listar_pedidos_cliente",
data: datos,
type : "POST",
dataType : "json",
success : function(json) {//alert(json);
if(json['resp']==1){
var Grid5 = new TGrid(json, 'resp5','Pedidos rechazados por administrador');
Grid5.SetNumeracion(true);
Grid5.SetName("Radmin");
Grid5.SetDetalle();
Grid5.Generar();
}else $("#resp5").html("No posee Pedidos Rechazados por Administrador");
}
});
} | judelvis/jpa-garte | system/js/panel/principal.js | JavaScript | gpl-2.0 | 2,919 |
define(['multi-download'], function (multiDownload) {
'use strict';
return {
download: function (items) {
multiDownload(items.map(function (item) {
return item.url;
}));
}
};
}); | gsnerf/MediaBrowser | MediaBrowser.WebDashboard/dashboard-ui/bower_components/emby-webcomponents/filedownloader.js | JavaScript | gpl-2.0 | 251 |
"use strict";
(function main_default_js(g) {
// - g is the global object.
// - User callbacks called without 'this', global only if callee is non-strict.
// - The names of function expressions are not required, but are used in stack
// traces. We name them where useful to show up (fname:#line always shows).
mp.msg = { log: mp.log };
mp.msg.verbose = mp.log.bind(null, "v");
var levels = ["fatal", "error", "warn", "info", "debug"];
levels.forEach(function(l) { mp.msg[l] = mp.log.bind(null, l) });
// same as {} but without inherited stuff, e.g. o["toString"] doesn't exist.
// used where we try to fetch items by keys which we don't absolutely trust.
function new_cache() {
return Object.create(null, {});
}
/**********************************************************************
* event handlers, property observers, client messages, hooks
*********************************************************************/
var ehandlers = new_cache() // items of event-name: array of {maybe cb: fn}
mp.register_event = function(name, fn) {
if (!ehandlers[name])
ehandlers[name] = [];
ehandlers[name] = ehandlers[name].concat([{cb: fn}]); // replaces the arr
return mp._request_event(name, true);
}
mp.unregister_event = function(fn) {
for (var name in ehandlers) {
ehandlers[name] = ehandlers[name].filter(function(h) {
if (h.cb != fn)
return true;
delete h.cb; // dispatch could have a ref to h
}); // replacing, not mutating the array
if (!ehandlers[name].length) {
delete ehandlers[name];
mp._request_event(name, false);
}
}
}
// call only pre-registered handlers, but not ones which got unregistered
function dispatch_event(e) {
var handlers = ehandlers[e.event];
if (handlers) {
for (var len = handlers.length, i = 0; i < len; i++) {
var cb = handlers[i].cb; // 'handlers' won't mutate, but unregister
if (cb) // could remove cb from some items
cb(e);
}
}
}
// ----- property observers -----
var next_oid = 1,
observers = new_cache(); // items of id: fn
mp.observe_property = function(name, format, fn) {
var id = next_oid++;
observers[id] = fn;
return mp._observe_property(id, name, format || undefined); // allow null
}
mp.unobserve_property = function(fn) {
for (var id in observers) {
if (observers[id] == fn) {
delete observers[id];
mp._unobserve_property(id);
}
}
}
function notify_observer(e) {
var cb = observers[e.id];
if (cb)
cb(e.name, e.data);
}
// ----- Client messages -----
var messages = new_cache(); // items of name: fn
// overrides name. no libmpv API to reg/unreg specific messages.
mp.register_script_message = function(name, fn) {
messages[name] = fn;
}
mp.unregister_script_message = function(name) {
delete messages[name];
}
function dispatch_message(ev) {
var cb = ev.args.length ? messages[ev.args[0]] : false;
if (cb)
cb.apply(null, ev.args.slice(1));
}
// ----- hooks -----
var next_hid = 1,
hooks = new_cache(); // items of id: fn
function hook_run(id, cont) {
var cb = hooks[id];
if (cb)
cb();
mp.commandv("hook-ack", cont);
}
mp.add_hook = function add_hook(name, pri, fn) {
if (next_hid == 1) // doesn't really matter if we do it once or always
mp.register_script_message("hook_run", hook_run);
var id = next_hid++;
hooks[id] = fn;
return mp.commandv("hook-add", name, id, pri);
}
/**********************************************************************
* key bindings
*********************************************************************/
// binds: items of (binding) name which are objects of:
// {cb: fn, forced: bool, maybe input: str, repeatable: bool, complex: bool}
var binds = new_cache();
function dispatch_key_binding(name, state) {
var cb = binds[name] ? binds[name].cb : false;
if (cb) // "script-binding [<script_name>/]<name>" command was invoked
cb(state);
}
function update_input_sections() {
var def = [], forced = [];
for (var n in binds) // Array.join() will later skip undefined .input
(binds[n].forced ? forced : def).push(binds[n].input);
var sect = "input_" + mp.script_name;
mp.commandv("define-section", sect, def.join("\n"), "default");
mp.commandv("enable-section", sect, "allow-hide-cursor+allow-vo-dragging");
sect = "input_forced_" + mp.script_name;
mp.commandv("define-section", sect, forced.join("\n"), "force");
mp.commandv("enable-section", sect, "allow-hide-cursor+allow-vo-dragging");
}
// name/opts maybe omitted. opts: object with optional bool members: repeatable,
// complex, forced, or a string str which is evaluated as object {str: true}.
var next_bid = 1;
function add_binding(forced, key, name, fn, opts) {
if (typeof name == "function") { // as if "name" is not part of the args
opts = fn;
fn = name;
name = "__keybinding" + next_bid++; // new unique binding name
}
var key_data = {forced: forced};
switch (typeof opts) { // merge opts into key_data
case "string": key_data[opts] = true; break;
case "object": for (var o in opts) key_data[o] = opts[o];
}
if (key_data.complex) {
mp.register_script_message(name, function msg_cb() {
fn({event: "press", is_mouse: false});
});
var KEY_STATES = { u: "up", d: "down", r: "repeat", p: "press" };
key_data.cb = function key_cb(state) {
fn({
event: KEY_STATES[state[0]] || "unknown",
is_mouse: state[1] == "m"
});
}
} else {
mp.register_script_message(name, fn);
key_data.cb = function key_cb(state) {
// Emulate the semantics at input.c: mouse emits on up, kb on down.
// Also, key repeat triggers the binding again.
var e = state[0],
emit = (state[1] == "m") ? (e == "u") : (e == "d");
if (emit || e == "p" || e == "r" && key_data.repeatable)
fn();
}
}
if (key)
key_data.input = key + " script-binding " + mp.script_name + "/" + name;
binds[name] = key_data; // used by user and/or our (key) script-binding
update_input_sections();
}
mp.add_key_binding = add_binding.bind(null, false);
mp.add_forced_key_binding = add_binding.bind(null, true);
mp.remove_key_binding = function(name) {
mp.unregister_script_message(name);
delete binds[name];
update_input_sections();
}
/**********************************************************************
Timers: compatible HTML5 WindowTimers - set/clear Timeout/Interval
- Spec: https://www.w3.org/TR/html5/webappapis.html#timers
- Guaranteed to callback a-sync to [re-]insertion (event-loop wise).
- Guaranteed to callback by expiration order, or, if equal, by insertion order.
- Not guaranteed schedule accuracy, though intervals should have good average.
*********************************************************************/
// pending 'timers' ordered by expiration: latest at index 0 (top fires first).
// Earlier timers are quicker to handle - just push/pop or fewer items to shift.
var next_tid = 1,
timers = [], // while in process_timers, just insertion-ordered (push)
tset_is_push = false, // signal set_timer that we're in process_timers
tcanceled = false, // or object of items timer-id: true
now = mp.get_time_ms; // just an alias
function insert_sorted(arr, t) {
for (var i = arr.length - 1; i >= 0 && t.when >= arr[i].when; i--)
arr[i + 1] = arr[i]; // move up timers which fire earlier than t
arr[i + 1] = t; // i is -1 or fires later than t
}
// args (is "arguments"): fn_or_str [,duration [,user_arg1 [, user_arg2 ...]]]
function set_timer(repeat, args) {
var fos = args[0],
duration = Math.max(0, (args[1] || 0)), // minimum and default are 0
t = {
id: next_tid++,
when: now() + duration,
interval: repeat ? duration : -1,
callback: (typeof fos == "function") ? fos : Function(fos),
args: (args.length < 3) ? false : [].slice.call(args, 2),
};
if (tset_is_push) {
timers.push(t);
} else {
insert_sorted(timers, t);
}
return t.id;
}
g.setTimeout = function setTimeout() { return set_timer(false, arguments) };
g.setInterval = function setInterval() { return set_timer(true, arguments) };
g.clearTimeout = g.clearInterval = function(id) {
if (id < next_tid) { // must ignore if not active timer id.
if (!tcanceled)
tcanceled = {};
tcanceled[id] = true;
}
}
// arr: ordered timers array. ret: -1: no timers, 0: due, positive: ms to wait
function peek_wait(arr) {
return arr.length ? Math.max(0, arr[arr.length - 1].when - now()) : -1;
}
// Callback all due non-canceled timers which were inserted before calling us.
// Returns wait in ms till the next timer (possibly 0), or -1 if nothing pends.
function process_timers() {
var wait = peek_wait(timers);
if (wait != 0)
return wait;
var actives = timers; // only process those already inserted by now
timers = []; // we'll handle added new timers at the end of processing.
tset_is_push = true; // signal set_timer to just push-insert
do {
var t = actives.pop();
if (tcanceled && tcanceled[t.id])
continue;
if (t.args) {
t.callback.apply(null, t.args);
} else {
(0, t.callback)(); // faster, nicer stack trace than t.cb.call()
}
if (t.interval >= 0) {
// allow 20 ms delay/clock-resolution/gc before we skip and reset
t.when = Math.max(now() - 20, t.when + t.interval);
timers.push(t); // insertion order only
}
} while (peek_wait(actives) == 0);
// new 'timers' are insertion-ordered. remains of actives are fully ordered
timers.forEach(function(t) { insert_sorted(actives, t) });
timers = actives; // now we're fully ordered again, and with all timers
tset_is_push = false;
if (tcanceled) {
timers = timers.filter(function(t) { return !tcanceled[t.id] });
tcanceled = false;
}
return peek_wait(timers);
}
/**********************************************************************
CommonJS module/require
Spec: http://wiki.commonjs.org/wiki/Modules/1.1.1
- All the mandatory requirements are implemented, all the unit tests pass.
- The implementation makes the following exception:
- Allows the chars [~@:\\] in module id for meta-dir/builtin/dos-drive/UNC.
Implementation choices beyond the specification:
- A module may assign to module.exports (rather than only to exports).
- A module's 'this' is the global object, also if it sets strict mode.
- No 'global'/'self'. Users can do "this.global = this;" before require(..)
- A module has "privacy of its top scope", runs in its own function context.
- No id identity with symlinks - a valid choice which others make too.
- require("X") always maps to "X.js" -> require("foo.js") is file "foo.js.js".
- Global modules search paths are 'scripts/modules.js/' in mpv config dirs.
- A main script could e.g. require("./abc") to load a non-global module.
- Module id supports mpv path enhancements, e.g. ~/foo, ~~/bar, ~~desktop/baz
*********************************************************************/
// Internal meta top-dirs. Users should not rely on these names.
var MODULES_META = "~~modules",
SCRIPTDIR_META = "~~scriptdir", // relative script path -> meta absolute id
main_script = mp.utils.split_path(mp.script_file); // -> [ path, file ]
function resolve_module_file(id) {
var sep = id.indexOf("/"),
base = id.substring(0, sep),
rest = id.substring(sep + 1) + ".js";
if (base == SCRIPTDIR_META)
return mp.utils.join_path(main_script[0], rest);
if (base == MODULES_META) {
var path = mp.find_config_file("scripts/modules.js/" + rest);
if (!path)
throw(Error("Cannot find module file '" + rest + "'"));
return path;
}
return id + ".js";
}
// Delimiter '/', remove redundancies, prefix with modules meta-root if needed.
// E.g. c:\x -> c:/x, or ./x//y/../z -> ./x/z, or utils/x -> ~~modules/utils/x .
function canonicalize(id) {
var path = id.replace(/\\/g,"/").split("/"),
t = path[0],
base = [];
// if not strictly relative then must be top-level. figure out base/rest
if (t != "." && t != "..") {
// global module if it's not fs-root/home/dos-drive/builtin/meta-dir
if (!(t == "" || t == "~" || t[1] == ":" || t == "@" || t.match(/^~~/)))
path.unshift(MODULES_META); // add an explicit modules meta-root
if (id.match(/^\\\\/)) // simple UNC handling, preserve leading \\srv
path = ["\\\\" + path[2]].concat(path.slice(3)); // [ \\srv, shr..]
if (t[1] == ":" && t.length > 2) { // path: [ "c:relative", "path" ]
path[0] = t.substring(2);
path.unshift(t[0] + ":."); // -> [ "c:.", "relative", "path" ]
}
base = [path.shift()];
}
// path is now logically relative. base, if not empty, is its [meta] root.
// normalize the relative part - always id-based (spec Module Id, 1.3.6).
var cr = []; // canonicalized relative
for (var i = 0; i < path.length; i++) {
if (path[i] == "." || path[i] == "")
continue;
if (path[i] == ".." && cr.length && cr[cr.length - 1] != "..") {
cr.pop();
continue;
}
cr.push(path[i]);
}
if (!base.length && cr[0] != "..")
base = ["."]; // relative and not ../<stuff> so must start with ./
return base.concat(cr).join("/");
}
function resolve_module_id(base_id, new_id) {
new_id = canonicalize(new_id);
if (!new_id.match(/^\.\/|^\.\.\//)) // doesn't start with ./ or ../
return new_id; // not relative, we don't care about base_id
var combined = mp.utils.join_path(mp.utils.split_path(base_id)[0], new_id);
return canonicalize(combined);
}
var req_cache = new_cache(); // global for all instances of require
// ret: a require function instance which uses base_id to resolve relative id's
function new_require(base_id) {
return function require(id) {
id = resolve_module_id(base_id, id); // id is now top-level
if (req_cache[id])
return req_cache[id].exports;
var new_module = {id: id, exports: {}};
req_cache[id] = new_module;
try {
var filename = resolve_module_file(id);
// we need dedicated free vars + filename in traces + allow strict
var str = "mp._req = function(require, exports, module) {" +
mp.utils.read_file(filename) +
"\n;}";
mp.utils.compile_js(filename, str)(); // only runs the assignment
var tmp = mp._req; // we have mp._req, or else we'd have thrown
delete mp._req;
tmp.call(g, new_require(id), new_module.exports, new_module);
} catch (e) {
delete req_cache[id];
throw(e);
}
return new_module.exports;
};
}
g.require = new_require(SCRIPTDIR_META + "/" + main_script[1]);
/**********************************************************************
* various
*********************************************************************/
g.print = mp.msg.info; // convenient alias
mp.get_script_name = function() { return mp.script_name };
mp.get_script_file = function() { return mp.script_file };
mp.get_time = function() { return mp.get_time_ms() / 1000 };
mp.utils.getcwd = function() { return mp.get_property("working-directory") };
mp.dispatch_event = dispatch_event;
mp.process_timers = process_timers;
mp.get_opt = function(key, def) {
var v = mp.get_property_native("options/script-opts")[key];
return (typeof v != "undefined") ? v : def;
}
mp.osd_message = function osd_message(text, duration) {
mp.commandv("show_text", text, Math.round(1000 * (duration || -1)));
}
// ----- dump: like print, but expands objects/arrays recursively -----
function replacer(k, v) {
var t = typeof v;
if (t == "function" || t == "undefined")
return "<" + t + ">";
if (Array.isArray(this) && t == "object" && v !== null) { // "safe" mode
if (this.indexOf(v) >= 0)
return "<VISITED>";
this.push(v);
}
return v;
}
function obj2str(v) {
try { // can process objects more than once, but throws on cycles
return JSON.stringify(v, replacer, 2);
} catch (e) { // simple safe: exclude visited objects, even if not cyclic
return JSON.stringify(v, replacer.bind([]), 2);
}
}
g.dump = function dump() {
var toprint = [];
for (var i = 0; i < arguments.length; i++) {
var v = arguments[i];
toprint.push((typeof v == "object") ? obj2str(v) : replacer(0, v));
}
print.apply(null, toprint);
}
/**********************************************************************
* main listeners and event loop
*********************************************************************/
mp.keep_running = true;
g.exit = function() { mp.keep_running = false }; // user-facing too
mp.register_event("shutdown", g.exit);
mp.register_event("property-change", notify_observer);
mp.register_event("client-message", dispatch_message);
mp.register_script_message("key-binding", dispatch_key_binding);
g.mp_event_loop = function mp_event_loop() {
var wait = 0; // seconds
do { // distapch events as long as they arrive, then do the timers
var e = mp.wait_event(wait);
if (e.event != "none") {
dispatch_event(e);
wait = 0; // poll the next one
} else {
wait = process_timers() / 1000;
}
} while (mp.keep_running);
};
})(this)
| torque/mpv | player/javascript/defaults.js | JavaScript | gpl-2.0 | 18,251 |
'use strict';
require('../common');
const assert = require('assert');
const Buffer = require('buffer').Buffer;
function FakeBuffer() { }
Object.setPrototypeOf(FakeBuffer, Buffer);
Object.setPrototypeOf(FakeBuffer.prototype, Buffer.prototype);
const fb = new FakeBuffer();
assert.throws(function() {
Buffer.from(fb);
}, TypeError);
assert.throws(function() {
+Buffer.prototype;
}, TypeError);
assert.throws(function() {
Buffer.compare(fb, Buffer.alloc(0));
}, TypeError);
assert.throws(function() {
fb.write('foo');
}, TypeError);
assert.throws(function() {
Buffer.concat([fb, fb]);
}, TypeError);
assert.throws(function() {
fb.toString();
}, TypeError);
assert.throws(function() {
fb.equals(Buffer.alloc(0));
}, TypeError);
assert.throws(function() {
fb.indexOf(5);
}, TypeError);
assert.throws(function() {
fb.readFloatLE(0);
}, TypeError);
assert.throws(function() {
fb.writeFloatLE(0);
}, TypeError);
assert.throws(function() {
fb.fill(0);
}, TypeError);
| domino-team/openwrt-cc | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/test/parallel/test-buffer-fakes.js | JavaScript | gpl-2.0 | 994 |
/*
html:after {
display: none;
content: '--small: (max-width: 500px) | --medium: (max-width: 1100px) | --large: (min-width: 1100px)';
}
*/
(function(window){
/*jshint eqnull:true */
'use strict';
var docElem = document.documentElement;
var create = function(){
if(!window.lazySizes || window.lazySizes.getCustomMedias){return;}
var lazySizes = window.lazySizes;
lazySizes.getCustomMedias = (function(){
var regCleanPseudos = /['"]/g;
var regSplit = /\s*\|\s*/g;
var regNamedQueries = /^([a-z0-9_-]+)\s*:\s*(.+)$/i;
var getStyle = function(elem, pseudo){
return (getComputedStyle(elem, pseudo).getPropertyValue('content') || 'none').replace(regCleanPseudos, '').trim();
};
var parse = function(string, object){
string.split(regSplit).forEach(function(query){
if(query.match(regNamedQueries)){
object[RegExp.$1] = RegExp.$2;
}
});
};
return function(object, element){
object = object || lazySizes.cfg.customMedia;
element = element || document.querySelector('html');
parse(getStyle(element, ':before'), object);
parse(getStyle(element, ':after'), object);
return object;
};
})();
lazySizes.updateCustomMedia = function(){
var i, len, customMedia;
var elems = docElem.querySelectorAll('source[media][data-media][srcset]');
lazySizes.getCustomMedias();
for(i = 0, len = elems.length; i < len; i++){
if( (customMedia = lazySizes.cfg.customMedia[elems[i].getAttribute('data-media') || elems[i].getAttribute('media')]) ){
elems[i].setAttribute('media', customMedia);
}
}
if(!window.HTMLPictureElement){
elems = docElem.querySelector('source[media][data-media][srcset] ~ img');
for(i = 0, len = elems.length; i < len; i++){
lazySizes.uP(elems[i]);
}
}
lazySizes.autoSizer.checkElems();
};
lazySizes.getCustomMedias();
docElem.removeEventListener('lazybeforeunveil', create);
};
if(window.addEventListener){
docElem.addEventListener('lazybeforeunveil', create);
create();
setTimeout(create);
}
})(window);
| georges5/bcangular | wp-content/plugins/wp-lazysizes-master/js/lazysizes/plugins/custommedia/ls.custommedia.js | JavaScript | gpl-2.0 | 2,072 |
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'list', 'pt-br', {
bulletedlist: 'Lista sem números',
numberedlist: 'Lista numerada'
} );
| SeeyaSia/www | web/libraries/ckeditor/plugins/list/lang/pt-br.js | JavaScript | gpl-2.0 | 262 |
(function(){
// module factory: start
var moduleFactory = function($) {
// module body: start
var module = this;
$.require()
.script("moment")
.done(function() {
var exports = function() {
$.moment.lang('ar-ma', {
months : "يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"),
monthsShort : "يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"),
weekdays : "الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"),
weekdaysShort : "احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت".split("_"),
weekdaysMin : "ح_ن_ث_ر_خ_ج_س".split("_"),
longDateFormat : {
LT : "HH:mm",
L : "DD/MM/YYYY",
LL : "D MMMM YYYY",
LLL : "D MMMM YYYY LT",
LLLL : "dddd D MMMM YYYY LT"
},
calendar : {
sameDay: "[اليوم على الساعة] LT",
nextDay: '[غدا على الساعة] LT',
nextWeek: 'dddd [على الساعة] LT',
lastDay: '[أمس على الساعة] LT',
lastWeek: 'dddd [على الساعة] LT',
sameElse: 'L'
},
relativeTime : {
future : "في %s",
past : "منذ %s",
s : "ثوان",
m : "دقيقة",
mm : "%d دقائق",
h : "ساعة",
hh : "%d ساعات",
d : "يوم",
dd : "%d أيام",
M : "شهر",
MM : "%d أشهر",
y : "سنة",
yy : "%d سنوات"
},
week : {
dow : 6, // Saturday is the first day of the week.
doy : 12 // The week that contains Jan 1st is the first week of the year.
}
});
};
exports();
module.resolveWith(exports);
});
// module body: end
};
// module factory: end
FD50.module("moment/ar-ma", moduleFactory);
}()); | BetterBetterBetter/B3App | media/foundry/5.0/scripts/moment/ar-ma.js | JavaScript | gpl-2.0 | 2,156 |
/**
* Playlist Loader
*/
import Event from '../events';
import EventHandler from '../event-handler';
import {ErrorTypes, ErrorDetails} from '../errors';
import URLHelper from '../utils/url';
import AttrList from '../utils/attr-list';
//import {logger} from '../utils/logger';
class PlaylistLoader extends EventHandler {
constructor(hls) {
super(hls,
Event.MANIFEST_LOADING,
Event.LEVEL_LOADING);
}
destroy() {
if (this.loader) {
this.loader.destroy();
this.loader = null;
}
this.url = this.id = null;
EventHandler.prototype.destroy.call(this);
}
onManifestLoading(data) {
this.load(data.url, null);
}
onLevelLoading(data) {
this.load(data.url, data.level, data.id);
}
load(url, id1, id2) {
var config = this.hls.config,
retry,
timeout,
retryDelay;
if (this.loading && this.loader) {
if (this.url === url && this.id === id1 && this.id2 === id2) {
// same request than last pending one, don't do anything
return;
} else {
// one playlist load request is pending, but with different params, abort it before loading new playlist
this.loader.abort();
}
}
this.url = url;
this.id = id1;
this.id2 = id2;
if(this.id === null) {
retry = config.manifestLoadingMaxRetry;
timeout = config.manifestLoadingTimeOut;
retryDelay = config.manifestLoadingRetryDelay;
} else {
retry = config.levelLoadingMaxRetry;
timeout = config.levelLoadingTimeOut;
retryDelay = config.levelLoadingRetryDelay;
}
this.loader = typeof(config.pLoader) !== 'undefined' ? new config.pLoader(config) : new config.loader(config);
this.loading = true;
this.loader.load(url, '', this.loadsuccess.bind(this), this.loaderror.bind(this), this.loadtimeout.bind(this), timeout, retry, retryDelay);
}
resolve(url, baseUrl) {
return URLHelper.buildAbsoluteURL(baseUrl, url);
}
parseMasterPlaylist(string, baseurl) {
let levels = [], result;
// https://regex101.com is your friend
const re = /#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g;
while ((result = re.exec(string)) != null){
const level = {};
var attrs = level.attrs = new AttrList(result[1]);
level.url = this.resolve(result[2], baseurl);
var resolution = attrs.decimalResolution('RESOLUTION');
if(resolution) {
level.width = resolution.width;
level.height = resolution.height;
}
level.bitrate = attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH');
level.name = attrs.NAME;
var codecs = attrs.CODECS;
if(codecs) {
codecs = codecs.split(',');
for (let i = 0; i < codecs.length; i++) {
const codec = codecs[i];
if (codec.indexOf('avc1') !== -1) {
level.videoCodec = this.avc1toavcoti(codec);
} else {
level.audioCodec = codec;
}
}
}
levels.push(level);
}
return levels;
}
avc1toavcoti(codec) {
var result, avcdata = codec.split('.');
if (avcdata.length > 2) {
result = avcdata.shift() + '.';
result += parseInt(avcdata.shift()).toString(16);
result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4);
} else {
result = codec;
}
return result;
}
cloneObj(obj) {
return JSON.parse(JSON.stringify(obj));
}
parseLevelPlaylist(string, baseurl, id) {
var currentSN = 0,
totalduration = 0,
level = {url: baseurl, fragments: [], live: true, startSN: 0},
levelkey = {method : null, key : null, iv : null, uri : null},
cc = 0,
programDateTime = null,
frag = null,
result,
regexp,
byteRangeEndOffset,
byteRangeStartOffset;
regexp = /(?:#EXT-X-(MEDIA-SEQUENCE):(\d+))|(?:#EXT-X-(TARGETDURATION):(\d+))|(?:#EXT-X-(KEY):(.*))|(?:#EXT(INF):([\d\.]+)[^\r\n]*([\r\n]+[^#|\r\n]+)?)|(?:#EXT-X-(BYTERANGE):([\d]+[@[\d]*)]*[\r\n]+([^#|\r\n]+)?|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(PROGRAM-DATE-TIME):(.*))/g;
while ((result = regexp.exec(string)) !== null) {
result.shift();
result = result.filter(function(n) { return (n !== undefined); });
switch (result[0]) {
case 'MEDIA-SEQUENCE':
currentSN = level.startSN = parseInt(result[1]);
break;
case 'TARGETDURATION':
level.targetduration = parseFloat(result[1]);
break;
case 'ENDLIST':
level.live = false;
break;
case 'DIS':
cc++;
break;
case 'BYTERANGE':
var params = result[1].split('@');
if (params.length === 1) {
byteRangeStartOffset = byteRangeEndOffset;
} else {
byteRangeStartOffset = parseInt(params[1]);
}
byteRangeEndOffset = parseInt(params[0]) + byteRangeStartOffset;
if (frag && !frag.url) {
frag.byteRangeStartOffset = byteRangeStartOffset;
frag.byteRangeEndOffset = byteRangeEndOffset;
frag.url = this.resolve(result[2], baseurl);
}
break;
case 'INF':
var duration = parseFloat(result[1]);
if (!isNaN(duration)) {
var fragdecryptdata,
sn = currentSN++;
if (levelkey.method && levelkey.uri && !levelkey.iv) {
fragdecryptdata = this.cloneObj(levelkey);
var uint8View = new Uint8Array(16);
for (var i = 12; i < 16; i++) {
uint8View[i] = (sn >> 8*(15-i)) & 0xff;
}
fragdecryptdata.iv = uint8View;
} else {
fragdecryptdata = levelkey;
}
var url = result[2] ? this.resolve(result[2], baseurl) : null;
frag = {url: url, duration: duration, start: totalduration, sn: sn, level: id, cc: cc, byteRangeStartOffset: byteRangeStartOffset, byteRangeEndOffset: byteRangeEndOffset, decryptdata : fragdecryptdata, programDateTime: programDateTime};
level.fragments.push(frag);
totalduration += duration;
byteRangeStartOffset = null;
programDateTime = null;
}
break;
case 'KEY':
// https://tools.ietf.org/html/draft-pantos-http-live-streaming-08#section-3.4.4
var decryptparams = result[1];
var keyAttrs = new AttrList(decryptparams);
var decryptmethod = keyAttrs.enumeratedString('METHOD'),
decrypturi = keyAttrs.URI,
decryptiv = keyAttrs.hexadecimalInteger('IV');
if (decryptmethod) {
levelkey = { method: null, key: null, iv: null, uri: null };
if ((decrypturi) && (decryptmethod === 'AES-128')) {
levelkey.method = decryptmethod;
// URI to get the key
levelkey.uri = this.resolve(decrypturi, baseurl);
levelkey.key = null;
// Initialization Vector (IV)
levelkey.iv = decryptiv;
}
}
break;
case 'PROGRAM-DATE-TIME':
programDateTime = new Date(Date.parse(result[1]));
break;
default:
break;
}
}
//logger.log('found ' + level.fragments.length + ' fragments');
if(frag && !frag.url) {
level.fragments.pop();
totalduration-=frag.duration;
}
level.totalduration = totalduration;
level.endSN = currentSN - 1;
return level;
}
loadsuccess(event, stats) {
var target = event.currentTarget,
string = target.responseText,
url = target.responseURL,
id = this.id,
id2 = this.id2,
hls = this.hls,
levels;
this.loading = false;
// responseURL not supported on some browsers (it is used to detect URL redirection)
if (url === undefined) {
// fallback to initial URL
url = this.url;
}
stats.tload = performance.now();
stats.mtime = new Date(target.getResponseHeader('Last-Modified'));
if (string.indexOf('#EXTM3U') === 0) {
if (string.indexOf('#EXTINF:') > 0) {
// 1 level playlist
// if first request, fire manifest loaded event, level will be reloaded afterwards
// (this is to have a uniform logic for 1 level/multilevel playlists)
if (this.id === null) {
hls.trigger(Event.MANIFEST_LOADED, {levels: [{url: url}], url: url, stats: stats});
} else {
var levelDetails = this.parseLevelPlaylist(string, url, id);
stats.tparsed = performance.now();
hls.trigger(Event.LEVEL_LOADED, {details: levelDetails, level: id, id: id2, stats: stats});
}
} else {
levels = this.parseMasterPlaylist(string, url);
// multi level playlist, parse level info
if (levels.length) {
hls.trigger(Event.MANIFEST_LOADED, {levels: levels, url: url, stats: stats});
} else {
hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no level found in manifest'});
}
}
} else {
hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no EXTM3U delimiter'});
}
}
loaderror(event) {
var details, fatal;
if (this.id === null) {
details = ErrorDetails.MANIFEST_LOAD_ERROR;
fatal = true;
} else {
details = ErrorDetails.LEVEL_LOAD_ERROR;
fatal = false;
}
if (this.loader) {
this.loader.abort();
}
this.loading = false;
this.hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: details, fatal: fatal, url: this.url, loader: this.loader, response: event.currentTarget, level: this.id, id: this.id2});
}
loadtimeout() {
var details, fatal;
if (this.id === null) {
details = ErrorDetails.MANIFEST_LOAD_TIMEOUT;
fatal = true;
} else {
details = ErrorDetails.LEVEL_LOAD_TIMEOUT;
fatal = false;
}
if (this.loader) {
this.loader.abort();
}
this.loading = false;
this.hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: details, fatal: fatal, url: this.url, loader: this.loader, level: this.id, id: this.id2});
}
}
export default PlaylistLoader;
| ChubbyArse/Emby | MediaBrowser.WebDashboard/dashboard-ui/bower_components/hls.js/src/loader/playlist-loader.js | JavaScript | gpl-2.0 | 10,482 |
(function(){
var PushBullet = {};
PushBullet.init = function(clientId, redirectUri){
this.clientId = clientId;
this.redirectUri = redirectUri;
this.accessToken = localStorage.pushBulletAccessToken;
};
//tests if we are authorized
PushBullet.checkAuth = function(callback){
request("https://api.pushbullet.com/v2/users/me",true,function(results){
callback(results != null);
});
};
//attempts to obtain a working accessToken, once Obtained it callsback with true
PushBullet.doAuth = function(callback){
var popup = window.open("https://www.pushbullet.com/authorize?client_id=" + encodeURIComponent(PushBullet.clientId) + "&redirect_uri=" + encodeURIComponent(this.redirectUri) + "&response_type=token",
"_blank","height=600,width=500,left=" + Math.round($(document).width() / 2 - 250) + ",top=" + Math.round($(document).height() / 2 - 300));
function onClosed(){
PushBullet.accessToken = localStorage.pushBulletAccessToken;
PushBullet.checkAuth(callback);
}
var popupInterval = setInterval(function(){
if (popup == null || popup.closed){
clearInterval(popupInterval);
onClosed();
}
},50);
};
PushBullet.Note = function(title, body){
this.type = "note";
this.title = title;
this.body = body;
};
PushBullet.Link = function(title,body,url){
this.type = "link";
this.title = title;
this.body = body;
this.url = url;
};
PushBullet.CheckList = function(title,items){
this.type = "list";
this.title = title;
this.items = items;
}
PushBullet.pushToChannel = function (channelName,pushBulletMessage){
var params = {
channel_tag: channelName
};
for (var param in pushBulletMessage){
params[param] = pushBulletMessage[param];
}
post("https://api.pushbullet.com/v2/pushes",true,params,function(results){
console.log(results);
});
}
function request(url, useAuth,callback){
var options = {};
if (useAuth && PushBullet.accessToken != null){
options.headers = {
'Authorization': 'Bearer ' + PushBullet.accessToken
};
}
options.success = function(response){
callback(response);
};
options.error = function(){
callback(null);
}
$.ajax(url,options);
}
function post(url,useAuth,params,callback){
var options = {};
if (useAuth && PushBullet.accessToken != null){
options.headers = {
'Authorization': 'Bearer ' + PushBullet.accessToken
};
}
options.type = "POST";
options.data = params;
options.success = function(response){
callback(response);
};
options.error = function(){
callback(null);
}
$.ajax(url,options);
}
window.PushBullet = PushBullet;
})(); | Belthazor2008/googulator | public_html/lib/pushbullet.js | JavaScript | gpl-3.0 | 3,181 |
var gr__expj_8h =
[
[ "gr_expj", "gr__expj_8h.html#a7d0144e5774158b746199c1da4d5b5ac", null ]
]; | aviralchandra/Sandhi | build/gr36/docs/doxygen/html/gr__expj_8h.js | JavaScript | gpl-3.0 | 100 |
/* ************************************************************************
Copyright:
License:
Authors:
************************************************************************ */
qx.Theme.define("${Namespace}.theme.modern.Decoration",
{
decorations :
{
}
}); | 09zwcbupt/undergrad_thesis | ext/poxdesk/qx/component/skeleton/contribution/trunk/source/class/custom/theme/modern/Decoration.tmpl.js | JavaScript | gpl-3.0 | 280 |
exports.play = 'afplay';
exports.raise_volume = 'osascript -e "set Volume 10"'; // unmutes as well | prey/prey-node-client | lib/agent/actions/alarm/mac.js | JavaScript | gpl-3.0 | 98 |
var UniteSettingsRev = new function(){
var arrControls = {};
var colorPicker;
var t=this;
this.getSettingsObject = function(formID){
var obj = new Object();
var form = document.getElementById(formID);
var name,value,type,flagUpdate;
//enabling all form items connected to mx
var len = form.elements.length;
for(var i=0; i<len; i++){
var element = form.elements[i];
if(element.name == "##NAME##[]") continue; //ignore dummy from multi text
name = element.name;
value = element.value;
type = element.type;
if(jQuery(element).hasClass("wp-editor-area"))
type = "editor";
//trace(name + " " + type);
flagUpdate = true;
switch(type){
case "checkbox":
value = form.elements[i].checked;
break;
case "radio":
if(form.elements[i].checked == false)
flagUpdate = false;
break;
case "editor":
value = tinyMCE.get(name).getContent();
break;
case "select-multiple":
value = jQuery(element).val();
if(value)
value = value.toString();
break;
}
if(flagUpdate == true && name != undefined){
if(name.indexOf('[]') > -1){
name = name.replace('[]', '');
if(typeof obj[name] !== 'object') obj[name] = [];
obj[name][Object.keys(obj[name]).length] = value;
}else{
obj[name] = value;
}
}
}
return(obj);
}
this.getsdsformvalue = function(formID){
var obj = new Object();
var form = document.getElementById(formID);
var name,value,type,flagUpdate;
//enabling all form items connected to mx
var len = form.elements.length;
for(var i=0; i<len; i++){
var element = form.elements[i];
if(element.name == "##NAME##[]") continue; //ignore dummy from multi text
name = element.name;
value = element.value;
type = element.type;
if(jQuery(element).hasClass("wp-editor-area"))
type = "editor";
//trace(name + " " + type);
flagUpdate = true;
switch(type){
case "checkbox":
value = form.elements[i].checked;
break;
case "radio":
if(form.elements[i].checked == false)
flagUpdate = false;
break;
case "editor":
value = tinyMCE.get(name).getContent();
break;
case "select-multiple":
value = jQuery(element).val();
if(value)
value = value.toString();
break;
}
if(flagUpdate == true && name != undefined){
if(name.indexOf('[]') > -1){
name = name.replace('[]', '');
if(typeof obj[name] !== 'object') obj[name] = [];
obj[name][Object.keys(obj[name]).length] = value;
}else{
obj[name] = value;
}
}
}
return(obj);
}
/**
* on selects change - impiment the hide/show, enabled/disables functionality
*/
var onSettingChange = function(){
var controlValue = this.value.toLowerCase();
var controlName = this.name;
if(!arrControls[this.name]) return(false);
jQuery(arrControls[this.name]).each(function(){
var childInput = document.getElementById(this.name);
var childRow = document.getElementById(this.name + "_row");
var value = this.value.toLowerCase();
var isChildRadio = (childInput && childInput.tagName == "SPAN" && jQuery(childInput).hasClass("radio_wrapper"));
switch(this.type){
case "enable":
case "disable":
if(childInput){ //disable
if(this.type == "enable" && controlValue != this.value || this.type == "disable" && controlValue == this.value){
childRow.className = "disabled";
if(childInput){
childInput.disabled = true;
childInput.style.color = "";
}
if(isChildRadio)
jQuery(childInput).children("input").prop("disabled","disabled").addClass("disabled");
}
else{ //enable
childRow.className = "";
if(childInput)
childInput.disabled = false;
if(isChildRadio)
jQuery(childInput).children("input").prop("disabled","").removeClass("disabled");
//color the input again
if(jQuery(childInput).hasClass("inputColorPicker")) g_picker.linkTo(childInput);
}
}
break;
case "show":
if(controlValue == this.value) jQuery(childRow).show();
else jQuery(childRow).hide();
break;
case "hide":
if(controlValue == this.value) jQuery(childRow).hide();
else jQuery(childRow).show();
break;
}
});
}
/**
* combine controls to one object, and init control events.
*/
var initControls = function(){
//combine controls
for(key in g_settingsObj){
var obj = g_settingsObj[key];
for(controlKey in obj.controls){
arrControls[controlKey] = obj.controls[controlKey];
}
}
//init events
jQuery(".settings_wrapper select").change(onSettingChange);
jQuery(".settings_wrapper input[type='radio']").change(onSettingChange);
}
//init color picker
var initColorPicker = function(){
var colorPickerWrapper = jQuery('#divColorPicker');
colorPicker = jQuery.farbtastic('#divColorPicker');
jQuery(".inputColorPicker").focus(function(){
colorPicker.linkTo(this);
colorPickerWrapper.show();
var input = jQuery(this);
var offset = input.offset();
var offsetView = jQuery("#viewWrapper").offset();
colorPickerWrapper.css({
"left":offset.left + input.width()+20-offsetView.left,
"top":offset.top - colorPickerWrapper.height() + 100-offsetView.top
});
if (jQuery(input.data('linkto'))) {
var oldval = jQuery(this).val();
jQuery(this).data('int',setInterval(function() {
if(input.val() != oldval){
oldval = input.val();
jQuery('#css_preview').css(input.data('linkto'), oldval);
jQuery('input[name="css_'+input.data('linkto')+'"]').val(oldval);
}
} ,200));
}
}).blur(function() {
clearInterval(jQuery(this).data('int'));
}).click(function(){
return(false); //prevent body click
}).change(function(){
colorPicker.linkTo(this);
colorPicker.setColor(jQuery(this).val());
});
colorPickerWrapper.click(function(){
return(false); //prevent body click
});
jQuery("body").click(function(){
colorPickerWrapper.hide();
});
}
/**
* close all accordion items
*/
var closeAllAccordionItems = function(formID){
jQuery("#"+formID+" .unite-postbox .inside").slideUp("fast");
jQuery("#"+formID+" .unite-postbox h3").addClass("box_closed");
}
/**
* init side settings accordion - started from php
*/
t.initAccordion = function(formID){
var classClosed = "box_closed";
jQuery("#"+formID+" .unite-postbox h3").click(function(){
var handle = jQuery(this);
//open
if(handle.hasClass(classClosed)){
closeAllAccordionItems(formID);
handle.removeClass(classClosed).siblings(".inside").slideDown("fast");
}else{ //close
handle.addClass(classClosed).siblings(".inside").slideUp("fast");
}
});
}
/**
* image search
*/
var initImageSearch = function(){
jQuery(".button-image-select").click(function(){
var settingID = this.id.replace("_button","");
UniteAdminRev.openAddImageDialog("Choose Image",function(urlImage, imageID){
//update input:
jQuery("#"+settingID).val(urlImage);
//update preview image:
var urlShowImage = UniteAdminRev.getUrlShowImage(imageID,100,70,true);
jQuery("#" + settingID + "_button_preview").html('<div style="width:100px;height:70px;background:url(\''+urlShowImage+'\'); background-position:center center; background-size:cover;"></div>');
});
});
jQuery(".button-image-remove").click(function(){
var settingID = this.id.replace("_button_remove","");
jQuery("#"+settingID).val('');
jQuery("#" + settingID + "_button_preview").html('');
});
jQuery(".button-image-select-video").click(function(){
UniteAdminRev.openAddImageDialog("Choose Image",function(urlImage, imageID){
//update input:
jQuery("#input_video_preview").val(urlImage);
//update preview image:
var urlShowImage = UniteAdminRev.getUrlShowImage(imageID,200,150,true);
jQuery("#video-thumbnail-preview").attr('src', urlShowImage);
});
});
jQuery(".button-image-remove-video").click(function(){
jQuery("#input_video_preview").val('');
if(jQuery('#video_block_vimeo').css('display') != 'none')
jQuery("#button_vimeo_search").trigger("click");
if(jQuery('#video_block_youtube').css('display') != 'none')
jQuery("#button_youtube_search").trigger("click");
});
}
/**
* init the settings function, set the tootips on sidebars.
*/
var init = function(){
//init tipsy
jQuery(".list_settings li .setting_text").tipsy({
gravity:"e",
delayIn: 70
});
jQuery(".tipsy_enabled_top").tipsy({
gravity:"s",
delayIn: 70
});
jQuery(".button-primary").tipsy({
gravity:"s",
delayIn: 70
});
//init controls
initControls();
initColorPicker();
initImageSearch();
//init checklist
jQuery(".settings_wrapper .input_checklist").each(function(){
var select = jQuery(this);
var ominWidth = select.data("minwidth");
if (ominWidth==undefined) ominWidth="none"
select.dropdownchecklist({
zIndex:1000,
minWidth:ominWidth,
onItemClick: function(checkbox,selector) {
for (var i=0;i<20;i++)
if (checkbox.val()=="notselectable"+i) {
//console.log(checkbox.val());
checkbox.attr("checked",false);
}
}
});
select.parent().find('input').each(function() {
var option = jQuery(this);
for (var i=0;i<20;i++)
if (option.val()=="notselectable"+i) option.parent().addClass("dropdowntitleoption");
})
});
}
//call "constructor"
jQuery(document).ready(function(){
init();
});
} // UniteSettings class end
| fwahyudi17/ofiskita | system/configa/revslider/js/settings.js | JavaScript | gpl-3.0 | 9,972 |
define([
'database',
'backbone'
], function (DB, Backbone) {
var MessageModel = Backbone.Model.extend({
defaults: {
messageId: 0,
sender: '',
title: '',
content: '',
hasAttachment: false,
sendDate: new Date(),
url: ''
},
save: function (attributes) {
var deferred = $.Deferred();
var self = this;
var transaction = DB.conx.transaction([
DB.TABLE_MESSAGE
], 'readwrite');
var store = transaction.objectStore(DB.TABLE_MESSAGE);
var request;
if (!attributes) {
request = store.add(this.toJSON());
} else {
self.set(attributes);
request = store.put(this.toJSON(), this.cid);
}
request.onsuccess = function (e) {
if (!attributes) {
self.cid = e.target.result;
}
deferred.resolve();
};
request.onerror = function () {
deferred.reject();
};
return deferred.promise();
},
getData: function (cid) {
var self = this;
var deferred = $.Deferred();
var transaction = DB.conx.transaction([
DB.TABLE_MESSAGE
]);
var store = transaction.objectStore(DB.TABLE_MESSAGE);
var request = store.get(cid);
request.onsuccess = function (e) {
if (request.result) {
var data = request.result;
self.cid = cid;
self.set(data);
deferred.resolve();
} else {
deferred.reject();
}
};
request.onerror = function () {
deferred.reject();
};
return deferred.promise();
},
getNext: function (currentKey) {
var deferred = $.Deferred();
var range = IDBKeyRange.lowerBound(this.get('messageId'), true);
var transaction = DB.conx.transaction([
DB.TABLE_MESSAGE
], 'readonly');
var store = transaction.objectStore(DB.TABLE_MESSAGE);
var index = store.index('messageId');
var request = index.openCursor(range);
request.onsuccess = function (e) {
var nextMessage = null;
var cursor = e.target.result;
if (cursor) {
nextMessage = new MessageModel(cursor.value);
nextMessage.cid = cursor.primaryKey;
}
deferred.resolve(nextMessage);
};
request.onerror = function () {
deferred.reject();
};
return deferred.promise();
},
getPrevious: function () {
var deferred = $.Deferred();
var range = IDBKeyRange.upperBound(this.get('messageId'), true);
var transaction = DB.conx.transaction([
DB.TABLE_MESSAGE
], 'readonly');
var store = transaction.objectStore(DB.TABLE_MESSAGE);
var index = store.index('messageId');
var request = index.openCursor(range, 'prev');
request.onsuccess = function (e) {
var previousMessage = null;
var cursor = e.target.result;
if (cursor) {
previousMessage = new MessageModel(cursor.value);
previousMessage.cid = cursor.primaryKey;
}
deferred.resolve(previousMessage);
};
request.onerror = function () {
deferred.reject();
};
return deferred.promise();
},
delete: function () {
var deferred = $.Deferred();
var transaction = DB.conx.transaction([
DB.TABLE_MESSAGE
], 'readwrite');
var store = transaction.objectStore(DB.TABLE_MESSAGE);
var request = store.clear();
request.onsuccess = function () {
deferred.resolve();
};
request.onerror = function () {
deferred.reject();
};
return deferred.promise();
}
});
return MessageModel;
});
| sanyaade-teachings/mobile-messaging | www/js/models/message.js | JavaScript | agpl-3.0 | 4,522 |
/*
* Copyright (c) 2018. Wise Wild Web
*
* This File is part of Caipi and under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License
* Full license at https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode
*
* @author : Nathanael Braun
* @contact : [email protected]
*/
var cfg = require('$super'),
p = (APP_PORT != 80) ? (":" + APP_PORT) : "",
domain = (__LOCAL__ ? 'mamasound.fr.local' + p : 'mamasound.fr' + p),
url = cfg.wwwDomain ? 'www.' + domain : domain;
export default {
...require('$super'),
PROJECT_NAME : "www.mamasound.fr",
PUBLIC_URL : url,
ROOT_DOMAIN : domain,
API_URL : 'api.' + domain,
UPLOAD_URL : 'upload.' + domain,
STATIC_URL : 'static.' + domain,
STATIC_REDIRECT_URL: __LOCAL__ && 'static.mamasound.fr',
OSM_URL: "http://{s}.tile.osm.org/{z}/{x}/{y}.png",
DB_URL : "mongodb://localhost:27017/www_mamasound_fr",
UPLOAD_DIR : "./uploads/",
CACHE_TM : 1000 * 60 * 2,
SESSION_CHECK_TM: 1000 * 60 * 1,
defaultRootMenuId: "Menu.HyInIUM8.html",
htmlRefs: [
{
"type": "script",
"src" : "https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyA7XcGxipnIMdSSBJHn3tzeJe-fU3ilCak"
},
...(cfg.htmlRefs || [])
]
}; | nathb2b/mamasound.fr | App/config.js | JavaScript | agpl-3.0 | 1,324 |
(function () {
var ns = $.namespace('pskl.service');
ns.SelectedColorsService = function () {
this.reset();
};
ns.SelectedColorsService.prototype.init = function () {
$.subscribe(Events.PRIMARY_COLOR_SELECTED, this.onPrimaryColorUpdate_.bind(this));
$.subscribe(Events.SECONDARY_COLOR_SELECTED, this.onSecondaryColorUpdate_.bind(this));
};
ns.SelectedColorsService.prototype.getPrimaryColor = function () {
return this.primaryColor_;
};
ns.SelectedColorsService.prototype.getSecondaryColor = function () {
return this.secondaryColor_;
};
ns.SelectedColorsService.prototype.reset = function () {
this.primaryColor_ = Constants.DEFAULT_PEN_COLOR;
this.secondaryColor_ = Constants.TRANSPARENT_COLOR;
};
ns.SelectedColorsService.prototype.onPrimaryColorUpdate_ = function (evt, color) {
this.primaryColor_ = color;
};
ns.SelectedColorsService.prototype.onSecondaryColorUpdate_ = function (evt, color) {
this.secondaryColor_ = color;
};
})();
| RichardMarks/piskel | src/js/service/SelectedColorsService.js | JavaScript | agpl-3.0 | 1,011 |
v.setCursorPosition(0,19);
v.type('/');
v.type('/');
v.type('/');
v.type('/');
v.type("ok");
| hlamer/kate | tests/data/indent/cppstyle/comment11/input.js | JavaScript | lgpl-2.1 | 93 |
function main() {
// Widget instantiation metadata...
var widget = {
id: "UploaderPlusAdmin",
name: "SoftwareLoop.UploaderPlusAdmin",
};
model.widgets = [widget];
}
main(); | sprouvez/uploader-plus | surf/src/main/amp/config/alfresco/web-extension/site-webscripts/uploader-plus/uploader-plus-admin.get.js | JavaScript | lgpl-3.0 | 204 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: >
The initial value of Boolean.prototype is the Boolean
prototype object
es5id: 15.6.3.1_A1
description: Checking Boolean.prototype property
---*/
//CHECK#1
if (typeof Boolean.prototype !== "object") {
$ERROR('#1: typeof Boolean.prototype === "object"');
}
//CHECK#2
if (Boolean.prototype != false) {
$ERROR('#2: Boolean.prototype == false');
}
delete Boolean.prototype.toString;
if (Boolean.prototype.toString() !== "[object Boolean]") {
$ERROR('#3: The [[Class]] property of the Boolean prototype object is set to "Boolean"');
}
| m0ppers/arangodb | 3rdParty/V8/V8-5.0.71.39/test/test262/data/test/built-ins/Boolean/prototype/S15.6.3.1_A1.js | JavaScript | apache-2.0 | 694 |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
(function() {
var module = angular.module('pnc.common.restclient');
/**
* @ngdoc service
* @name pnc.common.restclient:Build
* @description
*
*/
module.factory('Build', [
'BuildRecordDAO',
'RunningBuildRecordDAO',
'$q',
function(BuildRecordDAO, RunningBuildRecordDAO, $q) {
return {
get: function(spec) {
var deffered = $q.defer();
function overrideRejection(response) {
return $q.when(response);
}
/*
* In order to return the BuildRecord regardless of whether it is in
* progress or compelted we must attempt to fetch both the
* RunningBuild and the BuildRecord for the given ID in parralell
* (Unless something went wrong one of these requests should succeed
* and one fail). As such we have to catch the rejection for the
* request that failed and return a resolved promise. We can then
* check which request succeeded in the success callback and resolve
* the promise returned to the user with it.
*/
$q.all([
BuildRecordDAO.get(spec).$promise.catch(overrideRejection),
RunningBuildRecordDAO.get(spec).$promise.catch(overrideRejection)
]).then(
function(results) {
// Success - return whichever record we successfully pulled down.
if (results[0].id) {
deffered.resolve(results[0]);
} else if (results[1].id) {
deffered.resolve(results[1]);
} else {
deffered.reject(results);
}
},
function(results) {
// Error
deffered.reject(results);
}
);
return deffered.promise;
}
};
}
]);
})();
| emmettu/pnc | ui/app/common/restclient/services/Build.js | JavaScript | apache-2.0 | 2,590 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* global define, module, require, exports */
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery',
'Slick',
'nf.ErrorHandler',
'nf.Common',
'nf.Client',
'nf.CanvasUtils',
'nf.ng.Bridge',
'nf.Dialog',
'nf.Shell'],
function ($, Slick, nfErrorHandler, nfCommon, nfClient, nfCanvasUtils, nfNgBridge, nfDialog, nfShell) {
return (nf.PolicyManagement = factory($, Slick, nfErrorHandler, nfCommon, nfClient, nfCanvasUtils, nfNgBridge, nfDialog, nfShell));
});
} else if (typeof exports === 'object' && typeof module === 'object') {
module.exports = (nf.PolicyManagement =
factory(require('jquery'),
require('Slick'),
require('nf.ErrorHandler'),
require('nf.Common'),
require('nf.Client'),
require('nf.CanvasUtils'),
require('nf.ng.Bridge'),
require('nf.Dialog'),
require('nf.Shell')));
} else {
nf.PolicyManagement = factory(root.$,
root.Slick,
root.nf.ErrorHandler,
root.nf.Common,
root.nf.Client,
root.nf.CanvasUtils,
root.nf.ng.Bridge,
root.nf.Dialog,
root.nf.Shell);
}
}(this, function ($, Slick, nfErrorHandler, nfCommon, nfClient, nfCanvasUtils, nfNgBridge, nfDialog, nfShell) {
'use strict';
var config = {
urls: {
api: '../nifi-api',
searchTenants: '../nifi-api/tenants/search-results'
}
};
var initialized = false;
var initAddTenantToPolicyDialog = function () {
$('#new-policy-user-button').on('click', function () {
$('#search-users-dialog').modal('show');
$('#search-users-field').focus();
});
$('#delete-policy-button').on('click', function () {
promptToDeletePolicy();
});
$('#search-users-dialog').modal({
scrollableContentStyle: 'scrollable',
headerText: 'Add Users/Groups',
buttons: [{
buttonText: 'Add',
color: {
base: '#728E9B',
hover: '#004849',
text: '#ffffff'
},
handler: {
click: function () {
// add to table and update policy
var policyGrid = $('#policy-table').data('gridInstance');
var policyData = policyGrid.getData();
// begin the update
policyData.beginUpdate();
// add all users/groups
$.each(getTenantsToAdd($('#allowed-users')), function (_, user) {
// remove the user
policyData.addItem(user);
});
$.each(getTenantsToAdd($('#allowed-groups')), function (_, group) {
// remove the user
policyData.addItem(group);
});
// end the update
policyData.endUpdate();
// update the policy
updatePolicy();
// close the dialog
$('#search-users-dialog').modal('hide');
}
}
},
{
buttonText: 'Cancel',
color: {
base: '#E3E8EB',
hover: '#C7D2D7',
text: '#004849'
},
handler: {
click: function () {
// close the dialog
$('#search-users-dialog').modal('hide');
}
}
}],
handler: {
close: function () {
// reset the search fields
$('#search-users-field').userSearchAutocomplete('reset').val('');
// clear the selected users/groups
$('#allowed-users, #allowed-groups').empty();
}
}
});
// listen for removal requests
$(document).on('click', 'div.remove-allowed-entity', function () {
$(this).closest('li').remove();
});
// configure the user auto complete
$.widget('nf.userSearchAutocomplete', $.ui.autocomplete, {
reset: function () {
this.term = null;
},
_create: function() {
this._super();
this.widget().menu('option', 'items', '> :not(.search-no-matches)' );
},
_normalize: function (searchResults) {
var items = [];
items.push(searchResults);
return items;
},
_renderMenu: function (ul, items) {
// results are normalized into a single element array
var searchResults = items[0];
var allowedGroups = getAllAllowedGroups();
var allowedUsers = getAllAllowedUsers();
var nfUserSearchAutocomplete = this;
$.each(searchResults.userGroups, function (_, tenant) {
// see if this match is not already selected
if ($.inArray(tenant.id, allowedGroups) === -1) {
nfUserSearchAutocomplete._renderGroup(ul, $.extend({
type: 'group'
}, tenant));
}
});
$.each(searchResults.users, function (_, tenant) {
// see if this match is not already selected
if ($.inArray(tenant.id, allowedUsers) === -1) {
nfUserSearchAutocomplete._renderUser(ul, $.extend({
type: 'user'
}, tenant));
}
});
// ensure there were some results
if (ul.children().length === 0) {
ul.append('<li class="unset search-no-matches">No users matched the search terms</li>');
}
},
_resizeMenu: function () {
var ul = this.menu.element;
ul.width($('#search-users-field').outerWidth() - 2);
},
_renderUser: function (ul, match) {
var userContent = $('<a></a>').text(match.component.identity);
return $('<li></li>').data('ui-autocomplete-item', match).append(userContent).appendTo(ul);
},
_renderGroup: function (ul, match) {
var groupLabel = $('<span></span>').text(match.component.identity);
var groupContent = $('<a></a>').append('<div class="fa fa-users" style="margin-right: 5px;"></div>').append(groupLabel);
return $('<li></li>').data('ui-autocomplete-item', match).append(groupContent).appendTo(ul);
}
});
// configure the autocomplete field
$('#search-users-field').userSearchAutocomplete({
minLength: 0,
appendTo: '#search-users-results',
position: {
my: 'left top',
at: 'left bottom',
offset: '0 1'
},
source: function (request, response) {
// create the search request
$.ajax({
type: 'GET',
data: {
q: request.term
},
dataType: 'json',
url: config.urls.searchTenants
}).done(function (searchResponse) {
response(searchResponse);
});
},
select: function (event, ui) {
addAllowedTenant(ui.item);
// reset the search field
$(this).val('');
// stop event propagation
return false;
}
});
};
/**
* Gets all allowed groups including those already in the policy and those selected while searching (not yet saved).
*
* @returns {Array}
*/
var getAllAllowedGroups = function () {
var policyGrid = $('#policy-table').data('gridInstance');
var policyData = policyGrid.getData();
var userGroups = [];
// consider existing groups in the policy table
var items = policyData.getItems();
$.each(items, function (_, item) {
if (item.type === 'group') {
userGroups.push(item.id);
}
});
// also consider groups already selected in the search users dialog
$.each(getTenantsToAdd($('#allowed-groups')), function (_, group) {
userGroups.push(group.id);
});
return userGroups;
};
/**
* Gets the user groups that will be added upon applying the changes.
*
* @param {jQuery} container
* @returns {Array}
*/
var getTenantsToAdd = function (container) {
var tenants = [];
// also consider groups already selected in the search users dialog
container.children('li').each(function (_, allowedTenant) {
var tenant = $(allowedTenant).data('tenant');
if (nfCommon.isDefinedAndNotNull(tenant)) {
tenants.push(tenant);
}
});
return tenants;
};
/**
* Gets all allowed users including those already in the policy and those selected while searching (not yet saved).
*
* @returns {Array}
*/
var getAllAllowedUsers = function () {
var policyGrid = $('#policy-table').data('gridInstance');
var policyData = policyGrid.getData();
var users = [];
// consider existing users in the policy table
var items = policyData.getItems();
$.each(items, function (_, item) {
if (item.type === 'user') {
users.push(item.id);
}
});
// also consider users already selected in the search users dialog
$.each(getTenantsToAdd($('#allowed-users')), function (_, user) {
users.push(user.id);
});
return users;
};
/**
* Added the specified tenant to the listing of users/groups which will be added when applied.
*
* @param allowedTenant user/group to add
*/
var addAllowedTenant = function (allowedTenant) {
var allowedTenants = allowedTenant.type === 'user' ? $('#allowed-users') : $('#allowed-groups');
// append the user
var tenant = $('<span></span>').addClass('allowed-entity ellipsis').text(allowedTenant.component.identity).ellipsis();
var tenantAction = $('<div></div>').addClass('remove-allowed-entity fa fa-trash');
$('<li></li>').data('tenant', allowedTenant).append(tenant).append(tenantAction).appendTo(allowedTenants);
};
/**
* Determines whether the specified global policy type supports read/write options.
*
* @param policyType global policy type
* @returns {boolean} whether the policy supports read/write options
*/
var globalPolicySupportsReadWrite = function (policyType) {
return policyType === 'controller' || policyType === 'counters' || policyType === 'policies' || policyType === 'tenants';
};
/**
* Determines whether the specified global policy type only supports write.
*
* @param policyType global policy type
* @returns {boolean} whether the policy only supports write
*/
var globalPolicySupportsWrite = function (policyType) {
return policyType === 'proxy' || policyType === 'restricted-components';
};
/**
* Initializes the policy table.
*/
var initPolicyTable = function () {
$('#override-policy-dialog').modal({
headerText: 'Override Policy',
buttons: [{
buttonText: 'Override',
color: {
base: '#728E9B',
hover: '#004849',
text: '#ffffff'
},
handler: {
click: function () {
// create the policy, copying if appropriate
createPolicy($('#copy-policy-radio-button').is(':checked'));
$(this).modal('hide');
}
}
}, {
buttonText: 'Cancel',
color: {
base: '#E3E8EB',
hover: '#C7D2D7',
text: '#004849'
},
handler: {
click: function () {
$(this).modal('hide');
}
}
}],
handler: {
close: function () {
// reset the radio button
$('#copy-policy-radio-button').prop('checked', true);
}
}
});
// create/add a policy
$('#create-policy-link, #add-local-admin-link').on('click', function () {
createPolicy(false);
});
// override a policy
$('#override-policy-link').on('click', function () {
$('#override-policy-dialog').modal('show');
});
// policy type listing
$('#policy-type-list').combo({
options: [
nfCommon.getPolicyTypeListing('flow'),
nfCommon.getPolicyTypeListing('controller'),
nfCommon.getPolicyTypeListing('provenance'),
nfCommon.getPolicyTypeListing('restricted-components'),
nfCommon.getPolicyTypeListing('policies'),
nfCommon.getPolicyTypeListing('tenants'),
nfCommon.getPolicyTypeListing('site-to-site'),
nfCommon.getPolicyTypeListing('system'),
nfCommon.getPolicyTypeListing('proxy'),
nfCommon.getPolicyTypeListing('counters')],
select: function (option) {
if (initialized) {
// record the policy type
$('#selected-policy-type').text(option.value);
// if the option is for a specific component
if (globalPolicySupportsReadWrite(option.value)) {
// update the policy target and let it relaod the policy
$('#controller-policy-target').combo('setSelectedOption', {
'value': 'read'
}).show();
} else {
$('#controller-policy-target').hide();
// record the action
if (globalPolicySupportsWrite(option.value)) {
$('#selected-policy-action').text('write');
} else {
$('#selected-policy-action').text('read');
}
// reload the policy
loadPolicy();
}
}
}
});
// controller policy target
$('#controller-policy-target').combo({
options: [{
text: 'view',
value: 'read'
}, {
text: 'modify',
value: 'write'
}],
select: function (option) {
if (initialized) {
// record the policy action
$('#selected-policy-action').text(option.value);
// reload the policy
loadPolicy();
}
}
});
// component policy target
$('#component-policy-target').combo({
options: [{
text: 'view the component',
value: 'read-component',
description: 'Allows users to view component configuration details'
}, {
text: 'modify the component',
value: 'write-component',
description: 'Allows users to modify component configuration details'
}, {
text: 'view the data',
value: 'read-data',
description: 'Allows users to view metadata and content for this component through provenance data and flowfile queues in outbound connections'
}, {
text: 'modify the data',
value: 'write-data',
description: 'Allows users to empty flowfile queues in outbound connections and submit replays'
}, {
text: 'receive data via site-to-site',
value: 'write-receive-data',
description: 'Allows this port to receive data from these NiFi instances',
disabled: true
}, {
text: 'send data via site-to-site',
value: 'write-send-data',
description: 'Allows this port to send data to these NiFi instances',
disabled: true
}, {
text: 'view the policies',
value: 'read-policies',
description: 'Allows users to view the list of users who can view/modify this component'
}, {
text: 'modify the policies',
value: 'write-policies',
description: 'Allows users to modify the list of users who can view/modify this component'
}],
select: function (option) {
if (initialized) {
var resource = $('#selected-policy-component-type').text();
if (option.value === 'read-component') {
$('#selected-policy-action').text('read');
} else if (option.value === 'write-component') {
$('#selected-policy-action').text('write');
} else if (option.value === 'read-data') {
$('#selected-policy-action').text('read');
resource = ('data/' + resource);
} else if (option.value === 'write-data') {
$('#selected-policy-action').text('write');
resource = ('data/' + resource);
} else if (option.value === 'read-policies') {
$('#selected-policy-action').text('read');
resource = ('policies/' + resource);
} else if (option.value === 'write-policies') {
$('#selected-policy-action').text('write');
resource = ('policies/' + resource);
} else if (option.value === 'write-receive-data') {
$('#selected-policy-action').text('write');
resource = 'data-transfer/input-ports';
} else if (option.value === 'write-send-data') {
$('#selected-policy-action').text('write');
resource = 'data-transfer/output-ports';
}
// set the resource
$('#selected-policy-type').text(resource);
// reload the policy
loadPolicy();
}
}
});
// function for formatting the user identity
var identityFormatter = function (row, cell, value, columnDef, dataContext) {
var markup = '';
if (dataContext.type === 'group') {
markup += '<div class="fa fa-users" style="margin-right: 5px;"></div>';
}
markup += dataContext.component.identity;
return markup;
};
// function for formatting the actions column
var actionFormatter = function (row, cell, value, columnDef, dataContext) {
var markup = '';
// see if the user has permissions for the current policy
var currentEntity = $('#policy-table').data('policy');
var isPolicyEditable = $('#delete-policy-button').is(':disabled') === false;
if (currentEntity.permissions.canWrite === true && isPolicyEditable) {
markup += '<div title="Remove" class="pointer delete-user fa fa-trash"></div>';
}
return markup;
};
// initialize the templates table
var usersColumns = [
{
id: 'identity',
name: 'User',
sortable: true,
resizable: true,
formatter: identityFormatter
},
{
id: 'actions',
name: ' ',
sortable: false,
resizable: false,
formatter: actionFormatter,
width: 100,
maxWidth: 100
}
];
var usersOptions = {
forceFitColumns: true,
enableTextSelectionOnCells: true,
enableCellNavigation: true,
enableColumnReorder: false,
autoEdit: false
};
// initialize the dataview
var policyData = new Slick.Data.DataView({
inlineFilters: false
});
policyData.setItems([]);
// initialize the sort
sort({
columnId: 'identity',
sortAsc: true
}, policyData);
// initialize the grid
var policyGrid = new Slick.Grid('#policy-table', policyData, usersColumns, usersOptions);
policyGrid.setSelectionModel(new Slick.RowSelectionModel());
policyGrid.registerPlugin(new Slick.AutoTooltips());
policyGrid.setSortColumn('identity', true);
policyGrid.onSort.subscribe(function (e, args) {
sort({
columnId: args.sortCol.id,
sortAsc: args.sortAsc
}, policyData);
});
// configure a click listener
policyGrid.onClick.subscribe(function (e, args) {
var target = $(e.target);
// get the node at this row
var item = policyData.getItem(args.row);
// determine the desired action
if (policyGrid.getColumns()[args.cell].id === 'actions') {
if (target.hasClass('delete-user')) {
promptToRemoveUserFromPolicy(item);
}
}
});
// wire up the dataview to the grid
policyData.onRowCountChanged.subscribe(function (e, args) {
policyGrid.updateRowCount();
policyGrid.render();
// update the total number of displayed policy users
$('#displayed-policy-users').text(args.current);
});
policyData.onRowsChanged.subscribe(function (e, args) {
policyGrid.invalidateRows(args.rows);
policyGrid.render();
});
// hold onto an instance of the grid
$('#policy-table').data('gridInstance', policyGrid);
// initialize the number of displayed items
$('#displayed-policy-users').text('0');
};
/**
* Sorts the specified data using the specified sort details.
*
* @param {object} sortDetails
* @param {object} data
*/
var sort = function (sortDetails, data) {
// defines a function for sorting
var comparer = function (a, b) {
if(a.permissions.canRead && b.permissions.canRead) {
var aString = nfCommon.isDefinedAndNotNull(a.component[sortDetails.columnId]) ? a.component[sortDetails.columnId] : '';
var bString = nfCommon.isDefinedAndNotNull(b.component[sortDetails.columnId]) ? b.component[sortDetails.columnId] : '';
return aString === bString ? 0 : aString > bString ? 1 : -1;
} else {
if (!a.permissions.canRead && !b.permissions.canRead){
return 0;
}
if(a.permissions.canRead){
return 1;
} else {
return -1;
}
}
};
// perform the sort
data.sort(comparer, sortDetails.sortAsc);
};
/**
* Prompts for the removal of the specified user.
*
* @param item
*/
var promptToRemoveUserFromPolicy = function (item) {
nfDialog.showYesNoDialog({
headerText: 'Update Policy',
dialogContent: 'Remove \'' + nfCommon.escapeHtml(item.component.identity) + '\' from this policy?',
yesHandler: function () {
removeUserFromPolicy(item);
}
});
};
/**
* Removes the specified item from the current policy.
*
* @param item
*/
var removeUserFromPolicy = function (item) {
var policyGrid = $('#policy-table').data('gridInstance');
var policyData = policyGrid.getData();
// begin the update
policyData.beginUpdate();
// remove the user
policyData.deleteItem(item.id);
// end the update
policyData.endUpdate();
// save the configuration
updatePolicy();
};
/**
* Prompts for the deletion of the selected policy.
*/
var promptToDeletePolicy = function () {
nfDialog.showYesNoDialog({
headerText: 'Delete Policy',
dialogContent: 'By deleting this policy, the permissions for this component will revert to the inherited policy if applicable.',
yesText: 'Delete',
noText: 'Cancel',
yesHandler: function () {
deletePolicy();
}
});
};
/**
* Deletes the current policy.
*/
var deletePolicy = function () {
var currentEntity = $('#policy-table').data('policy');
if (nfCommon.isDefinedAndNotNull(currentEntity)) {
$.ajax({
type: 'DELETE',
url: currentEntity.uri + '?' + $.param(nfClient.getRevision(currentEntity)),
dataType: 'json'
}).done(function () {
loadPolicy();
}).fail(function (xhr, status, error) {
nfErrorHandler.handleAjaxError(xhr, status, error);
resetPolicy();
loadPolicy();
});
} else {
nfDialog.showOkDialog({
headerText: 'Delete Policy',
dialogContent: 'No policy selected'
});
}
};
/**
* Gets the currently selected resource.
*/
var getSelectedResourceAndAction = function () {
var componentId = $('#selected-policy-component-id').text();
var resource = $('#selected-policy-type').text();
if (componentId !== '') {
resource += ('/' + componentId);
}
return {
'action': $('#selected-policy-action').text(),
'resource': '/' + resource
};
};
/**
* Populates the table with the specified users and groups.
*
* @param users
* @param userGroups
*/
var populateTable = function (users, userGroups) {
var policyGrid = $('#policy-table').data('gridInstance');
var policyData = policyGrid.getData();
// begin the update
policyData.beginUpdate();
var policyUsers = [];
// add each user
$.each(users, function (_, user) {
policyUsers.push($.extend({
type: 'user'
}, user));
});
// add each group
$.each(userGroups, function (_, group) {
policyUsers.push($.extend({
type: 'group'
}, group));
});
// set the rows
policyData.setItems(policyUsers);
// end the update
policyData.endUpdate();
// re-sort and clear selection after updating
policyData.reSort();
policyGrid.invalidate();
policyGrid.getSelectionModel().setSelectedRows([]);
};
/**
* Converts the specified resource into human readable form.
*
* @param resource
*/
var getResourceMessage = function (resource) {
if (resource === '/policies') {
return $('<span>Showing effective policy inherited from all policies.</span>');
} else if (resource === '/controller') {
return $('<span>Showing effective policy inherited from the controller.</span>');
} else {
// extract the group id
var processGroupId = nfCommon.substringAfterLast(resource, '/');
var processGroupName = processGroupId;
// attempt to resolve the group name
var breadcrumbs = nfNgBridge.injector.get('breadcrumbsCtrl').getBreadcrumbs();
$.each(breadcrumbs, function (_, breadcrumbEntity) {
if (breadcrumbEntity.id === processGroupId) {
processGroupName = breadcrumbEntity.label;
return false;
}
});
// build the mark up
return $('<span>Showing effective policy inherited from Process Group </span>')
.append( $('<span class="link ellipsis" style="max-width: 200px; vertical-align: top;"></span>')
.text(processGroupName)
.attr('title', processGroupName)
.on('click', function () {
// close the shell
$('#shell-close-button').click();
// load the correct group and unselect everything if necessary
nfCanvasUtils.getComponentByType('ProcessGroup').enterGroup(processGroupId).done(function () {
nfCanvasUtils.getSelection().classed('selected', false);
// inform Angular app that values have changed
nfNgBridge.digest();
});
})
).append('<span>.</span>');
}
};
/**
* Populates the specified policy.
*
* @param policyEntity
*/
var populatePolicy = function (policyEntity) {
var policy = policyEntity.component;
// get the currently selected policy
var resourceAndAction = getSelectedResourceAndAction();
// reset of the policy message
resetPolicyMessage();
// store the current policy version
$('#policy-table').data('policy', policyEntity);
// see if the policy is for this resource
if (resourceAndAction.resource === policy.resource) {
// allow remove when policy is not inherited
$('#delete-policy-button').prop('disabled', policyEntity.permissions.canWrite === false);
// allow modification if allowed
$('#new-policy-user-button').prop('disabled', policyEntity.permissions.canWrite === false);
} else {
$('#policy-message').append(getResourceMessage(policy.resource));
// policy is inherited, we do not know if the user has permissions to modify the desired policy... show button and let server decide
$('#override-policy-message').show();
// do not support policy deletion/modification
$('#delete-policy-button').prop('disabled', true);
$('#new-policy-user-button').prop('disabled', true);
}
// populate the table
populateTable(policy.users, policy.userGroups);
};
/**
* Loads the configuration for the specified process group.
*/
var loadPolicy = function () {
var resourceAndAction = getSelectedResourceAndAction();
var policyDeferred;
if (resourceAndAction.resource.startsWith('/policies')) {
$('#admin-policy-message').show();
policyDeferred = $.Deferred(function (deferred) {
$.ajax({
type: 'GET',
url: '../nifi-api/policies/' + resourceAndAction.action + resourceAndAction.resource,
dataType: 'json'
}).done(function (policyEntity) {
// update the refresh timestamp
$('#policy-last-refreshed').text(policyEntity.generated);
// ensure appropriate actions for the loaded policy
if (policyEntity.permissions.canRead === true) {
var policy = policyEntity.component;
// if the return policy is for the desired policy (not inherited, show it)
if (resourceAndAction.resource === policy.resource) {
// populate the policy details
populatePolicy(policyEntity);
} else {
// reset the policy
resetPolicy();
// show an appropriate message
$('#policy-message').text('No component specific administrators.');
// we don't know if the user has permissions to the desired policy... show create button and allow the server to decide
$('#add-local-admin-message').show();
}
} else {
// reset the policy
resetPolicy();
// show an appropriate message
$('#policy-message').text('No component specific administrators.');
// we don't know if the user has permissions to the desired policy... show create button and allow the server to decide
$('#add-local-admin-message').show();
}
deferred.resolve();
}).fail(function (xhr, status, error) {
if (xhr.status === 404) {
// reset the policy
resetPolicy();
// show an appropriate message
$('#policy-message').text('No component specific administrators.');
// we don't know if the user has permissions to the desired policy... show create button and allow the server to decide
$('#add-local-admin-message').show();
deferred.resolve();
} else if (xhr.status === 403) {
// reset the policy
resetPolicy();
// show an appropriate message
$('#policy-message').text('Not authorized to access the policy for the specified resource.');
deferred.resolve();
} else {
// reset the policy
resetPolicy();
deferred.reject();
nfErrorHandler.handleAjaxError(xhr, status, error);
}
});
}).promise();
} else {
$('#admin-policy-message').hide();
policyDeferred = $.Deferred(function (deferred) {
$.ajax({
type: 'GET',
url: '../nifi-api/policies/' + resourceAndAction.action + resourceAndAction.resource,
dataType: 'json'
}).done(function (policyEntity) {
// return OK so we either have access to the policy or we don't have access to an inherited policy
// update the refresh timestamp
$('#policy-last-refreshed').text(policyEntity.generated);
// ensure appropriate actions for the loaded policy
if (policyEntity.permissions.canRead === true) {
// populate the policy details
populatePolicy(policyEntity);
} else {
// reset the policy
resetPolicy();
// since we cannot read, the policy may be inherited or not... we cannot tell
$('#policy-message').text('Not authorized to view the policy.');
// allow option to override because we don't know if it's supported or not
$('#override-policy-message').show();
}
deferred.resolve();
}).fail(function (xhr, status, error) {
if (xhr.status === 404) {
// reset the policy
resetPolicy();
// show an appropriate message
$('#policy-message').text('No policy for the specified resource.');
// we don't know if the user has permissions to the desired policy... show create button and allow the server to decide
$('#new-policy-message').show();
deferred.resolve();
} else if (xhr.status === 403) {
// reset the policy
resetPolicy();
// show an appropriate message
$('#policy-message').text('Not authorized to access the policy for the specified resource.');
deferred.resolve();
} else {
resetPolicy();
deferred.reject();
nfErrorHandler.handleAjaxError(xhr, status, error);
}
});
}).promise();
}
return policyDeferred;
};
/**
* Creates a new policy for the current selection.
*
* @param copyInheritedPolicy Whether or not to copy the inherited policy
*/
var createPolicy = function (copyInheritedPolicy) {
var resourceAndAction = getSelectedResourceAndAction();
var users = [];
var userGroups = [];
if (copyInheritedPolicy === true) {
var policyGrid = $('#policy-table').data('gridInstance');
var policyData = policyGrid.getData();
var items = policyData.getItems();
$.each(items, function (_, item) {
var itemCopy = $.extend({}, item);
if (itemCopy.type === 'user') {
users.push(itemCopy);
} else {
userGroups.push(itemCopy);
}
// remove the type as it was added client side to render differently and is not part of the actual schema
delete itemCopy.type;
});
}
var entity = {
'revision': nfClient.getRevision({
'revision': {
'version': 0
}
}),
'component': {
'action': resourceAndAction.action,
'resource': resourceAndAction.resource,
'users': users,
'userGroups': userGroups
}
};
$.ajax({
type: 'POST',
url: '../nifi-api/policies',
data: JSON.stringify(entity),
dataType: 'json',
contentType: 'application/json'
}).done(function (policyEntity) {
// ensure appropriate actions for the loaded policy
if (policyEntity.permissions.canRead === true) {
// populate the policy details
populatePolicy(policyEntity);
} else {
// the request succeeded but we don't have access to the policy... reset/reload the policy
resetPolicy();
loadPolicy();
}
}).fail(nfErrorHandler.handleAjaxError);
};
/**
* Updates the policy for the current selection.
*/
var updatePolicy = function () {
var policyGrid = $('#policy-table').data('gridInstance');
var policyData = policyGrid.getData();
var users = [];
var userGroups = [];
var items = policyData.getItems();
$.each(items, function (_, item) {
var itemCopy = $.extend({}, item);
if (itemCopy.type === 'user') {
users.push(itemCopy);
} else {
userGroups.push(itemCopy);
}
// remove the type as it was added client side to render differently and is not part of the actual schema
delete itemCopy.type;
});
var currentEntity = $('#policy-table').data('policy');
if (nfCommon.isDefinedAndNotNull(currentEntity)) {
var entity = {
'revision': nfClient.getRevision(currentEntity),
'component': {
'id': currentEntity.id,
'users': users,
'userGroups': userGroups
}
};
$.ajax({
type: 'PUT',
url: currentEntity.uri,
data: JSON.stringify(entity),
dataType: 'json',
contentType: 'application/json'
}).done(function (policyEntity) {
// ensure appropriate actions for the loaded policy
if (policyEntity.permissions.canRead === true) {
// populate the policy details
populatePolicy(policyEntity);
} else {
// the request succeeded but we don't have access to the policy... reset/reload the policy
resetPolicy();
loadPolicy();
}
}).fail(function (xhr, status, error) {
nfErrorHandler.handleAjaxError(xhr, status, error);
resetPolicy();
loadPolicy();
}).always(function () {
nfCanvasUtils.reload({
'transition': true
});
});
} else {
nfDialog.showOkDialog({
headerText: 'Update Policy',
dialogContent: 'No policy selected'
});
}
};
/**
* Shows the process group configuration.
*/
var showPolicy = function () {
// show the configuration dialog
nfShell.showContent('#policy-management').always(function () {
reset();
});
// adjust the table size
nfPolicyManagement.resetTableSize();
};
/**
* Reset the policy message.
*/
var resetPolicyMessage = function () {
$('#policy-message').text('').empty();
$('#new-policy-message').hide();
$('#override-policy-message').hide();
$('#add-local-admin-message').hide();
};
/**
* Reset the policy.
*/
var resetPolicy = function () {
resetPolicyMessage();
// reset button state
$('#delete-policy-button').prop('disabled', true);
$('#new-policy-user-button').prop('disabled', true);
// reset the current policy
$('#policy-table').removeData('policy');
// populate the table with no users
populateTable([], []);
}
/**
* Resets the policy management dialog.
*/
var reset = function () {
resetPolicy();
// clear the selected policy details
$('#selected-policy-type').text('');
$('#selected-policy-action').text('');
$('#selected-policy-component-id').text('');
$('#selected-policy-component-type').text('');
// clear the selected component details
$('div.policy-selected-component-container').hide();
};
var nfPolicyManagement = {
/**
* Initializes the settings page.
*/
init: function () {
initAddTenantToPolicyDialog();
initPolicyTable();
$('#policy-refresh-button').on('click', function () {
loadPolicy();
});
// reset the policy to initialize
resetPolicy();
// mark as initialized
initialized = true;
},
/**
* Update the size of the grid based on its container's current size.
*/
resetTableSize: function () {
var policyTable = $('#policy-table');
if (policyTable.is(':visible')) {
var policyGrid = policyTable.data('gridInstance');
if (nfCommon.isDefinedAndNotNull(policyGrid)) {
policyGrid.resizeCanvas();
}
}
},
/**
* Shows the controller service policy.
*
* @param d
*/
showControllerServicePolicy: function (d) {
// reset the policy message
resetPolicyMessage();
// update the policy controls visibility
$('#component-policy-controls').show();
$('#global-policy-controls').hide();
// update the visibility
if (d.permissions.canRead === true) {
$('#policy-selected-controller-service-container div.policy-selected-component-name').text(d.component.name);
} else {
$('#policy-selected-controller-service-container div.policy-selected-component-name').text(d.id);
}
$('#policy-selected-controller-service-container').show();
// populate the initial resource
$('#selected-policy-component-id').text(d.id);
$('#selected-policy-component-type').text('controller-services');
$('#component-policy-target')
.combo('setOptionEnabled', {
value: 'write-receive-data'
}, false)
.combo('setOptionEnabled', {
value: 'write-send-data'
}, false)
.combo('setOptionEnabled', {
value: 'read-data'
}, false)
.combo('setOptionEnabled', {
value: 'write-data'
}, false)
.combo('setSelectedOption', {
value: 'read-component'
});
return loadPolicy().always(showPolicy);
},
/**
* Shows the reporting task policy.
*
* @param d
*/
showReportingTaskPolicy: function (d) {
// reset the policy message
resetPolicyMessage();
// update the policy controls visibility
$('#component-policy-controls').show();
$('#global-policy-controls').hide();
// update the visibility
if (d.permissions.canRead === true) {
$('#policy-selected-reporting-task-container div.policy-selected-component-name').text(d.component.name);
} else {
$('#policy-selected-reporting-task-container div.policy-selected-component-name').text(d.id);
}
$('#policy-selected-reporting-task-container').show();
// populate the initial resource
$('#selected-policy-component-id').text(d.id);
$('#selected-policy-component-type').text('reporting-tasks');
$('#component-policy-target')
.combo('setOptionEnabled', {
value: 'write-receive-data'
}, false)
.combo('setOptionEnabled', {
value: 'write-send-data'
}, false)
.combo('setOptionEnabled', {
value: 'read-data'
}, false)
.combo('setOptionEnabled', {
value: 'write-data'
}, false)
.combo('setSelectedOption', {
value: 'read-component'
});
return loadPolicy().always(showPolicy);
},
/**
* Shows the template policy.
*
* @param d
*/
showTemplatePolicy: function (d) {
// reset the policy message
resetPolicyMessage();
// update the policy controls visibility
$('#component-policy-controls').show();
$('#global-policy-controls').hide();
// update the visibility
if (d.permissions.canRead === true) {
$('#policy-selected-template-container div.policy-selected-component-name').text(d.template.name);
} else {
$('#policy-selected-template-container div.policy-selected-component-name').text(d.id);
}
$('#policy-selected-template-container').show();
// populate the initial resource
$('#selected-policy-component-id').text(d.id);
$('#selected-policy-component-type').text('templates');
$('#component-policy-target')
.combo('setOptionEnabled', {
value: 'write-receive-data'
}, false)
.combo('setOptionEnabled', {
value: 'write-send-data'
}, false)
.combo('setOptionEnabled', {
value: 'read-data'
}, false)
.combo('setOptionEnabled', {
value: 'write-data'
}, false)
.combo('setSelectedOption', {
value: 'read-component'
});
return loadPolicy().always(showPolicy);
},
/**
* Shows the component policy dialog.
*/
showComponentPolicy: function (selection) {
// reset the policy message
resetPolicyMessage();
// update the policy controls visibility
$('#component-policy-controls').show();
$('#global-policy-controls').hide();
// update the visibility
$('#policy-selected-component-container').show();
var resource;
if (selection.empty()) {
$('#selected-policy-component-id').text(nfCanvasUtils.getGroupId());
resource = 'process-groups';
// disable site to site option
$('#component-policy-target')
.combo('setOptionEnabled', {
value: 'write-receive-data'
}, false)
.combo('setOptionEnabled', {
value: 'write-send-data'
}, false)
.combo('setOptionEnabled', {
value: 'read-data'
}, true)
.combo('setOptionEnabled', {
value: 'write-data'
}, true);
} else {
var d = selection.datum();
$('#selected-policy-component-id').text(d.id);
if (nfCanvasUtils.isProcessor(selection)) {
resource = 'processors';
} else if (nfCanvasUtils.isProcessGroup(selection)) {
resource = 'process-groups';
} else if (nfCanvasUtils.isInputPort(selection)) {
resource = 'input-ports';
} else if (nfCanvasUtils.isOutputPort(selection)) {
resource = 'output-ports';
} else if (nfCanvasUtils.isRemoteProcessGroup(selection)) {
resource = 'remote-process-groups';
} else if (nfCanvasUtils.isLabel(selection)) {
resource = 'labels';
} else if (nfCanvasUtils.isFunnel(selection)) {
resource = 'funnels';
}
// enable site to site option
$('#component-policy-target')
.combo('setOptionEnabled', {
value: 'write-receive-data'
}, nfCanvasUtils.isInputPort(selection) && nfCanvasUtils.getParentGroupId() === null)
.combo('setOptionEnabled', {
value: 'write-send-data'
}, nfCanvasUtils.isOutputPort(selection) && nfCanvasUtils.getParentGroupId() === null)
.combo('setOptionEnabled', {
value: 'read-data'
}, !nfCanvasUtils.isLabel(selection))
.combo('setOptionEnabled', {
value: 'write-data'
}, !nfCanvasUtils.isLabel(selection));
}
// populate the initial resource
$('#selected-policy-component-type').text(resource);
$('#component-policy-target').combo('setSelectedOption', {
value: 'read-component'
});
return loadPolicy().always(showPolicy);
},
/**
* Shows the global policies dialog.
*/
showGlobalPolicies: function () {
// reset the policy message
resetPolicyMessage();
// update the policy controls visibility
$('#component-policy-controls').hide();
$('#global-policy-controls').show();
// reload the current policies
var policyType = $('#policy-type-list').combo('getSelectedOption').value;
$('#selected-policy-type').text(policyType);
if (globalPolicySupportsReadWrite(policyType)) {
$('#selected-policy-action').text($('#controller-policy-target').combo('getSelectedOption').value);
} else if (globalPolicySupportsWrite(policyType)) {
$('#selected-policy-action').text('write');
} else {
$('#selected-policy-action').text('read');
}
return loadPolicy().always(showPolicy);
}
};
return nfPolicyManagement;
})); | tequalsme/nifi | nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-policy-management.js | JavaScript | apache-2.0 | 55,421 |
var estabelecimentoViewCtrl = angular.module('estabelecimentoViewCtrl', ['ngResource']);
estabelecimentoViewCtrl.controller('estabelecimentoViewCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.estabelecimentos = [];
$scope.carregarPontosCriticos = function(){
$http.get("../webresources/com.andepuc.estabelecimentos").success(function (data, status){
$scope.estabelecimentos = data;
});
};
}]); | ScHaFeR/AndePUCRS-WebService | andePuc/target/andePuc-1.0/js/controllers/estabelecimentoViewController.js | JavaScript | apache-2.0 | 497 |
//// [typeOfThisInStaticMembers13.ts]
class C {
static readonly c: "foo" = "foo"
static bar = class Inner {
static [this.c] = 123;
[this.c] = 123;
}
}
//// [typeOfThisInStaticMembers13.js]
var C = /** @class */ (function () {
function C() {
}
var _a, _b, _c, _d;
_a = C;
Object.defineProperty(C, "c", {
enumerable: true,
configurable: true,
writable: true,
value: "foo"
});
Object.defineProperty(C, "bar", {
enumerable: true,
configurable: true,
writable: true,
value: (_b = /** @class */ (function () {
function Inner() {
Object.defineProperty(this, _d, {
enumerable: true,
configurable: true,
writable: true,
value: 123
});
}
return Inner;
}()),
_c = _a.c,
_d = _a.c,
Object.defineProperty(_b, _c, {
enumerable: true,
configurable: true,
writable: true,
value: 123
}),
_b)
});
return C;
}());
| Microsoft/TypeScript | tests/baselines/reference/typeOfThisInStaticMembers13(target=es5).js | JavaScript | apache-2.0 | 1,288 |
// create table view
var tableview = Titanium.UI.createTableView();
Ti.App.fireEvent("show_indicator");
// create table view event listener
tableview.addEventListener('click', function(e)
{
// event data
var index = e.index;
var section = e.section;
var row = e.row;
var rowdata = e.rowData;
Titanium.UI.createAlertDialog({title:'Table View',message:'row ' + row + ' index ' + index + ' section ' + section + ' row data ' + rowdata}).show();
});
var navActInd = Titanium.UI.createActivityIndicator();
navActInd.show();
if (Titanium.Platform.name == 'iPhone OS') {
Titanium.UI.currentWindow.setRightNavButton(navActInd);
}
// add table view to the window
Titanium.UI.currentWindow.add(tableview);
Titanium.Yahoo.yql('select * from flickr.photos.search where text="Cat" limit 10',function(e)
{
var images = [];
var data = e.data;
for (var c=0;c<data.photo.length;c++)
{
var photo = data.photo[c];
// form the flickr url
var url = 'http://farm' + photo.farm + '.static.flickr.com/' + photo.server + '/' + photo.id + '_' + photo.secret + '_m.jpg';
Ti.API.info("flickr url = "+url);
var row = Ti.UI.createTableViewRow({height:60});
var title = Ti.UI.createLabel({
left:70,
right:10,
textAlign:'left',
height:50,
text:photo.title ? photo.title : "Untitled",
font:{fontWeight:'bold',fontSize:18}
});
var image;
if (Titanium.Platform.name == 'android')
{
// iphone moved to a single image property - android needs to do the same
image = Ti.UI.createImageView({
url : url,
height:50,
width:50,
left:10,
defaultImage:'../modules/ui/images/photoDefault.png'
});
}
else
{
image = Ti.UI.createImageView({
image : url,
height:50,
width:50,
left:10,
defaultImage:'../modules/ui/images/photoDefault.png'
});
}
row.add(image);
row.add(title);
images[c] = row;
}
tableview.setData(images);
navActInd.hide();
Ti.App.fireEvent("hide_indicator");
});
| arnaudsj/titanium_mobile | demos/SmokeTest/Resources/examples/yql_flickr.js | JavaScript | apache-2.0 | 1,970 |
'use strict';
let angular = require('angular');
module.exports = angular.module('spinnaker.serverGroup.configure.gce.instanceArchetypeCtrl', [])
.controller('gceInstanceArchetypeCtrl', function($scope, instanceTypeService, modalWizardService) {
var wizard = modalWizardService.getWizard();
$scope.$watch('command.viewState.instanceProfile', function() {
if (!$scope.command.viewState.instanceProfile || $scope.command.viewState.instanceProfile === 'custom') {
wizard.excludePage('instance-type');
} else {
wizard.includePage('instance-type');
wizard.markClean('instance-profile');
wizard.markComplete('instance-profile');
}
});
$scope.$watch('command.viewState.instanceType', function(newVal) {
if (newVal) {
wizard.markClean('instance-profile');
wizard.markComplete('instance-profile');
}
});
}).name;
| zanthrash/deck-1 | app/scripts/modules/google/serverGroup/configure/wizard/ServerGroupInstanceArchetype.controller.js | JavaScript | apache-2.0 | 911 |
/// Copyright (c) 2009 Microsoft Corporation
///
/// Redistribution and use in source and binary forms, with or without modification, are permitted provided
/// that the following conditions are met:
/// * Redistributions of source code must retain the above copyright notice, this list of conditions and
/// the following disclaimer.
/// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
/// the following disclaimer in the documentation and/or other materials provided with the distribution.
/// * Neither the name of Microsoft nor the names of its contributors may be used to
/// endorse or promote products derived from this software without specific prior written permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
/// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
/// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
/// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
/// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
/// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
/// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
ES5Harness.registerTest({
id: "15.4.4.14-9-b-i-6",
path: "TestCases/chapter15/15.4/15.4.4/15.4.4.14/15.4.4.14-9-b-i-6.js",
description: "Array.prototype.indexOf - element to be retrieved is own data property that overrides an inherited accessor property on an Array-like object",
test: function testcase() {
try {
Object.defineProperty(Object.prototype, "0", {
get: function () {
return false;
},
configurable: true
});
return 0 === Array.prototype.indexOf.call({ 0: true, 1: 1, length: 2 }, true);
} finally {
delete Object.prototype[0];
}
},
precondition: function prereq() {
return fnExists(Array.prototype.indexOf) && fnExists(Object.defineProperty) && fnSupportsArrayIndexGettersOnObjects();
}
});
| hnafar/IronJS | Src/Tests/ietestcenter/chapter15/15.4/15.4.4/15.4.4.14/15.4.4.14-9-b-i-6.js | JavaScript | apache-2.0 | 2,446 |
(function () {
"use strict";
var fs = require("fs"),
fse = require("fs-extra"),
path = require("path"),
readline = require("readline");
var _domainManager;
function init(domainManager) {
_domainManager = domainManager;
if (!_domainManager.hasDomain("importNode")) {
_domainManager.registerDomain("importNode", {major: 0, minor: 1});
}
// Get shared project from share
function getSharedProject(callback) {
var sharedPath = path.join(process.cwd(), "share");
fs.readdir(sharedPath, function(error, files) {
callback(null, files);
});
}
function getSharedFile(projectName, callback) {
var fileName;
var sharedPath = path.join(process.cwd(), "share", projectName);
// Get target name from makefile
var makePath = path.join(sharedPath, "makefile");
if (fs.existsSync(makePath)) {
var lineReader = readline.createInterface({
input: fs.createReadStream(makePath)
});
lineReader.on("line", function(line) {
if (line.startsWith("TARGET")) {
var file = line.split("=")[1].trim();
fileName = file.split(".")[0];
}
});
lineReader.on("close", function() {
// FIXME: We just checked wasm and js whether it was exsited
// or not. We need a way to find correct result file.
var wasmPath = path.join(sharedPath, fileName + ".wasm");
var loaderPath = path.join(sharedPath, fileName + ".js");
var fileList = [];
if (fs.existsSync(wasmPath) && fs.existsSync(loaderPath)) {
fileList.push(fileName + ".wasm");
fileList.push(fileName + ".js");
callback(null, fileList);
} else {
callback("Not found wasm");
}
});
} else {
callback("Not found makefile");
}
}
function copySharedFile(projectName, fileList, targetId, callback) {
var sharedPath = path.join(process.cwd(), "share", projectName);
var destPath = path.join(process.cwd(), "projects", targetId);
// Copy files to the target project
fileList.forEach(function(file) {
var sourcePath = path.join(sharedPath, file);
if (fs.existsSync(sourcePath)) {
var destFilePath = path.join(destPath, file);
try {
fse.copySync(sourcePath, destFilePath);
} catch (error) {
return callback("Fail to copy files");
}
}
});
callback(null);
}
function copyFile(projectId, src, name, dest, callback) {
const sourcePath = path.join(process.cwd(), 'projects', projectId, src, name);
const destPath = path.join(process.cwd(), 'projects', projectId, dest, name);
fse.copy(sourcePath, destPath, (err) => {
if (err) {
return callback(err);
}
callback();
});
}
function moveFile(projectId, src, name, dest, callback) {
const sourcePath = path.join(process.cwd(), 'projects', projectId, src, name);
const destPath = path.join(process.cwd(), 'projects', projectId, dest, name);
fse.move(sourcePath, destPath, (err) => {
if (err) {
return callback(err);
}
callback();
});
}
_domainManager.registerCommand(
"importNode",
"getSharedProject",
getSharedProject,
true,
"Get Shared Project",
null,
[
{name: "data", type: "array"}
]
);
_domainManager.registerCommand(
"importNode",
"getSharedFile",
getSharedFile,
true,
"Get Shared File",
[
{name: "projectName", type: "string"}
],
[
{name: "result", type: "array"}
]
);
_domainManager.registerCommand(
"importNode",
"copySharedFile",
copySharedFile,
true,
"Copy Shared File",
[
{name: "projectName", type: "string"},
{name: "fileList", type: "array"},
{name: "targetId", type: "string"}
],
[]
);
_domainManager.registerCommand(
"importNode",
"COPY",
copyFile,
true,
"Copy File",
[
{name: "projectId", type: "string"},
{name: "src", type: "string"},
{name: "name", type: "string"},
{name: "dest", type: "string"}
],
[]
);
_domainManager.registerCommand(
"importNode",
"CUT",
moveFile,
true,
"Move File",
[
{name: "projectId", type: "string"},
{name: "src", type: "string"},
{name: "name", type: "string"},
{name: "dest", type: "string"}
],
[]
);
}
exports.init = init;
}());
| hyundukkim/WATT | libs/brackets-server/embedded-ext/importfile/node/ImportDomain.js | JavaScript | apache-2.0 | 5,812 |
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var S18 = (function (_super) {
__extends(S18, _super);
function S18() {
_super.apply(this, arguments);
}
return S18;
})(S18);
(new S18()).blah;
| hippich/typescript | tests/baselines/reference/recursiveBaseCheck6.js | JavaScript | apache-2.0 | 400 |
'use strict';
var TodoServiceFactory = function(database){
return {
// Return all todos in the database
getTodos: function(){
return database('Todo').select().orderBy('createdAt', 'desc');
},
// Return a single todo by Id
getTodo: function(id){
var p = Promise.defer();
database('Todo').where('id', id).select()
.then(function(rows){
if(rows.length === 0){
//not found
p.reject('TodoService: not found');
}
else {
p.resolve(rows[0]);
}
});
return p.promise;
},
//Update a todo in the database
updateTodo: function(todo){
var p = Promise.defer();
//TODO: real-world validation
database('Todo').update({
text: todo.text,
completed: todo.completed
})
.where('id', todo.id)
.then(function(affectedRows){
if(affectedRows === 1){
p.resolve(todo);
}
else {
p.reject('Not found');
}
});
return p.promise;
},
//Create a new todo in the database
createTodo: function(todo){
var p = Promise.defer();
//TODO: real-world validation
database('Todo').insert(todo)
.then(function(idArray){
//return the newly created todo
todo.id = idArray[0];
p.resolve(todo);
})
.catch(function(err){
p.reject('TodoService: create failed. Error:' + err.toString());
});
return p.promise;
},
//Delete a todo specified by Id
deleteTodo: function(todoId){
var p = Promise.defer();
database('Todo').where('id', todoId).del()
.then(function(affectedRows){
if(affectedRows === 1){
return p.resolve(true);
}
else {
return p.reject('TodoService: not found');
}
})
.catch(function(err){
p.reject('TodoService: delete failed. Error' + err.toString());
});
return p.promise;
}
}
}
module.exports = TodoServiceFactory; | raffaeu/Syncho | src/node_modules/kontainer-di/examples/express/services/todo_service.js | JavaScript | apache-2.0 | 2,050 |
/*
* Copyright 2015-present Boundless Spatial Inc., http://boundlessgeo.com
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
import {connect} from 'react-redux';
import PropTypes from 'prop-types';
import * as mapActions from '../../actions/map';
/** @module components/map/zoom-control
* @example
* import SdkZoomControl from '@boundlessgeo/sdk/components/map/zoom-control';
* import { Provider } from 'react-redux';
* import SdkMap from '@boundlessgeo/sdk/components/map';
* import ReactDOM from 'react-dom';
*
* ReactDOM.render(<Provider store={store}>
* <SdkMap>
* <SdkZoomControl />
* </SdkMap>
* </Provider>, document.getElementById('map'));
*
* @desc Provides 2 buttons to zoom the map (zoom in and out).
*/
class ZoomControl extends React.Component {
render() {
let className = 'sdk-zoom-control';
if (this.props.className) {
className += ' ' + this.props.className;
}
return (
<div className={className} style={this.props.style}>
<button className='sdk-zoom-in' onClick={this.props.zoomIn} title={this.props.zoomInTitle}>+</button>
<button className='sdk-zoom-out' onClick={this.props.zoomOut} title={this.props.zoomOutTitle}>{'\u2212'}</button>
</div>
);
}
}
ZoomControl.propTypes = {
/**
* Css className for the root div.
*/
className: PropTypes.string,
/**
* Style config object for root div.
*/
style: PropTypes.object,
/**
* Title for the zoom in button.
*/
zoomInTitle: PropTypes.string,
/**
* Title for the zoom out button.
*/
zoomOutTitle: PropTypes.string,
};
ZoomControl.defaultProps = {
zoomInTitle: 'Zoom in',
zoomOutTitle: 'Zoom out',
};
function mapDispatchToProps(dispatch) {
return {
zoomIn: () => {
dispatch(mapActions.zoomIn());
},
zoomOut: () => {
dispatch(mapActions.zoomOut());
},
};
}
export default connect(null, mapDispatchToProps)(ZoomControl);
| boundlessgeo/sdk | src/components/map/zoom-control.js | JavaScript | apache-2.0 | 2,469 |
/// Copyright (c) 2009 Microsoft Corporation
///
/// Redistribution and use in source and binary forms, with or without modification, are permitted provided
/// that the following conditions are met:
/// * Redistributions of source code must retain the above copyright notice, this list of conditions and
/// the following disclaimer.
/// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
/// the following disclaimer in the documentation and/or other materials provided with the distribution.
/// * Neither the name of Microsoft nor the names of its contributors may be used to
/// endorse or promote products derived from this software without specific prior written permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
/// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
/// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
/// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
/// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
/// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
/// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
ES5Harness.registerTest({
id: "15.4.4.14-3-21",
path: "TestCases/chapter15/15.4/15.4.4/15.4.4.14/15.4.4.14-3-21.js",
description: "Array.prototype.indexOf - 'length' is an object that has an own valueOf method that returns an object and toString method that returns a string",
test: function testcase() {
var toStringAccessed = false;
var valueOfAccessed = false;
var obj = {
1: true,
length: {
toString: function () {
toStringAccessed = true;
return '2';
},
valueOf: function () {
valueOfAccessed = true;
return {};
}
}
};
return Array.prototype.indexOf.call(obj, true) === 1 && toStringAccessed && valueOfAccessed;
},
precondition: function prereq() {
return fnExists(Array.prototype.indexOf);
}
});
| hnafar/IronJS | Src/Tests/ietestcenter/chapter15/15.4/15.4.4/15.4.4.14/15.4.4.14-3-21.js | JavaScript | apache-2.0 | 2,528 |
define(function(require, exports, module) {
var Morris=require("morris");
require("jquery.bootstrap-datetimepicker");
var Validator = require('bootstrap.validator');
var autoSubmitCondition=require("./autoSubmitCondition.js");
require('common/validator-rules').inject(Validator);
var now = new Date();
exports.run = function() {
if($('#data').length > 0){
var data = eval ("(" + $('#data').attr("value") + ")");
Morris.Line({
element: 'line-data',
data: data,
xkey: 'date',
ykeys: ['count'],
labels: [Translator.trans('班级营收额')],
xLabels:"day"
});
}
$("[name=endTime]").datetimepicker({
autoclose: true,
format: 'yyyy-mm-dd',
minView: 'month'
});
$('[name=endTime]').datetimepicker('setEndDate', now);
$('[name=endTime]').datetimepicker('setStartDate', $('#classroomIncomeStartDate').attr("value"));
$("[name=startTime]").datetimepicker({
autoclose: true,
format: 'yyyy-mm-dd',
minView: 'month'
});
$('[name=startTime]').datetimepicker('setEndDate', now);
$('[name=startTime]').datetimepicker('setStartDate', $('#classroomIncomeStartDate').attr("value"));
var validator = new Validator({
element: '#operation-form'});
validator.addItem({
element: '[name=startTime]',
required: true,
rule:'date_check'
});
validator.addItem({
element: '[name=endTime]',
required: true,
rule:'date_check'
});
validator.addItem({
element: '[name=analysisDateType]',
required: true
});
autoSubmitCondition.autoSubmitCondition();
};
}); | 18826252059/im | web/bundles/topxiaadmin/js/controller/analysis/classroom-income.js | JavaScript | apache-2.0 | 1,998 |
/// Copyright (c) 2009 Microsoft Corporation
///
/// Redistribution and use in source and binary forms, with or without modification, are permitted provided
/// that the following conditions are met:
/// * Redistributions of source code must retain the above copyright notice, this list of conditions and
/// the following disclaimer.
/// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
/// the following disclaimer in the documentation and/or other materials provided with the distribution.
/// * Neither the name of Microsoft nor the names of its contributors may be used to
/// endorse or promote products derived from this software without specific prior written permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
/// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
/// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
/// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
/// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
/// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
/// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
ES5Harness.registerTest({
id: "15.2.3.6-4-45",
path: "TestCases/chapter15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-45.js",
description: "Object.defineProperty - 'O' is the global object that uses Object's [[GetOwnProperty]] method to access the 'name' property (8.12.9 step 1)",
test: function testcase() {
try {
Object.defineProperty(fnGlobalObject(), "foo", {
value: 12,
configurable: true
});
return dataPropertyAttributesAreCorrect(fnGlobalObject(), "foo", 12, false, false, true);
} finally {
delete fnGlobalObject().foo;
}
},
precondition: function prereq() {
return fnExists(Object.defineProperty);
}
});
| hnafar/IronJS | Src/Tests/ietestcenter/chapter15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-45.js | JavaScript | apache-2.0 | 2,309 |
'use strict';
/**
* @license
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
goog.provide('tachyfont.WorkQueue');
goog.require('goog.Promise');
goog.require('tachyfont.Reporter');
/**
* This class manages work queues.
* @param {string} name An identifier useful for error reports.
* @constructor @struct @final
*/
tachyfont.WorkQueue = function(name) {
/** @private @const {string} */
this.name_ = name;
/** @private {!Array<!tachyfont.WorkQueue.Task>} */
this.queue_ = [];
};
/**
* Adds a task.
* @param {function(?)} taskFunction The function to call.
* @param {*} data The data to pass to the function.
* @param {string} fontId An identifier useful for error messages.
* @param {number=} opt_watchDogTime Option watch dog time.
* @return {!tachyfont.WorkQueue.Task} A task object.
*/
tachyfont.WorkQueue.prototype.addTask = function(
taskFunction, data, fontId, opt_watchDogTime) {
var task = new tachyfont.WorkQueue.Task(
taskFunction, data, fontId, opt_watchDogTime);
this.queue_.push(task);
if (this.queue_.length == 1) {
this.runNextTask();
}
return task;
};
/**
* Runs a task.
*/
tachyfont.WorkQueue.prototype.runNextTask = function() {
if (this.queue_.length < 1) {
return;
}
var task = this.queue_[0];
task.run().thenAlways(
/** @this {tachyfont.WorkQueue} */
function() {
this.queue_.shift();
this.runNextTask();
},
this);
};
/**
* Gets the queue length.
* @return {number}
*/
tachyfont.WorkQueue.prototype.getLength = function() {
return this.queue_.length;
};
/**
* Enum for error values.
* @enum {string}
*/
// LINT.IfChange
tachyfont.WorkQueue.Error = {
FILE_ID: 'EWQ',
WATCH_DOG_TIMER: '01',
END: '00'
};
// LINT.ThenChange(//depot/google3/\
// java/com/google/i18n/tachyfont/boq/gen204/error-reports.properties)
/**
* The error reporter for this file.
* @param {string} errNum The error number;
* @param {string} errId Identifies the error.
* @param {*} errInfo The error object;
*/
tachyfont.WorkQueue.reportError = function(errNum, errId, errInfo) {
tachyfont.Reporter.reportError(
tachyfont.WorkQueue.Error.FILE_ID + errNum, errId, errInfo);
};
/**
* Gets the work queue name
* @return {string}
*/
tachyfont.WorkQueue.prototype.getName = function() {
return this.name_;
};
/**
* A class that holds a task.
* @param {function(?)} taskFunction The function to call.
* @param {*} data The data to pass to the function.
* @param {string} fontId An indentifer for error reporting.
* @param {number=} opt_watchDogTime Option watch dog time.
* @constructor @struct @final
*/
tachyfont.WorkQueue.Task = function(
taskFunction, data, fontId, opt_watchDogTime) {
var resolver;
/** @private {function(?)} */
this.function_ = taskFunction;
/** @private {*} */
this.data_ = data;
/** @private {string} */
this.fontId_ = fontId;
/** @private {!goog.Promise<?,?>} */
this.result_ = new goog.Promise(function(resolve, reject) { //
resolver = resolve;
});
/** @private {function(*=)} */
this.resolver_ = resolver;
/** @private {?number} */
this.timeoutId_ = null;
/** @private {number} */
this.watchDogTime_ =
opt_watchDogTime || tachyfont.WorkQueue.Task.WATCH_DOG_TIME;
};
/**
* The time in milliseconds to wait before reporting that a running task did not
* complete.
* @type {number}
*/
tachyfont.WorkQueue.Task.WATCH_DOG_TIME = 10 * 60 * 1000;
/**
* Gets the task result promise (may be unresolved).
* @return {!goog.Promise<?,?>}
*/
tachyfont.WorkQueue.Task.prototype.getResult = function() {
return this.result_;
};
/**
* Resolves the task result promise.
* @param {*} result The result of the function. May be any value including a
* resolved/rejected promise.
* @return {!goog.Promise<?,?>}
* @private
*/
tachyfont.WorkQueue.Task.prototype.resolve_ = function(result) {
this.resolver_(result);
return this.result_;
};
/**
* Runs the task.
* @return {*}
*/
tachyfont.WorkQueue.Task.prototype.run = function() {
this.startWatchDogTimer_();
var result;
try {
result = this.function_(this.data_);
} catch (e) {
result = goog.Promise.reject(e);
}
this.result_.thenAlways(function() { //
this.stopWatchDogTimer_();
}.bind(this));
return this.resolve_(result);
};
/**
* Starts the watch dog timer.
* @return {*}
* @private
*/
tachyfont.WorkQueue.Task.prototype.startWatchDogTimer_ = function() {
this.timeoutId_ = setTimeout(function() {
this.timeoutId_ = null;
tachyfont.WorkQueue.reportError(
tachyfont.WorkQueue.Error.WATCH_DOG_TIMER, this.fontId_, '');
}.bind(this), this.watchDogTime_);
};
/**
* Stops the watch dog timer.
* @private
*/
tachyfont.WorkQueue.Task.prototype.stopWatchDogTimer_ = function() {
if (this.timeoutId_) {
clearTimeout(this.timeoutId_);
}
this.timeoutId_ = null;
};
| googlefonts/TachyFont | run_time/src/gae_server/www/js/tachyfont/work_queue.js | JavaScript | apache-2.0 | 5,429 |
'use strict';
var debug = require('debug')('ali-oss:sts');
var crypto = require('crypto');
var querystring = require('querystring');
var copy = require('copy-to');
var AgentKeepalive = require('agentkeepalive');
var is = require('is-type-of');
var ms = require('humanize-ms');
var urllib = require('urllib');
var globalHttpAgent = new AgentKeepalive();
module.exports = STS;
function STS(options) {
if (!(this instanceof STS)) {
return new STS(options);
}
if (!options
|| !options.accessKeyId
|| !options.accessKeySecret) {
throw new Error('require accessKeyId, accessKeySecret');
}
this.options = {
endpoint: options.endpoint || 'https://sts.aliyuncs.com',
format: 'JSON',
apiVersion: '2015-04-01',
sigMethod: 'HMAC-SHA1',
sigVersion: '1.0',
timeout: '60s'
};
copy(options).to(this.options);
// support custom agent and urllib client
if (this.options.urllib) {
this.urllib = this.options.urllib;
} else {
this.urllib = urllib;
this.agent = this.options.agent || globalHttpAgent;
}
};
var proto = STS.prototype;
/**
* STS opertaions
*/
proto.assumeRole = function* assumeRole(role, policy, expiration, session, options) {
var opts = this.options;
var params = {
'Action': 'AssumeRole',
'RoleArn': role,
'RoleSessionName': session || 'app',
'DurationSeconds': expiration || 3600,
'Format': opts.format,
'Version': opts.apiVersion,
'AccessKeyId': opts.accessKeyId,
'SignatureMethod': opts.sigMethod,
'SignatureVersion': opts.sigVersion,
'SignatureNonce': Math.random(),
'Timestamp': new Date().toISOString()
};
if (policy) {
var policyStr;
if (is.string(policy)) {
try {
policyStr = JSON.stringify(JSON.parse(policy));
} catch (err) {
throw new Error('Policy string is not a valid JSON: ' + err.message);
}
} else {
policyStr = JSON.stringify(policy);
}
params.Policy = policyStr;
}
var signature = this._getSignature('POST', params, opts.accessKeySecret);
params.Signature = signature;
var reqUrl = opts.endpoint;
var reqParams = {
agent: this.agent,
timeout: ms(options && options.timeout || opts.timeout),
method: 'POST',
content: querystring.stringify(params),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
ctx: options && options.ctx,
};
var result = yield this.urllib.request(reqUrl, reqParams);
debug('response %s %s, got %s, headers: %j',
reqParams.method, reqUrl, result.status, result.headers);
if (Math.floor(result.status / 100) !== 2) {
var err = yield this._requestError(result);
err.params = reqParams;
throw err;
}
result.data = JSON.parse(result.data);
return {
res: result.res,
credentials: result.data.Credentials
};
};
proto._requestError = function* _requestError(result) {
var err = new Error();
err.status = result.status;
try {
var resp = yield JSON.parse(result.data) || {};
err.code = resp.Code;
err.message = resp.Code + ': ' + resp.Message;
err.requestId = resp.RequestId;
} catch (e) {
err.message = 'UnknownError: ' + String(result.data);
}
return err;
};
proto._getSignature = function _getSignature(method, params, key) {
var that = this;
var canoQuery = Object.keys(params).sort().map(function (key) {
return that._escape(key) + '=' + that._escape(params[key])
}).join('&');
var stringToSign =
method.toUpperCase() +
'&' + this._escape('/') +
'&' + this._escape(canoQuery);
debug('string to sign: %s', stringToSign);
var signature = crypto.createHmac('sha1', key + '&');
signature = signature.update(stringToSign).digest('base64');
debug('signature: %s', signature);
return signature;
};
/**
* Since `encodeURIComponent` doesn't encode '*', which causes
* 'SignatureDoesNotMatch'. We need do it ourselves.
*/
proto._escape = function _escape(str) {
return encodeURIComponent(str).replace(/\*/g, '%2A');
};
| WebDeltaSync/WebR2sync_plus | node_modules/ali-oss/lib/sts.js | JavaScript | apache-2.0 | 4,037 |
// Copyright 2014 Samsung Electronics Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
assert(Math.atan2(+0, -Infinity) === Math.PI);
| tilmannOSG/jerryscript | tests/jerry-test-suite/15/15.08/15.08.02/15.08.02.05/15.08.02.05-010.js | JavaScript | apache-2.0 | 653 |
/// Copyright (c) 2009 Microsoft Corporation
///
/// Redistribution and use in source and binary forms, with or without modification, are permitted provided
/// that the following conditions are met:
/// * Redistributions of source code must retain the above copyright notice, this list of conditions and
/// the following disclaimer.
/// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
/// the following disclaimer in the documentation and/or other materials provided with the distribution.
/// * Neither the name of Microsoft nor the names of its contributors may be used to
/// endorse or promote products derived from this software without specific prior written permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
/// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
/// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
/// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
/// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
/// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
/// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
ES5Harness.registerTest({
id: "15.10.4.1-2",
path: "TestCases/chapter15/15.10/15.10.4/15.10.4.1-2.js",
description: "RegExp - the thrown error is SyntaxError instead of RegExpError when the characters of 'P' do not have the syntactic form Pattern",
test: function testcase() {
try {
var regExpObj = new RegExp('\\');
return false;
} catch (e) {
return e instanceof SyntaxError;
}
},
precondition: function prereq() {
return true;
}
});
| hnafar/IronJS | Src/Tests/ietestcenter/chapter15/15.10/15.10.4/15.10.4.1-2.js | JavaScript | apache-2.0 | 2,097 |
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails oncall+relay
*/
'use strict';
require('configureForRelayOSS');
const Relay = require('Relay');
const RelayTestUtils = require('RelayTestUtils');
const generateRQLFieldAlias = require('generateRQLFieldAlias');
const transformRelayQueryPayload = require('transformRelayQueryPayload');
describe('transformClientPayload()', () => {
var {getNode} = RelayTestUtils;
it('transforms singular root payloads', () => {
var query = getNode(Relay.QL`
query {
node(id: "123") {
friends(first:"1") {
count,
edges {
node {
id,
... on User {
profilePicture(size: "32") {
uri,
},
},
},
},
},
}
}
`);
var payload = {
node: {
id: '123',
friends: {
count: 1,
edges: [
{
cursor: 'friend:cursor',
node: {
id: 'client:1',
profilePicture: {
uri: 'friend.jpg',
},
},
},
],
},
},
};
expect(transformRelayQueryPayload(query, payload)).toEqual({
node: {
__typename: undefined,
id: '123',
[generateRQLFieldAlias('friends.first(1)')]: {
count: 1,
edges: [
{
cursor: 'friend:cursor',
node: {
id: 'client:1',
[generateRQLFieldAlias('profilePicture.size(32)')]: {
uri: 'friend.jpg',
},
},
},
],
pageInfo: undefined,
},
},
});
});
it('transforms plural root payloads of arrays', () => {
var query = getNode(Relay.QL`
query {
nodes(ids: ["123", "456"]) {
... on User {
profilePicture(size: "32") {
uri,
},
},
},
}
`);
var payload = {
123: {
id: '123',
profilePicture: {
uri: '123.jpg',
},
},
456: {
id: '456',
profilePicture: {
uri: '456.jpg',
},
},
};
expect(transformRelayQueryPayload(query, payload)).toEqual({
123: {
__typename: undefined,
id: '123',
[generateRQLFieldAlias('profilePicture.size(32)')]: {
uri: '123.jpg',
},
},
456: {
__typename: undefined,
id: '456',
[generateRQLFieldAlias('profilePicture.size(32)')]: {
uri: '456.jpg',
},
},
});
});
it('transforms plural root payloads of objects (OSS)', () => {
var query = getNode(Relay.QL`
query {
nodes(ids: ["123", "456"]) {
... on User {
profilePicture(size: "32") {
uri,
},
},
},
}
`);
var payload = [
{
id: '123',
profilePicture: {
uri: '123.jpg',
},
},
{
id: '456',
profilePicture: {
uri: '456.jpg',
},
},
];
expect(transformRelayQueryPayload(query, payload)).toEqual([
{
__typename: undefined,
id: '123',
[generateRQLFieldAlias('profilePicture.size(32)')]: {
uri: '123.jpg',
},
},
{
__typename: undefined,
id: '456',
[generateRQLFieldAlias('profilePicture.size(32)')]: {
uri: '456.jpg',
},
},
]);
});
it('transforms plural root payloads of objects (FB)', () => {
var query = getNode(Relay.QL`
query {
nodes(ids: ["123", "456"]) {
... on User {
profilePicture(size: "32") {
uri,
},
},
},
}
`);
var payload = {
nodes: [
{
id: '123',
profilePicture: {
uri: '123.jpg',
},
},
{
id: '456',
profilePicture: {
uri: '456.jpg',
},
},
],
};
expect(transformRelayQueryPayload(query, payload)).toEqual({
nodes: [
{
__typename: undefined,
id: '123',
[generateRQLFieldAlias('profilePicture.size(32)')]: {
uri: '123.jpg',
},
},
{
__typename: undefined,
id: '456',
[generateRQLFieldAlias('profilePicture.size(32)')]: {
uri: '456.jpg',
},
},
],
});
});
});
| Aweary/relay | src/tools/__tests__/transformRelayQueryPayload-test.js | JavaScript | bsd-3-clause | 4,969 |
import _forEachInstanceProperty from "@babel/runtime-corejs3/core-js/instance/for-each";
import _Object$getOwnPropertyDescriptor from "@babel/runtime-corejs3/core-js/object/get-own-property-descriptor";
import _filterInstanceProperty from "@babel/runtime-corejs3/core-js/instance/filter";
import _concatInstanceProperty from "@babel/runtime-corejs3/core-js/instance/concat";
import _Object$getOwnPropertySymbols from "@babel/runtime-corejs3/core-js/object/get-own-property-symbols";
import _Object$keys from "@babel/runtime-corejs3/core-js/object/keys";
import defineProperty from "@babel/runtime-corejs3/helpers/esm/defineProperty";
export default function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? Object(arguments[i]) : {};
var ownKeys = _Object$keys(source);
if (typeof _Object$getOwnPropertySymbols === 'function') {
var _context;
ownKeys = _concatInstanceProperty(ownKeys).call(ownKeys, _filterInstanceProperty(_context = _Object$getOwnPropertySymbols(source)).call(_context, function (sym) {
return _Object$getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
_forEachInstanceProperty(ownKeys).call(ownKeys, function (key) {
defineProperty(target, key, source[key]);
});
}
return target;
} | ChromeDevTools/devtools-frontend | node_modules/@babel/runtime-corejs3/helpers/esm/objectSpread.js | JavaScript | bsd-3-clause | 1,330 |
// d. ii. If k + 2 is greater than or equal to strLen, throw a URIError exception.
decodeURI('%1');
| daejunpark/jsaf | tests/bug_detector_tests/urierror1.js | JavaScript | bsd-3-clause | 100 |
/*
* Copyright (c) 2008-present The Open Source Geospatial Foundation
*
* Published under the BSD license.
* See https://github.com/geoext/geoext2/blob/master/license.txt for the full
* text of the license.
*/
/** api: example[layeropacityslider]
* Layer Opacity Slider
* --------------------
* Use a slider to control layer opacity.
*/
var panel1, panel2, wms, slider;
Ext.require([
'Ext.container.Viewport',
'Ext.layout.container.Border',
'GeoExt.panel.Map',
'GeoExt.slider.LayerOpacity',
'GeoExt.slider.Tip'
]);
Ext.application({
name: 'LayerOpacitySlider GeoExt2',
launch: function() {
wms = new OpenLayers.Layer.WMS(
"Global Imagery",
"http://maps.opengeo.org/geowebcache/service/wms",
{layers: "bluemarble"}
);
// create a map panel with an embedded slider
panel1 = Ext.create('GeoExt.panel.Map', {
title: "Map 1",
renderTo: "map1-container",
height: 300,
width: 400,
map: {
controls: [new OpenLayers.Control.Navigation()]
},
layers: [wms],
extent: [-5, 35, 15, 55],
items: [{
xtype: "gx_opacityslider",
layer: wms,
vertical: true,
height: 120,
x: 10,
y: 10,
plugins: Ext.create("GeoExt.slider.Tip", {
getText: function(thumb) {
return Ext.String.format('Opacity: {0}%', thumb.value);
}
})
}]
});
// create a separate slider bound to the map but displayed elsewhere
slider = Ext.create('GeoExt.slider.LayerOpacity', {
layer: wms,
aggressive: true,
width: 200,
isFormField: true,
inverse: true,
fieldLabel: "opacity",
renderTo: "slider",
plugins: Ext.create("GeoExt.slider.Tip", {
getText: function(thumb) {
return Ext.String.format('Transparency: {0}%', thumb.value);
}
})
});
var clone = wms.clone();
var wms2 = new OpenLayers.Layer.WMS(
"OpenStreetMap WMS",
"http://ows.terrestris.de/osm/service?",
{layers: 'OSM-WMS'},
{
attribution: '© terrestris GmbH & Co. KG <br>' +
'Data © OpenStreetMap ' +
'<a href="http://www.openstreetmap.org/copyright/en"' +
'target="_blank">contributors<a>'
}
);
panel2 = Ext.create('GeoExt.panel.Map', {
title: "Map 2",
renderTo: "map2-container",
height: 300,
width: 400,
map: {
controls: [new OpenLayers.Control.Navigation()]
},
layers: [wms2, clone],
extent: [-5, 35, 15, 55],
items: [{
xtype: "gx_opacityslider",
layer: clone,
complementaryLayer: wms2,
changeVisibility: true,
aggressive: true,
vertical: true,
height: 120,
x: 10,
y: 10,
plugins: Ext.create("GeoExt.slider.Tip", {
getText: function(thumb) {
return Ext.String.format('{0}%', thumb.value);
}
})
}]
});
}
});
| chrismayer/geoext2 | examples/layeropacityslider/layeropacityslider.js | JavaScript | bsd-3-clause | 3,626 |
define([
"dojo/_base/declare",
"dojo/_base/sniff",
"dojo/dom-class",
"dojo/dom-construct",
"dojo/dom-style",
"dijit/_Contained",
"dijit/_Container",
"dijit/_WidgetBase",
"./IconMenuItem"
], function(declare, has, domClass, domConstruct, domStyle, Contained, Container, WidgetBase){
// module:
// dojox/mobile/IconMenu
return declare("dojox.mobile.IconMenu", [WidgetBase, Container, Contained], {
// summary:
// A pop-up menu.
// description:
// The dojox/mobile/IconMenu widget displays a pop-up menu just
// like iPhone's call options menu that is shown while you are on a
// call. Each menu item must be dojox/mobile/IconMenuItem.
// transition: String
// The default animated transition effect for child items.
transition: "slide",
// iconBase: String
// The default icon path for child items.
iconBase: "",
// iconPos: String
// The default icon position for child items.
iconPos: "",
// cols: Number
// The number of child items in a row.
cols: 3,
// tag: String
// A name of html tag to create as domNode.
tag: "ul",
/* internal properties */
selectOne: false,
// baseClass: String
// The name of the CSS class of this widget.
baseClass: "mblIconMenu",
// childItemClass: String
// The name of the CSS class of menu items.
childItemClass: "mblIconMenuItem",
// _createTerminator: [private] Boolean
_createTerminator: false,
buildRendering: function(){
this.domNode = this.containerNode = this.srcNodeRef || domConstruct.create(this.tag);
this.inherited(arguments);
if(this._createTerminator){
var t = this._terminator = domConstruct.create("br");
t.className = this.childItemClass + "Terminator";
this.domNode.appendChild(t);
}
},
startup: function(){
if(this._started){ return; }
this.refresh();
this.inherited(arguments);
},
refresh: function(){
var p = this.getParent();
if(p){
domClass.remove(p.domNode, "mblSimpleDialogDecoration");
}
var children = this.getChildren();
if(this.cols){
var nRows = Math.ceil(children.length / this.cols);
var w = Math.floor(100/this.cols);
var _w = 100 - w*this.cols;
var h = Math.floor(100 / nRows);
var _h = 100 - h*nRows;
if(has("ie")){
_w--;
_h--;
}
}
for(var i = 0; i < children.length; i++){
var item = children[i];
if(this.cols){
var first = ((i % this.cols) === 0); // first column
var last = (((i + 1) % this.cols) === 0); // last column
var rowIdx = Math.floor(i / this.cols);
domStyle.set(item.domNode, {
width: w + (last ? _w : 0) + "%",
height: h + ((rowIdx + 1 === nRows) ? _h : 0) + "%"
});
domClass.toggle(item.domNode, this.childItemClass + "FirstColumn", first);
domClass.toggle(item.domNode, this.childItemClass + "LastColumn", last);
domClass.toggle(item.domNode, this.childItemClass + "FirstRow", rowIdx === 0);
domClass.toggle(item.domNode, this.childItemClass + "LastRow", rowIdx + 1 === nRows);
}
};
},
addChild: function(widget, /*Number?*/insertIndex){
this.inherited(arguments);
this.refresh();
},
hide: function(){
var p = this.getParent();
if(p && p.hide){
p.hide();
}
}
});
});
| kitsonk/expo | src/dojox/mobile/IconMenu.js | JavaScript | bsd-3-clause | 3,265 |
//2
var __result1 = 2; // for SAFE
var __expect1 = 2; // for SAFE
| darkrsw/safe | tests/typing_tests/TAJS_micro/test2.js | JavaScript | bsd-3-clause | 68 |
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/** @const {number} */
const DEFAULT_BLACK_CURSOR_COLOR = 0;
/**
* @fileoverview
* 'settings-manage-a11y-page' is the subpage with the accessibility
* settings.
*/
import {afterNextRender, Polymer, html, flush, Templatizer, TemplateInstanceBase} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import '//resources/cr_elements/cr_icon_button/cr_icon_button.m.js';
import '//resources/cr_elements/cr_link_row/cr_link_row.js';
import '//resources/cr_elements/icons.m.js';
import '//resources/cr_elements/shared_vars_css.m.js';
import {WebUIListenerBehavior} from '//resources/js/web_ui_listener_behavior.m.js';
import {I18nBehavior} from '//resources/js/i18n_behavior.m.js';
import {loadTimeData} from '//resources/js/load_time_data.m.js';
import '../../controls/settings_slider.js';
import '../../controls/settings_toggle_button.js';
import {DeepLinkingBehavior} from '../deep_linking_behavior.m.js';
import {routes} from '../os_route.m.js';
import {Router, Route} from '../../router.js';
import {RouteObserverBehavior} from '../route_observer_behavior.js';
import '../../settings_shared_css.js';
import {BatteryStatus, DevicePageBrowserProxy, DevicePageBrowserProxyImpl, ExternalStorage, IdleBehavior, LidClosedBehavior, NoteAppInfo, NoteAppLockScreenSupport, PowerManagementSettings, PowerSource, getDisplayApi, StorageSpaceState} from '../device_page/device_page_browser_proxy.js';
import '//resources/cr_components/chromeos/localized_link/localized_link.js';
import {RouteOriginBehaviorImpl, RouteOriginBehavior} from '../route_origin_behavior.m.js';
import {ManageA11yPageBrowserProxyImpl, ManageA11yPageBrowserProxy} from './manage_a11y_page_browser_proxy.js';
Polymer({
_template: html`{__html_template__}`,
is: 'settings-manage-a11y-page',
behaviors: [
DeepLinkingBehavior,
I18nBehavior,
RouteObserverBehavior,
RouteOriginBehavior,
WebUIListenerBehavior,
],
properties: {
/**
* Preferences state.
*/
prefs: {
type: Object,
notify: true,
},
/**
* Enum values for the 'settings.a11y.screen_magnifier_mouse_following_mode'
* preference. These values map to
* AccessibilityController::MagnifierMouseFollowingMode, and are written to
* prefs and metrics, so order should not be changed.
* @private {!Object<string, number>}
*/
screenMagnifierMouseFollowingModePrefValues_: {
readOnly: true,
type: Object,
value: {
CONTINUOUS: 0,
CENTERED: 1,
EDGE: 2,
},
},
screenMagnifierZoomOptions_: {
readOnly: true,
type: Array,
value() {
// These values correspond to the i18n values in settings_strings.grdp.
// If these values get changed then those strings need to be changed as
// well.
return [
{value: 2, name: loadTimeData.getString('screenMagnifierZoom2x')},
{value: 4, name: loadTimeData.getString('screenMagnifierZoom4x')},
{value: 6, name: loadTimeData.getString('screenMagnifierZoom6x')},
{value: 8, name: loadTimeData.getString('screenMagnifierZoom8x')},
{value: 10, name: loadTimeData.getString('screenMagnifierZoom10x')},
{value: 12, name: loadTimeData.getString('screenMagnifierZoom12x')},
{value: 14, name: loadTimeData.getString('screenMagnifierZoom14x')},
{value: 16, name: loadTimeData.getString('screenMagnifierZoom16x')},
{value: 18, name: loadTimeData.getString('screenMagnifierZoom18x')},
{value: 20, name: loadTimeData.getString('screenMagnifierZoom20x')},
];
},
},
autoClickDelayOptions_: {
readOnly: true,
type: Array,
value() {
// These values correspond to the i18n values in settings_strings.grdp.
// If these values get changed then those strings need to be changed as
// well.
return [
{
value: 600,
name: loadTimeData.getString('delayBeforeClickExtremelyShort')
},
{
value: 800,
name: loadTimeData.getString('delayBeforeClickVeryShort')
},
{value: 1000, name: loadTimeData.getString('delayBeforeClickShort')},
{value: 2000, name: loadTimeData.getString('delayBeforeClickLong')},
{
value: 4000,
name: loadTimeData.getString('delayBeforeClickVeryLong')
},
];
},
},
autoClickMovementThresholdOptions_: {
readOnly: true,
type: Array,
value() {
return [
{
value: 5,
name: loadTimeData.getString('autoclickMovementThresholdExtraSmall')
},
{
value: 10,
name: loadTimeData.getString('autoclickMovementThresholdSmall')
},
{
value: 20,
name: loadTimeData.getString('autoclickMovementThresholdDefault')
},
{
value: 30,
name: loadTimeData.getString('autoclickMovementThresholdLarge')
},
{
value: 40,
name: loadTimeData.getString('autoclickMovementThresholdExtraLarge')
},
];
},
},
/** @private {!Array<{name: string, value: number}>} */
cursorColorOptions_: {
readOnly: true,
type: Array,
value() {
return [
{
value: DEFAULT_BLACK_CURSOR_COLOR,
name: loadTimeData.getString('cursorColorBlack'),
},
{
value: 0xd93025, // Red 600
name: loadTimeData.getString('cursorColorRed'),
},
{
value: 0xf29900, // Yellow 700
name: loadTimeData.getString('cursorColorYellow'),
},
{
value: 0x1e8e3e, // Green 600
name: loadTimeData.getString('cursorColorGreen'),
},
{
value: 0x03b6be, // Cyan 600
name: loadTimeData.getString('cursorColorCyan'),
},
{
value: 0x1a73e8, // Blue 600
name: loadTimeData.getString('cursorColorBlue'),
},
{
value: 0xc61ad9, // Magenta 600
name: loadTimeData.getString('cursorColorMagenta'),
},
{
value: 0xf50057, // Pink A400
name: loadTimeData.getString('cursorColorPink'),
},
];
},
},
/** @private */
isMagnifierContinuousMouseFollowingModeSettingEnabled_: {
type: Boolean,
value() {
return loadTimeData.getBoolean(
'isMagnifierContinuousMouseFollowingModeSettingEnabled');
},
},
/**
* Whether the user is in kiosk mode.
* @private
*/
isKioskModeActive_: {
type: Boolean,
value() {
return loadTimeData.getBoolean('isKioskModeActive');
}
},
/**
* Whether a setting for enabling shelf navigation buttons in tablet mode
* should be displayed in the accessibility settings.
* @private
*/
showShelfNavigationButtonsSettings_: {
type: Boolean,
computed:
'computeShowShelfNavigationButtonsSettings_(isKioskModeActive_)',
},
/** @private */
isGuest_: {
type: Boolean,
value() {
return loadTimeData.getBoolean('isGuest');
}
},
/** @private */
screenMagnifierHintLabel_: {
type: String,
value() {
return this.i18n(
'screenMagnifierHintLabel',
this.i18n('screenMagnifierHintSearchKey'));
}
},
/** @private */
dictationSubtitle_: {
type: String,
value() {
return loadTimeData.getString('dictationDescription');
}
},
/** @private */
dictationLocaleSubtitleOverride_: {
type: String,
value: '',
},
/** @private */
useDictationLocaleSubtitleOverride_: {
type: Boolean,
value: false,
},
/** @private */
dictationLocaleMenuSubtitle_: {
type: String,
computed: 'computeDictationLocaleSubtitle_(' +
'dictationLocaleOptions_, ' +
'prefs.settings.a11y.dictation_locale.value, ' +
'dictationLocaleSubtitleOverride_)',
},
/** @private */
areDictationLocalePrefsAllowed_: {
type: Boolean,
readOnly: true,
value() {
return loadTimeData.getBoolean('areDictationLocalePrefsAllowed');
}
},
/** @private */
dictationLocaleOptions_: {
type: Array,
value() {
return [];
}
},
/** @private */
dictationLocalesList_: {
type: Array,
value() {
return [];
}
},
/** @private */
showDictationLocaleMenu_: {
type: Boolean,
value: false,
},
/**
* |hasKeyboard_|, |hasMouse_|, |hasPointingStick_|, and |hasTouchpad_|
* start undefined so observers don't trigger until they have been
* populated.
* @private
*/
hasKeyboard_: Boolean,
/** @private */
hasMouse_: Boolean,
/** @private */
hasPointingStick_: Boolean,
/** @private */
hasTouchpad_: Boolean,
/**
* Boolean indicating whether shelf navigation buttons should implicitly be
* enabled in tablet mode - the navigation buttons are implicitly enabled
* when spoken feedback, automatic clicks, or switch access are enabled.
* The buttons can also be explicitly enabled by a designated a11y setting.
* @private
*/
shelfNavigationButtonsImplicitlyEnabled_: {
type: Boolean,
computed: 'computeShelfNavigationButtonsImplicitlyEnabled_(' +
'prefs.settings.accessibility.value,' +
'prefs.settings.a11y.autoclick.value,' +
'prefs.settings.a11y.switch_access.enabled.value)',
},
/**
* The effective pref value that indicates whether shelf navigation buttons
* are enabled in tablet mode.
* @type {chrome.settingsPrivate.PrefObject}
* @private
*/
shelfNavigationButtonsPref_: {
type: Object,
computed: 'getShelfNavigationButtonsEnabledPref_(' +
'shelfNavigationButtonsImplicitlyEnabled_,' +
'prefs.settings.a11y.tablet_mode_shelf_nav_buttons_enabled)',
},
/**
* Used by DeepLinkingBehavior to focus this page's deep links.
* @type {!Set<!chromeos.settings.mojom.Setting>}
*/
supportedSettingIds: {
type: Object,
value: () => new Set([
chromeos.settings.mojom.Setting.kChromeVox,
chromeos.settings.mojom.Setting.kSelectToSpeak,
chromeos.settings.mojom.Setting.kHighContrastMode,
chromeos.settings.mojom.Setting.kFullscreenMagnifier,
chromeos.settings.mojom.Setting.kFullscreenMagnifierMouseFollowingMode,
chromeos.settings.mojom.Setting.kFullscreenMagnifierFocusFollowing,
chromeos.settings.mojom.Setting.kDockedMagnifier,
chromeos.settings.mojom.Setting.kStickyKeys,
chromeos.settings.mojom.Setting.kOnScreenKeyboard,
chromeos.settings.mojom.Setting.kDictation,
chromeos.settings.mojom.Setting.kHighlightKeyboardFocus,
chromeos.settings.mojom.Setting.kHighlightTextCaret,
chromeos.settings.mojom.Setting.kAutoClickWhenCursorStops,
chromeos.settings.mojom.Setting.kLargeCursor,
chromeos.settings.mojom.Setting.kHighlightCursorWhileMoving,
chromeos.settings.mojom.Setting.kTabletNavigationButtons,
chromeos.settings.mojom.Setting.kMonoAudio,
chromeos.settings.mojom.Setting.kStartupSound,
chromeos.settings.mojom.Setting.kEnableSwitchAccess,
chromeos.settings.mojom.Setting.kEnableCursorColor,
]),
},
},
observers: [
'pointersChanged_(hasMouse_, hasPointingStick_, hasTouchpad_, ' +
'isKioskModeActive_)',
],
/** RouteOriginBehavior override */
route_: routes.MANAGE_ACCESSIBILITY,
/** @private {?ManageA11yPageBrowserProxy} */
manageBrowserProxy_: null,
/** @private {?DevicePageBrowserProxy} */
deviceBrowserProxy_: null,
/** @override */
created() {
this.manageBrowserProxy_ = ManageA11yPageBrowserProxyImpl.getInstance();
this.deviceBrowserProxy_ = DevicePageBrowserProxyImpl.getInstance();
},
/** @override */
attached() {
this.addWebUIListener(
'has-mouse-changed', (exists) => this.set('hasMouse_', exists));
this.addWebUIListener(
'has-pointing-stick-changed',
(exists) => this.set('hasPointingStick_', exists));
this.addWebUIListener(
'has-touchpad-changed', (exists) => this.set('hasTouchpad_', exists));
this.deviceBrowserProxy_.initializePointers();
this.addWebUIListener(
'has-hardware-keyboard',
(hasKeyboard) => this.set('hasKeyboard_', hasKeyboard));
this.deviceBrowserProxy_.initializeKeyboardWatcher();
},
/** @override */
ready() {
this.addWebUIListener(
'initial-data-ready',
(startup_sound_enabled) =>
this.onManageAllyPageReady_(startup_sound_enabled));
this.addWebUIListener(
'dictation-locale-menu-subtitle-changed',
(result) => this.onDictationLocaleMenuSubtitleChanged_(result));
this.addWebUIListener(
'dictation-locales-set',
(locales) => this.onDictationLocalesSet_(locales));
this.manageBrowserProxy_.manageA11yPageReady();
const r = routes;
this.addFocusConfig_(r.MANAGE_TTS_SETTINGS, '#ttsSubpageButton');
this.addFocusConfig_(r.MANAGE_CAPTION_SETTINGS, '#captionsSubpageButton');
this.addFocusConfig_(
r.MANAGE_SWITCH_ACCESS_SETTINGS, '#switchAccessSubpageButton');
this.addFocusConfig_(r.DISPLAY, '#displaySubpageButton');
this.addFocusConfig_(r.KEYBOARD, '#keyboardSubpageButton');
this.addFocusConfig_(r.POINTERS, '#pointerSubpageButton');
},
/**
* @param {!Route} route
* @param {!Route} oldRoute
*/
currentRouteChanged(route, oldRoute) {
// Does not apply to this page.
if (route !== routes.MANAGE_ACCESSIBILITY) {
return;
}
this.attemptDeepLink();
},
/**
* @param {boolean} hasMouse
* @param {boolean} hasPointingStick
* @param {boolean} hasTouchpad
* @private
*/
pointersChanged_(hasMouse, hasTouchpad, hasPointingStick, isKioskModeActive) {
this.$.pointerSubpageButton.hidden =
(!hasMouse && !hasPointingStick && !hasTouchpad) || isKioskModeActive;
},
/**
* Updates the Select-to-Speak description text based on:
* 1. Whether Select-to-Speak is enabled.
* 2. If it is enabled, whether a physical keyboard is present.
* @param {boolean} enabled
* @param {boolean} hasKeyboard
* @param {string} disabledString String to show when Select-to-Speak is
* disabled.
* @param {string} keyboardString String to show when there is a physical
* keyboard
* @param {string} noKeyboardString String to show when there is no keyboard
* @private
*/
getSelectToSpeakDescription_(
enabled, hasKeyboard, disabledString, keyboardString, noKeyboardString) {
return !enabled ? disabledString :
hasKeyboard ? keyboardString : noKeyboardString;
},
/**
* @param {!CustomEvent<boolean>} e
* @private
*/
toggleStartupSoundEnabled_(e) {
this.manageBrowserProxy_.setStartupSoundEnabled(e.detail);
},
/** @private */
onManageTtsSettingsTap_() {
Router.getInstance().navigateTo(routes.MANAGE_TTS_SETTINGS);
},
/** @private */
onChromeVoxSettingsTap_() {
this.manageBrowserProxy_.showChromeVoxSettings();
},
/** @private */
onChromeVoxTutorialTap_() {
this.manageBrowserProxy_.showChromeVoxTutorial();
},
/** @private */
onCaptionsClick_() {
Router.getInstance().navigateTo(routes.MANAGE_CAPTION_SETTINGS);
},
/** @private */
onSelectToSpeakSettingsTap_() {
this.manageBrowserProxy_.showSelectToSpeakSettings();
},
/** @private */
onSwitchAccessSettingsTap_() {
Router.getInstance().navigateTo(routes.MANAGE_SWITCH_ACCESS_SETTINGS);
},
/** @private */
onDisplayTap_() {
Router.getInstance().navigateTo(
routes.DISPLAY,
/* dynamicParams */ null, /* removeSearch */ true);
},
/** @private */
onAppearanceTap_() {
// Open browser appearance section in a new browser tab.
window.open('chrome://settings/appearance');
},
/** @private */
onKeyboardTap_() {
Router.getInstance().navigateTo(
routes.KEYBOARD,
/* dynamicParams */ null, /* removeSearch */ true);
},
/**
* @param {!Event} event
* @private
*/
onA11yCaretBrowsingChange_(event) {
if (event.target.checked) {
chrome.metricsPrivate.recordUserAction(
'Accessibility.CaretBrowsing.EnableWithSettings');
} else {
chrome.metricsPrivate.recordUserAction(
'Accessibility.CaretBrowsing.DisableWithSettings');
}
},
/**
* @return {boolean}
* @private
*/
computeShowShelfNavigationButtonsSettings_() {
return !this.isKioskModeActive_ &&
loadTimeData.getBoolean('showTabletModeShelfNavigationButtonsSettings');
},
/**
* @return {boolean} Whether shelf navigation buttons should implicitly be
* enabled in tablet mode (due to accessibility settings different than
* shelf_navigation_buttons_enabled_in_tablet_mode).
* @private
*/
computeShelfNavigationButtonsImplicitlyEnabled_() {
/**
* Gets the bool pref value for the provided pref key.
* @param {string} key
* @return {boolean}
*/
const getBoolPrefValue = (key) => {
const pref = /** @type {chrome.settingsPrivate.PrefObject} */ (
this.get(key, this.prefs));
return pref && !!pref.value;
};
return getBoolPrefValue('settings.accessibility') ||
getBoolPrefValue('settings.a11y.autoclick') ||
getBoolPrefValue('settings.a11y.switch_access.enabled');
},
/**
* Calculates the effective value for "shelf navigation buttons enabled in
* tablet mode" setting - if the setting is implicitly enabled (by other a11y
* settings), this will return a stub pref value.
* @private
* @return {chrome.settingsPrivate.PrefObject}
*/
getShelfNavigationButtonsEnabledPref_() {
if (this.shelfNavigationButtonsImplicitlyEnabled_) {
return /** @type {!chrome.settingsPrivate.PrefObject}*/ ({
value: true,
type: chrome.settingsPrivate.PrefType.BOOLEAN,
key: ''
});
}
return /** @type {chrome.settingsPrivate.PrefObject} */ (this.get(
'settings.a11y.tablet_mode_shelf_nav_buttons_enabled', this.prefs));
},
/** @private */
onShelfNavigationButtonsLearnMoreClicked_() {
chrome.metricsPrivate.recordUserAction(
'Settings_A11y_ShelfNavigationButtonsLearnMoreClicked');
},
/**
* Handles the <code>tablet_mode_shelf_nav_buttons_enabled</code> setting's
* toggle changes. It updates the backing pref value, unless the setting is
* implicitly enabled.
* @private
*/
updateShelfNavigationButtonsEnabledPref_() {
if (this.shelfNavigationButtonsImplicitlyEnabled_) {
return;
}
const enabled = this.$$('#shelfNavigationButtonsEnabledControl').checked;
this.set(
'prefs.settings.a11y.tablet_mode_shelf_nav_buttons_enabled.value',
enabled);
this.manageBrowserProxy_.recordSelectedShowShelfNavigationButtonValue(
enabled);
},
/** @private */
onA11yCursorColorChange_() {
// Custom cursor color is enabled when the color is not set to black.
const a11yCursorColorOn =
this.get('prefs.settings.a11y.cursor_color.value') !==
DEFAULT_BLACK_CURSOR_COLOR;
this.set(
'prefs.settings.a11y.cursor_color_enabled.value', a11yCursorColorOn);
},
/** @private */
onMouseTap_() {
Router.getInstance().navigateTo(
routes.POINTERS,
/* dynamicParams */ null, /* removeSearch */ true);
},
/**
* Handles updating the visibility of the shelf navigation buttons setting
* and updating whether startupSoundEnabled is checked.
* @param {boolean} startup_sound_enabled Whether startup sound is enabled.
* @private
*/
onManageAllyPageReady_(startup_sound_enabled) {
this.$.startupSoundEnabled.checked = startup_sound_enabled;
},
/**
* Whether additional features link should be shown.
* @param {boolean} isKiosk
* @param {boolean} isGuest
* @return {boolean}
* @private
*/
shouldShowAdditionalFeaturesLink_(isKiosk, isGuest) {
return !isKiosk && !isGuest;
},
/**
* @param {string} subtitle
* @private
*/
onDictationLocaleMenuSubtitleChanged_(subtitle) {
this.useDictationLocaleSubtitleOverride_ = true;
this.dictationLocaleSubtitleOverride_ = subtitle;
},
/**
* Saves a list of locales and updates the UI to reflect the list.
* @param {!Array<!Array<string>>} locales
* @private
*/
onDictationLocalesSet_(locales) {
this.dictationLocalesList_ = locales;
this.onDictationLocalesChanged_();
},
/**
* Converts an array of locales and their human-readable equivalents to
* an array of menu options.
* TODO(crbug.com/1195916): Use 'offline' to indicate to the user which
* locales work offline with an icon in the select options.
* @private
*/
onDictationLocalesChanged_() {
const currentLocale =
this.get('prefs.settings.a11y.dictation_locale.value');
this.dictationLocaleOptions_ =
this.dictationLocalesList_.map((localeInfo) => {
return {
name: localeInfo.name,
value: localeInfo.value,
worksOffline: localeInfo.worksOffline,
installed: localeInfo.installed,
recommended:
localeInfo.recommended || localeInfo.value === currentLocale,
};
});
},
/**
* Calculates the Dictation locale subtitle based on the current
* locale from prefs and the offline availability of that locale.
* @return {string}
* @private
*/
computeDictationLocaleSubtitle_() {
if (this.useDictationLocaleSubtitleOverride_) {
// Only use the subtitle override once, since we still want the subtitle
// to repsond to changes to the dictation locale.
this.useDictationLocaleSubtitleOverride_ = false;
return this.dictationLocaleSubtitleOverride_;
}
const currentLocale =
this.get('prefs.settings.a11y.dictation_locale.value');
const locale = this.dictationLocaleOptions_.find(
(element) => element.value === currentLocale);
if (!locale) {
return '';
}
if (!locale.worksOffline) {
// If a locale is not supported offline, then use the network subtitle.
return this.i18n('dictationLocaleSubLabelNetwork', locale.name);
}
if (!locale.installed) {
// If a locale is supported offline, but isn't installed, then use the
// temporary network subtitle.
return this.i18n(
'dictationLocaleSubLabelNetworkTemporarily', locale.name);
}
// If we get here, we know a locale is both supported offline and installed.
return this.i18n('dictationLocaleSubLabelOffline', locale.name);
},
/** @private */
onChangeDictationLocaleButtonClicked_() {
if (this.areDictationLocalePrefsAllowed_) {
this.showDictationLocaleMenu_ = true;
}
},
/** @private */
onChangeDictationLocalesDialogClosed_() {
this.showDictationLocaleMenu_ = false;
},
});
| ric2b/Vivaldi-browser | chromium/chrome/browser/resources/settings/chromeos/os_a11y_page/manage_a11y_page.js | JavaScript | bsd-3-clause | 23,701 |
var Checker = require('../../lib/checker');
var assert = require('assert');
var operators = require('../../lib/utils').unaryOperators;
describe('rules/require-space-after-prefix-unary-operators', function() {
var checker;
beforeEach(function() {
checker = new Checker();
checker.registerDefaultRules();
});
operators.forEach(function(operator) {
var sticked = 'var test;' + operator + 'test';
var stickedWithParenthesis = 'var test;' + operator + '(test)';
var notSticked = 'var test;' + operator + ' test';
var notStickedWithParenthesis = 'var test;' + operator + ' (test)';
[[operator], true].forEach(function(value) {
it('should report sticky operator for ' + sticked + ' with ' + value + ' option',
function() {
checker.configure({ requireSpaceAfterPrefixUnaryOperators: value });
assert(checker.checkString(sticked).getErrorCount() === 1);
}
);
it('should not report sticky operator for ' + notSticked + ' with ' + value + ' option',
function() {
checker.configure({ requireSpaceAfterPrefixUnaryOperators: value });
assert(checker.checkString(notSticked).isEmpty());
}
);
it('should report sticky operator for ' + stickedWithParenthesis + ' with ' + value + ' option',
function() {
checker.configure({ requireSpaceAfterPrefixUnaryOperators: value });
assert(checker.checkString(stickedWithParenthesis).getErrorCount() === 1);
}
);
it('should not report sticky operator for ' + notStickedWithParenthesis + ' with ' + value + ' option',
function() {
checker.configure({ requireSpaceAfterPrefixUnaryOperators: value });
assert(checker.checkString(notStickedWithParenthesis).isEmpty());
}
);
});
});
it('should report sticky operator if operand in parentheses', function() {
checker.configure({ requireSpaceAfterPrefixUnaryOperators: ['-', '~', '!', '++'] });
assert(checker.checkString('var x = ~(0); ++(((x))); -( x ); !(++( x ));').getErrorCount() === 5);
});
it('should not report consecutive operators (#405)', function() {
checker.configure({ requireSpaceAfterPrefixUnaryOperators: ['!'] });
assert(checker.checkString('!~test;').isEmpty());
assert(checker.checkString('!~test;').isEmpty());
assert(checker.checkString('!++test;').isEmpty());
});
});
| appium/node-jscs | test/rules/require-space-after-prefix-unary-operators.js | JavaScript | mit | 2,695 |
asynctest(
'browser.tinymce.ui.content.LinkTargetsTest',
[
'ephox.mcagar.api.LegacyUnit',
'ephox.agar.api.Pipeline',
'tinymce.ui.content.LinkTargets',
'tinymce.core.util.Arr',
'global!document'
],
function (LegacyUnit, Pipeline, LinkTargets, Arr, document) {
var success = arguments[arguments.length - 2];
var failure = arguments[arguments.length - 1];
var suite = LegacyUnit.createSuite();
var createFromHtml = function (html) {
var elm = document.createElement('div');
elm.contentEditable = true;
elm.innerHTML = html;
return elm;
};
var targetsIn = function (html) {
return LinkTargets.find(createFromHtml(html));
};
var equalTargets = function (actualTargets, expectedTargets, message) {
var nonAttachedTargets = Arr.map(actualTargets, function (target) {
return {
level: target.level,
title: target.title,
type: target.type,
url: target.url
};
});
LegacyUnit.deepEqual(nonAttachedTargets, expectedTargets, message);
};
suite.test('Non link targets', function () {
LegacyUnit.equal(targetsIn('a').length, 0, 'Text has no targets');
LegacyUnit.equal(targetsIn('<p>a</p>').length, 0, 'Paragraph has no targets');
LegacyUnit.equal(targetsIn('<a href="#1">a</a>').length, 0, 'Link has no targets');
});
suite.test('Anchor targets', function () {
equalTargets(targetsIn('<a id="a"></a>'), [{ level: 0, title: '#a', type: 'anchor', url: '#a' }], 'Anchor with id');
equalTargets(targetsIn('<a name="a"></a>'), [{ level: 0, title: '#a', type: 'anchor', url: '#a' }], 'Anchor with name');
equalTargets(targetsIn('<a name="a" contentEditable="false"></a>'), [], 'cE=false anchor');
equalTargets(targetsIn('<div contentEditable="false"><a name="a"></a></div>'), [], 'Anchor in cE=false');
equalTargets(targetsIn('<a name=""></a>'), [], 'Empty anchor name should not produce a target');
equalTargets(targetsIn('<a id=""></a>'), [], 'Empty anchor id should not produce a target');
});
suite.test('Header targets', function () {
equalTargets(targetsIn('<h1 id="a">a</h1>'), [{ level: 1, title: 'a', type: 'header', url: '#a' }], 'Header 1 with id');
equalTargets(targetsIn('<h2 id="a">a</h2>'), [{ level: 2, title: 'a', type: 'header', url: '#a' }], 'Header 2 with id');
equalTargets(targetsIn('<h3 id="a">a</h3>'), [{ level: 3, title: 'a', type: 'header', url: '#a' }], 'Header 3 with id');
equalTargets(targetsIn('<h4 id="a">a</h4>'), [{ level: 4, title: 'a', type: 'header', url: '#a' }], 'Header 4 with id');
equalTargets(targetsIn('<h5 id="a">a</h5>'), [{ level: 5, title: 'a', type: 'header', url: '#a' }], 'Header 5 with id');
equalTargets(targetsIn('<h6 id="a">a</h6>'), [{ level: 6, title: 'a', type: 'header', url: '#a' }], 'Header 6 with id');
equalTargets(targetsIn('<h1 id="a"></h1>'), [], 'Empty header should not produce a target');
equalTargets(targetsIn('<div contentEditable="false"><h1 id="a">a</h1></div>'), [], 'Header in cE=false');
equalTargets(targetsIn('<h1 id="a" contentEditable="false">a</h1>'), [], 'cE=false header');
});
suite.test('Mixed targets', function () {
equalTargets(
targetsIn('<h1 id="a">a</h1><a id="b"></a>'),
[
{ level: 1, title: 'a', type: 'header', url: '#a' },
{ level: 0, title: '#b', type: 'anchor', url: '#b' }
],
'Header 1 with id and anchor with id'
);
});
suite.test('Anchor attach', function () {
var elm = createFromHtml('<a id="a"></a>');
var targets = LinkTargets.find(elm);
targets[0].attach();
LegacyUnit.equal(elm.innerHTML, '<a id="a"></a>', 'Should remain the same as before attach');
});
suite.test('Header attach on header with id', function () {
var elm = createFromHtml('<h1 id="a">a</h1>');
var targets = LinkTargets.find(elm);
targets[0].attach();
LegacyUnit.equal(elm.innerHTML, '<h1 id="a">a</h1>', 'Should remain the same as before attach');
});
suite.test('Header attach on headers without ids', function () {
var elm = createFromHtml('<h1>a</h1><h2>b</h2>');
var targets = LinkTargets.find(elm);
targets[0].attach();
targets[1].attach();
var idA = elm.firstChild.id;
var idB = elm.lastChild.id;
var afterAttachHtml = elm.innerHTML;
LegacyUnit.equal(afterAttachHtml, '<h1 id="' + idA + '">a</h1><h2 id="' + idB + '">b</h2>', 'Should have unique id:s');
LegacyUnit.equal(idA === idB, false, 'Should not be equal id:s');
targets[0].attach();
targets[1].attach();
LegacyUnit.equal(elm.innerHTML, afterAttachHtml, 'Should be the same id:s regardless of how many times you attach');
});
Pipeline.async({}, suite.toSteps({}), function () {
success();
}, failure);
}
);
| pvskand/addictionRemoval | tinymce/src/ui/src/test/js/browser/content/LinkTargetsTest.js | JavaScript | mit | 4,977 |
foo || bar;
(x => x) || bar;
(function a(x) {
return x;
}) || 2;
0 || function () {
return alpha;
};
a && b && c;
a && b && c;
a || b || c;
a || b || c;
a || b && c;
a && (b || c);
(a || b) && c;
a && b || c; | kaicataldo/babel | packages/babel-generator/test/fixtures/types/LogicalExpression/output.js | JavaScript | mit | 215 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: The "in" token can not be used as identifier
es5id: 7.6.1.1_A1.13
description: Checking if execution of "in=1" fails
negative: SyntaxError
---*/
in = 1;
| PiotrDabkowski/Js2Py | tests/test_cases/language/keywords/S7.6.1.1_A1.13.js | JavaScript | mit | 299 |
/*!
* jQuery JavaScript Library v1.8.3 -ajax,-ajax/jsonp,-ajax/script,-ajax/xhr,-effects,-dimensions
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: Thu Feb 07 2013 15:58:11 GMT-0600 (CST)
*/
(function( window, undefined ) {
var
// A central reference to the root jQuery(document)
rootjQuery,
// The deferred used on DOM ready
readyList,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
location = window.location,
navigator = window.navigator,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// Save a reference to some core methods
core_push = Array.prototype.push,
core_slice = Array.prototype.slice,
core_indexOf = Array.prototype.indexOf,
core_toString = Object.prototype.toString,
core_hasOwn = Object.prototype.hasOwnProperty,
core_trim = String.prototype.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,
// Used for detecting and trimming whitespace
core_rnotwhite = /\S/,
core_rspace = /\s+/,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return ( letter + "" ).toUpperCase();
},
// The ready event handler and self cleanup method
DOMContentLoaded = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
} else if ( document.readyState === "complete" ) {
// we're here because readyState === "complete" in oldIE
// which is good enough for us to call the dom ready!
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
},
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
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 = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = ( context && context.nodeType ? context.ownerDocument || context : document );
// scripts is true for back-compat
selector = jQuery.parseHTML( match[1], doc, true );
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
this.attr.call( selector, context, true );
}
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.8.3 -ajax,-ajax/jsonp,-ajax/script,-ajax/xhr,-effects,-dimensions",
// 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 core_slice.call( this );
},
// 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 = jQuery.merge( this.constructor(), 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 ) {
// Add the callback
jQuery.ready.promise().done( 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( core_slice.apply( this, arguments ),
"slice", core_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: core_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 ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// 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.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// 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[ core_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 &&
!core_hasOwn.call(obj, "constructor") &&
!core_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 || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// scripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, scripts ) {
var parsed;
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
scripts = context;
context = 0;
}
context = context || document;
// Single tag
if ( (parsed = rsingleTag.exec( data )) ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] );
return jQuery.merge( [],
(parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes );
},
parseJSON: function( data ) {
if ( !data || typeof data !== "string") {
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 ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
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 && core_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.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var name,
i = 0,
length = obj.length,
isObj = length === undefined || jQuery.isFunction( obj );
if ( args ) {
if ( isObj ) {
for ( name in obj ) {
if ( callback.apply( obj[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( obj[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in obj ) {
if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var type,
ret = results || [];
if ( arr != null ) {
// The window, strings (and functions) also have 'length'
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
type = jQuery.type( arr );
if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) {
core_push.call( ret, arr );
} else {
jQuery.merge( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; 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 retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; 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 ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
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
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context, args.concat( core_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 || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of 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();
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready, 1 );
// Standards-based browsers support DOMContentLoaded
} else 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 {
// 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 top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.split( core_rspace ), function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* 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( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // 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,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( 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
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Control if a given callback is in the list
has: function( fn ) {
return jQuery.inArray( fn, list ) > -1;
},
// 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 ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( 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;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ]( jQuery.isFunction( fn ) ?
function() {
var returned = fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
}
} :
newDefer[ action ]
);
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ] = list.fire
deferred[ tuple[0] ] = list.fire;
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function() {
var support,
all,
a,
select,
opt,
input,
fragment,
eventName,
i,
isSupported,
clickFn,
div = document.createElement("div");
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// Support tests won't run in some limited or non-browser environments
all = div.getElementsByTagName("*");
a = div.getElementsByTagName("a")[ 0 ];
if ( !all || !a || !all.length ) {
return {};
}
// First batch of tests
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
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.5/.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>",
// jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
boxModel: ( document.compatMode === "CSS1Compat" ),
// Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
boxSizingReliable: true,
pixelPosition: false
};
// 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", clickFn = function() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent = false;
});
div.cloneNode( true ).fireEvent("onclick");
div.detachEvent( "onclick", clickFn );
}
// 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: true,
change: true,
focusin: true
}) {
eventName = "on" + i;
isSupported = ( eventName in div );
if ( !isSupported ) {
div.setAttribute( eventName, "return;" );
isSupported = ( typeof div[ eventName ] === "function" );
}
support[ i + "Bubbles" ] = isSupported;
}
}
// Run tests that need a body at doc ready
jQuery(function() {
var container, div, tds, marginDiv,
divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;",
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px";
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></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
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 box-sizing and margin behavior
div.innerHTML = "";
div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
support.boxSizing = ( div.offsetWidth === 4 );
support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );
// NOTE: To any future maintainer, we've window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// 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
marginDiv = document.createElement("div");
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
div.appendChild( marginDiv );
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
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.cssText = divReset + "width:1px;padding:1px;display:inline;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></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
container.style.zoom = 1;
}
// Null elements to avoid leaks in IE
body.removeChild( container );
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
fragment.removeChild( div );
all = a = select = opt = input = fragment = div = null;
return support;
})();
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
jQuery.extend({
cache: {},
deletedIds: [],
// Remove at next major release (1.9/2.0)
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 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;
// 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] || (!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.deletedIds.pop() || jQuery.guid++;
} 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 );
}
}
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;
}
// 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,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// 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;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = 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 ) {
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
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-" ) ) {
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 :
// Only convert to a number if it doesn't change the string
+data + "" === 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 ) {
var name;
for ( 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;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery.removeData( elem, type + "queue", true );
jQuery.removeData( elem, key, true );
})
});
}
});
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 );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
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, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook, fixSpecified,
rclass = /[\t\r\n]/g,
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;
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( core_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 ] + " " ) < 0 ) {
setClass += classNames[ c ] + " ";
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
var removes, className, elem, c, cl, i, l;
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 ) {
removes = ( value || "" ).split( core_rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 && elem.className ) {
className = (" " + elem.className + " ").replace( rclass, " " );
// loop over each item in the removal list
for ( c = 0, cl = removes.length; c < cl; c++ ) {
// Remove until there is nothing to remove,
while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) {
className = className.replace( " " + removes[ c ] + " " , " " );
}
}
elem.className = value ? jQuery.trim( 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( core_rspace );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated 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 ) >= 0 ) {
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 val,
self = jQuery(this);
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, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( 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 );
}
}
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;
}
}
},
// Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9
attrFn: {},
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 && jQuery.isFunction( jQuery.fn[ name ] ) ) {
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, isBool,
i = 0;
if ( value && elem.nodeType === 1 ) {
attrNames = value.split( core_rspace );
for ( ; i < attrNames.length; 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;
}
}
}
});
// 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.value !== "" : ret.specified ) ?
ret.value :
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.value = value + "" );
}
};
// 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)$/,
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, 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,
needsContext: selector && jQuery.expr.match.needsContext.test( 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 t, tns, type, origType, namespaces, origCount,
j, events, special, eventType, handleObj,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
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, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery.removeData( elem, "events", 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 cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType,
type = event.type || event,
namespaces = [];
// 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;
for ( old = elem; 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 === (elem.ownerDocument || document) ) {
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 && 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 i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related,
handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
delegateCount = handlers.delegateCount,
args = core_slice.call( arguments ),
run_all = !event.exclusive && !event.namespace,
special = jQuery.event.special[ event.type ] || {},
handlerQueue = [];
// 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") ) {
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
// Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
selMatch = {};
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
sel = handleObj.selector;
if ( selMatch[ sel ] === undefined ) {
selMatch[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
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, metaKey==false if it's undefined (#3368, #11328; IE6/7/8)
event.metaKey = !!event.metaKey;
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
},
special: {
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 ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === "undefined" ) {
elem[ name ] = null;
}
elem.detachEvent( name, 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 ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj,
selector = handleObj.selector;
// 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 && !jQuery._data( form, "_submit_attached" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( 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;
}
// Allow triggered, simulated change events (#11500)
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 ) && !jQuery._data( 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 );
}
});
jQuery._data( 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 ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
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 ( 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 ( 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 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://sizzlejs.com/
*/
(function( window, undefined ) {
var i,
cachedruns,
Expr,
getText,
isXML,
compile,
hasDuplicate,
outermostContext,
// Local document vars
setDocument,
document,
docElem,
documentIsXML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
sortOrder,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
support = {},
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Array methods
arr = [],
pop = arr.pop,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
operators = "([*^$|!~]?=)",
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments quoted,
// then not containing pseudos/brackets,
// then attribute selectors/non-parenthetical expressions,
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rsibling = /[\x20\t\r\n\f]*[+~]/,
rnative = /\{\s*\[native code\]\s*\}/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rescape = /'|\\/g,
rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,
funescape = function( _, escaped ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
return high !== high ?
escaped :
// BMP codepoint
high < 0 ?
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};
// Use a stripped-down slice if we can't use a native one
try {
slice.call( docElem.childNodes, 0 )[0].nodeType;
} catch ( e ) {
slice = function( i ) {
var elem,
results = [];
for ( ; (elem = this[i]); i++ ) {
results.push( elem );
}
return results;
};
}
/**
* For feature detection
* @param {Function} fn The function to test for native support
*/
function isNative( fn ) {
return rnative.test( fn + "" );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var cache,
keys = [];
return (cache = function( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key += " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key ] = value);
});
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return fn( div );
} catch (e) {
return false;
} finally {
// release memory in IE
div = null;
}
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( !documentIsXML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// 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, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) {
push.apply( results, slice.call(context.getElementsByClassName( m ), 0) );
return results;
}
}
// QSA path
if ( support.qsa && !rbuggyQSA.test(selector) ) {
old = true;
nid = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// 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
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results, slice.call( newContext.querySelectorAll(
newSelector
), 0 ) );
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Detect xml
* @param {Element|Object} elem An element or a document
*/
isXML = 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).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var doc = node ? node.ownerDocument || node : preferredDoc;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsXML = isXML( doc );
// Check if getElementsByTagName("*") returns only elements
support.tagNameNoComments = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if attributes should be retrieved by attribute nodes
support.attributes = assert(function( div ) {
div.innerHTML = "<select></select>";
var type = typeof div.lastChild.getAttribute("multiple");
// IE8 returns a string for some attributes even when not present
return type !== "boolean" && type !== "string";
});
// Check if getElementsByClassName can be trusted
support.getByClassName = assert(function( div ) {
// Opera can't find a second classname (in 9.6)
div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) {
return false;
}
// Safari 3.2 caches class attributes and doesn't catch changes
div.lastChild.className = "e";
return div.getElementsByClassName("e").length === 2;
});
// Check if getElementById returns elements by name
// Check if getElementsByName privileges form controls or returns elements by ID
support.getByName = assert(function( div ) {
// Inject content
div.id = expando + 0;
div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
docElem.insertBefore( div, docElem.firstChild );
// Test
var pass = doc.getElementsByName &&
// buggy browsers will return fewer than the correct 2
doc.getElementsByName( expando ).length === 2 +
// buggy browsers will return more than the correct 0
doc.getElementsByName( expando + 0 ).length;
support.getIdNotName = !doc.getElementById( expando );
// Cleanup
docElem.removeChild( div );
return pass;
});
// IE6/7 return modified attributes
Expr.attrHandle = assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
div.firstChild.getAttribute("href") === "#";
}) ?
{} :
{
"href": function( elem ) {
return elem.getAttribute( "href", 2 );
},
"type": function( elem ) {
return elem.getAttribute("type");
}
};
// ID find and filter
if ( support.getIdNotName ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && !documentIsXML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && !documentIsXML ) {
var m = context.getElementById( id );
return m ?
m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
[m] :
undefined :
[];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.tagNameNoComments ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
for ( ; (elem = results[i]); i++ ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Name
Expr.find["NAME"] = support.getByName && function( tag, context ) {
if ( typeof context.getElementsByName !== strundefined ) {
return context.getElementsByName( name );
}
};
// Class
Expr.find["CLASS"] = support.getByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) {
return context.getElementsByClassName( className );
}
};
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21),
// no need to also add to buggyMatches since matches checks buggyQSA
// A support test would require too much code (would include document ready)
rbuggyQSA = [ ":focus" ];
if ( (support.qsa = isNative(doc.querySelectorAll)) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explictly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// IE8 - Some boolean attributes are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Opera 10-12/IE8 - ^= $= *= and empty values
// Should not select anything
div.innerHTML = "<input type='hidden' i=''/>";
if ( div.querySelectorAll("[i^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector ||
docElem.mozMatchesSelector ||
docElem.webkitMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = new RegExp( rbuggyMatches.join("|") );
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = isNative(docElem.contains) || docElem.compareDocumentPosition ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
// Document order sorting
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
var compare;
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) {
if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) {
if ( a === doc || contains( preferredDoc, a ) ) {
return -1;
}
if ( b === doc || contains( preferredDoc, b ) ) {
return 1;
}
return 0;
}
return compare & 4 ? -1 : 1;
}
return a.compareDocumentPosition ? -1 : 1;
} :
function( a, b ) {
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ 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 ( ~b.sourceIndex || MAX_NEGATIVE ) - ( contains( preferredDoc, a ) && ~a.sourceIndex || MAX_NEGATIVE );
// Parentless nodes are either documents or disconnected
} else if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
// Always assume the presence of duplicates if sort doesn't
// pass them to our comparison function (as in Google Chrome).
hasDuplicate = false;
[0, 0].sort( sortOrder );
support.detectDuplicates = hasDuplicate;
return document;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
// rbuggyQSA always contains :focus, so no need for an existence check
if ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, document, null, [elem] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
var val;
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
if ( !documentIsXML ) {
name = name.toLowerCase();
}
if ( (val = Expr.attrHandle[ name ]) ) {
return val( elem );
}
if ( documentIsXML || support.attributes ) {
return elem.getAttribute( name );
}
return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ?
name :
val && val.specified ? val.value : null;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
// Document sorting and removing duplicates
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
i = 1,
j = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( ; (elem = results[i]); i++ ) {
if ( elem === results[ i - 1 ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
function siblingCheck( a, b ) {
var cur = a && b && a.nextSibling;
for ( ; cur; cur = cur.nextSibling ) {
if ( cur === b ) {
return -1;
}
}
return a ? 1 : -1;
}
// Returns a function to use in pseudos for input types
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
// Returns a function to use in pseudos for buttons
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
// Returns a function to use in pseudos for positionals
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[5] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[4] ) {
match[2] = match[4];
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeName ) {
if ( nodeName === "*" ) {
return function() { return true; };
}
nodeName = nodeName.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.substr( result.length - check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifider
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsXML ?
elem.getAttribute("xml:lang") || elem.getAttribute("lang") :
elem.lang) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"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;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
// 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" &&
elem.type === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push( {
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
} );
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push( {
value: matched,
type: type,
matches: match
} );
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && combinator.dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var data, cache, outerCache,
dirkey = dirruns + " " + doneName;
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
if ( (data = cache[1]) === true || data === cachedruns ) {
return data === true;
}
} else {
cache = outerCache[ dir ] = [ dirkey ];
cache[1] = matcher( elem, context, xml ) || cachedruns;
if ( cache[1] === true ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
// A counter to specify which element is currently being matched
var matcherCachedRuns = 0,
bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Nested matchers should use non-integer dirruns
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = matcherCachedRuns;
}
// Add elements passing elementMatchers directly to results
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
for ( j = 0; (matcher = elementMatchers[j]); j++ ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++matcherCachedRuns;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
// `i` starts as a string, so matchedCount would equal "00" if there are no elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
for ( j = 0; (matcher = setMatchers[j]); j++ ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed ) {
var i, tokens, token, type, find,
match = tokenize( selector );
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
context.nodeType === 9 && !documentIsXML &&
Expr.relative[ tokens[1].type ] ) {
context = Expr.find["ID"]( token.matches[0].replace( runescape, funescape ), context )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
for ( i = matchExpr["needsContext"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && context.parentNode || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, slice.call( seed, 0 ) );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
documentIsXML,
results,
rsibling.test( selector )
);
return results;
}
// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Easy API for creating new setFilters
function setFilters() {}
Expr.filters = setFilters.prototype = Expr.pseudos;
Expr.setFilters = new setFilters();
// Initialize with the default document
setDocument();
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
var runtil = /Until$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
isSimple = /^.[^:#\[\.,]*$/,
rneedsContext = jQuery.expr.match.needsContext,
// 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 i, l, length, n, r, ret,
self = this;
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;
}
}
});
}
ret = this.pushStack( "", "find", selector );
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 i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; 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/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
rneedsContext.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 cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
cur = this[i];
while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
}
cur = cur.parentNode;
}
}
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 ) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
jQuery.fn.andSelf = jQuery.fn.addBack;
// 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;
}
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
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 sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "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.merge( [], 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 && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, core_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;
},
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+="(?:null|\d+)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
rnocache = /<(?:script|object|embed|option|style)/i,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rcheckableType = /^(?:checkbox|radio)$/,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /\/(java|ecma)script/i,
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,
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 ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "X<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.nodeType === 11 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( !isDisconnected( this[0] ) ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
}
if ( arguments.length ) {
var set = jQuery.clean( arguments );
return this.pushStack( jQuery.merge( set, this ), "before", this.selector );
}
},
after: function() {
if ( !isDisconnected( this[0] ) ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
}
if ( arguments.length ) {
var set = jQuery.clean( arguments );
return this.pushStack( jQuery.merge( this, set ), "after", this.selector );
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
i = 0;
for ( ; (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() {
var elem,
i = 0;
for ( ; (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, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.htmlSerialize || !rnoshimcache.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 ( !isDisconnected( this[0] ) ) {
// 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 );
}
});
}
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 ) {
// Flatten any nested arrays
args = [].concat.apply( [], args );
var results, first, fragment, iNoClone,
i = 0,
value = args[0],
scripts = [],
l = this.length;
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback );
});
}
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] ) {
results = jQuery.buildFragment( args, this, scripts );
fragment = results.fragment;
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
// Fragments from the fragment cache must always be cloned and never used in place.
for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) {
callback.call(
table && jQuery.nodeName( this[i], "table" ) ?
findOrAppend( this[i], "tbody" ) :
this[i],
i === iNoClone ?
fragment :
jQuery.clone( fragment, true, true )
);
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
if ( scripts.length ) {
jQuery.each( scripts, function( i, elem ) {
if ( elem.src ) {
if ( jQuery.ajax ) {
jQuery.ajax({
url: elem.src,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
} else {
jQuery.error("no ajax");
}
} else {
jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
});
}
}
return this;
}
});
function findOrAppend( elem, tag ) {
return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) );
}
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();
if ( nodeName === "object" ) {
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
// 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
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 );
}
jQuery.buildFragment = function( args, context, scripts ) {
var fragment, cacheable, cachehit,
first = args[ 0 ];
// Set context from what may come in as undefined or a jQuery collection or a node
// Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 &
// also doubles as fix for #8950 where plain objects caused createDocumentFragment exception
context = context || document;
context = !context.nodeType && context[0] || context;
context = context.ownerDocument || context;
// 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 && context === document &&
first.charAt(0) === "<" && !rnocache.test( first ) &&
(jQuery.support.checkClone || !rchecked.test( first )) &&
(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {
// Mark cacheable and look for a hit
cacheable = true;
fragment = jQuery.fragments[ first ];
cachehit = fragment !== undefined;
}
if ( !fragment ) {
fragment = context.createDocumentFragment();
jQuery.clean( args, context, fragment, scripts );
// Update the cache, but only store false
// unless this is a second parsing of the same content
if ( cacheable ) {
jQuery.fragments[ first ] = cachehit && fragment;
}
}
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 elems,
i = 0,
ret = [],
insert = jQuery( selector ),
l = insert.length,
parent = this.length === 1 && this[0].parentNode;
if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( ; i < l; i++ ) {
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 ( rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var srcElements,
destElements,
i,
clone;
if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
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 i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags,
safe = context === document && safeFragment,
ret = [];
// Ensure that context is a document
if ( !context || typeof context.createDocumentFragment === "undefined" ) {
context = document;
}
// Use the already-created safe fragment if context permits
for ( i = 0; (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 {
// Ensure a safe container in which to render the html
safe = safe || createSafeFragment( context );
div = context.createElement("div");
safe.appendChild( div );
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Go to html and back, then peel off extra wrappers
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
depth = wrap[0];
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>
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;
// Take out of fragment container (we need a fresh div each time)
div.parentNode.removeChild( div );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
jQuery.merge( ret, elem );
}
}
// Fix #11356: Clear elements from safeFragment
if ( div ) {
elem = div = safe = null;
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !jQuery.support.appendChecked ) {
for ( i = 0; (elem = ret[i]) != null; i++ ) {
if ( jQuery.nodeName( elem, "input" ) ) {
fixDefaultChecked( elem );
} else if ( typeof elem.getElementsByTagName !== "undefined" ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
}
// Append elements to a provided document fragment
if ( fragment ) {
// Special handling of each script element
handleScript = function( elem ) {
// Check if we consider it executable
if ( !elem.type || rscriptType.test( elem.type ) ) {
// Detach the script and store it in the scripts array (if provided) or the fragment
// Return truthy to indicate that it has been handled
return scripts ?
scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) :
fragment.appendChild( elem );
}
};
for ( i = 0; (elem = ret[i]) != null; i++ ) {
// Check if we're done after handling an executable script
if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) {
// Append to fragment and handle embedded scripts
fragment.appendChild( elem );
if ( typeof elem.getElementsByTagName !== "undefined" ) {
// handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration
jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript );
// Splice the scripts into ret after their former ancestor and advance our index beyond them
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
i += jsTags.length;
}
}
}
}
return ret;
},
cleanData: function( elems, /* internal */ acceptData ) {
var data, id, elem, type,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( 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 );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// 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 ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
jQuery.deletedIds.push( id );
}
}
}
}
}
});
// Limit scope pollution from any deprecated API
(function() {
var matched, browser;
// Use of jQuery.browser is frowned upon.
// More details: http://api.jquery.com/jQuery.browser
// jQuery.uaMatch maintained for back-compat
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
matched = jQuery.uaMatch( navigator.userAgent );
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
jQuery.browser = browser;
jQuery.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;
};
})();
var curCSS, iframe, iframeDoc,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ),
elemdisplay = { BODY: "block" },
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ],
eventsToggle = jQuery.fn.toggle;
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function isHidden( elem, el ) {
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
function showHide( elements, show ) {
var elem, display,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && elem.style.display === "none" ) {
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 ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
display = curCSS( elem, "display" );
if ( !values[ index ] && display !== "none" ) {
jQuery._data( elem, "olddisplay", display );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.fn.extend({
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 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state, fn2 ) {
var bool = typeof state === "boolean";
if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) {
return eventsToggle.apply( this, arguments );
}
return this.each(function() {
if ( bool ? state : isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
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;
}
}
}
},
// 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, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ 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, extra )) !== 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, numeric, extra ) {
var val, num, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( numeric || extra !== undefined ) {
num = parseFloat( val );
return numeric || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var ret, name,
old = {};
// 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;
}
});
// NOTE: To any future maintainer, we've window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
curCSS = function( elem, name ) {
var ret, width, minWidth, maxWidth,
computed = window.getComputedStyle( elem, null ),
style = elem.style;
if ( computed ) {
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed.getPropertyValue( name ) || computed[ name ];
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
} else if ( document.documentElement.currentStyle ) {
curCSS = function( elem, name ) {
var left, rsLeft,
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 && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// 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;
};
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
// we use jQuery.css instead of curCSS here
// because of the reliableMarginRight CSS hook!
val += jQuery.css( elem, extra + cssExpand[ i ], true );
}
// From this point on we use curCSS for maximum performance (relevant in animations)
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
} else {
// at this point, extra isn't content, so add padding
val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
valueIsBorderBox = true,
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// 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;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
if ( elemdisplay[ nodeName ] ) {
return elemdisplay[ nodeName ];
}
var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.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 === "" ) {
// Use the already-created iframe if possible
iframe = document.body.appendChild(
iframe || jQuery.extend( document.createElement("iframe"), {
frameBorder: 0,
width: 0,
height: 0
})
);
// 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("<!doctype html><html><body>");
iframeDoc.close();
}
elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) );
display = curCSS( elem, "display" );
document.body.removeChild( iframe );
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
return display;
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) {
return jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
});
} else {
return getWidthOrHeight( elem, name, extra );
}
}
},
set: function( elem, value, extra ) {
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"
) : 0
);
}
};
});
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) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
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, "" ) ) === "" &&
style.removeAttribute ) {
// 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;
}
};
}
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
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, "marginRight" );
}
});
}
};
}
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = {
get: function( elem, computed ) {
if ( computed ) {
var ret = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret;
}
}
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( 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;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
rselectTextarea = /^(?:select|textarea)/i;
jQuery.fn.extend({
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();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && 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 ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
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 ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
var rroot = /^(?:body|html)$/i;
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
if ( (body = doc.body) === elem ) {
return jQuery.offset.bodyOffset( elem );
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== "undefined" ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
clientTop = docElem.clientTop || body.clientTop || 0;
clientLeft = docElem.clientLeft || body.clientLeft || 0;
scrollTop = win.pageYOffset || docElem.scrollTop;
scrollLeft = win.pageXOffset || docElem.scrollLeft;
return {
top: box.top + scrollTop - clientTop,
left: box.left + scrollLeft - clientLeft
};
};
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;
}
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 || document.body;
});
}
});
// 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 ] :
win.document.documentElement[ 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;
}
// 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 );
| eric-seekas/jquery-builder | dist/1.8.3/jquery-ajax-dimensions-effects.js | JavaScript | mit | 217,443 |
Subsets and Splits