code stringlengths 2 1.05M |
|---|
const path = require('path');
const os = require('os');
// This is also defined in bindings.js. This code duplication is ugly, but it
// significantly simplifies packaging the `kelda init` code with the
// "@kelda/install" module.
const infraDirectory = path.join(os.homedir(), '.kelda', 'infra');
const baseInfraLocation = path.join(infraDirectory, 'default.js');
// Used in infrastructure template.
const namespace = 'namespace';
const provider = 'provider';
const size = 'size';
const ram = 'ram';
const cpu = 'cpu';
const preemptible = 'preemptible';
const region = 'region';
const masterCount = 'masterCount';
const workerCount = 'workerCount';
// Infrastructure.
const infraOverwrite = 'infraOverwrite';
// Provider.
const providerUseExistingKey = 'useExistingKey';
const providerCredsPath = 'credsPath';
const credsConfirmOverwrite = 'confirmOverwrite';
// Size.
const other = 'other';
const inputCredsPath = 'credsPath';
module.exports = {
infraDirectory,
baseInfraLocation,
namespace,
infraOverwrite,
provider,
providerUseExistingKey,
providerCredsPath,
credsConfirmOverwrite,
other,
size,
ram,
cpu,
preemptible,
region,
masterCount,
workerCount,
inputCredsPath,
};
|
'use strict';
/**
* External module's name startof "$"
*/
var $Message = require('./message')
var $keypath = require('./keypath')
var $arrayHook = require('./array-hook')
var $info = require('./info')
var $util = require('./util')
var $normalize = $keypath.normalize
var $join = $keypath.join
var $type = $util.type
var $indexOf = $util.indexOf
var $hasOwn = $util.hasOwn
var $warn = $info.warn
/**
* CONTS
*/
var STRING = 'string'
var ARRAY = 'array'
var OBJECT = 'object'
var FUNCTION = 'function'
var CHANGE_EVENT = 'change'
var _id = 0
function allotId() {
return _id ++
}
/**
* Mux model constructor
* @public
*/
function Mux(options) {
// static config checking
options = options || {}
Ctor.call(this, options)
}
/**
* Mux model creator
* @public
*/
Mux.extend = function(options) {
return MuxFactory(options || {})
}
/**
* Mux global config
* @param conf <Object>
*/
Mux.config = function (conf) {
if (conf.warn === false) $info.disable()
else $info.enable()
}
/**
* Create a emitter instance
* @param `Optional` context use for binding "this"
*/
Mux.emitter = function (context) {
return new $Message(context)
}
/**
* Expose Keypath API
*/
Mux.keyPath = $keypath
Mux.utils = $util
/**
* Mux model factory
* @private
*/
function MuxFactory(options) {
function Class (receiveProps) {
Ctor.call(this, options, receiveProps)
}
Class.prototype = Object.create(Mux.prototype)
return Class
}
/**
* Mux's model class, could instance with "new" operator or call it directly.
* @param receiveProps <Object> initial props set to model which will no trigger change event.
*/
function Ctor(options, receiveProps) {
var model = this
var emitter = options.emitter || new $Message(model) // EventEmitter of this model, context bind to model
var _emitter = options._emitter || new $Message(model)
var _computedCtx = $hasOwn(options, 'computedContext') ? options.computedContext : model
var __kp__ = $keypath.normalize(options.__kp__ || '')
var __muxid__ = allotId()
var _isExternalEmitter = !!options.emitter
var _isExternalPrivateEmitter = !!options._emitter
var _destroy // interanl destroyed flag
var _privateProperties = {}
_defPrivateProperty('__muxid__', __muxid__)
_defPrivateProperty('__kp__', __kp__)
/**
* return current keypath prefix of this model
*/
function _rootPath () {
return __kp__ || ''
}
/**
* define priavate property of the instance object
*/
function _defPrivateProperty(name, value) {
if (instanceOf(value, Function)) value = value.bind(model)
_privateProperties[name] = value
$util.def(model, name, {
enumerable: false,
value: value
})
}
var getter = options.props
/**
* Get initial props from options
*/
var _initialProps = {}
var _t = $type(getter)
if (_t == FUNCTION) {
_initialProps = getter()
} else if (_t == OBJECT) {
_initialProps = getter
}
// free
getter = null
var _initialComputedProps = options.computed
var _computedProps = {}
var _computedKeys = []
var _cptDepsMapping = {} // mapping: deps --> props
var _cptCaches = {} // computed properties caches
var _observableKeys = []
var _props = {} // all observable properties {propname: propvalue}
/**
* Observe initial properties
*/
$util.objEach(_initialProps, function (pn, pv) {
_$add(pn, pv, true)
})
_initialProps = null
/**
* Define initial computed properties
*/
$util.objEach(_initialComputedProps, function (pn, def) {
_$computed(pn, def.deps, def.get, def.set, def.enum)
})
_initialComputedProps = null
/**
* batch emit computed property change
*/
_emitter.on(CHANGE_EVENT, function (kp) {
var willComputedProps = []
var mappings = []
if (!Object.keys(_cptDepsMapping).length) return
while(kp) {
_cptDepsMapping[kp] && (mappings = mappings.concat(_cptDepsMapping[kp]))
kp = $keypath.digest(kp)
}
if (!mappings.length) return
/**
* get all computed props that depend on kp
*/
mappings.reduce(function (pv, cv) {
if (!$indexOf(pv, cv)) pv.push(cv)
return pv
}, willComputedProps)
willComputedProps.forEach(function (ck) {
$util.patch(_cptCaches, ck, {})
var cache = _cptCaches[ck]
var pre = cache.pre = cache.cur
var next = cache.cur = (_computedProps[ck].get || NOOP).call(_computedCtx, model)
if ($util.diff(next, pre)) _emitChange(ck, next, pre)
})
}, __muxid__/*scope*/)
/**
* private methods
*/
function _destroyNotice () {
$warn('Instance already has bean destroyed')
return _destroy
}
// local proxy for EventEmitter
function _emitChange(propname/*, arg1, ..., argX*/) {
var args = arguments
var kp = $normalize($join(_rootPath(), propname))
args[0] = CHANGE_EVENT + ':' + kp
_emitter.emit(CHANGE_EVENT, kp)
emitter.emit.apply(emitter, args)
args = $util.copyArray(args)
args[0] = kp
args.unshift('*')
emitter.emit.apply(emitter, args)
}
/**
* Add dependence to "_cptDepsMapping"
* @param propname <String> property name
* @param dep <String> dependency name
*/
function _prop2CptDepsMapping (propname, dep) {
// if ($indexOf(_computedKeys, dep))
// return $warn('Dependency should not computed property')
$util.patch(_cptDepsMapping, dep, [])
var dest = _cptDepsMapping[dep]
if ($indexOf(dest, propname)) return
dest.push(propname)
}
/**
* Instance or reuse a sub-mux-instance with specified keyPath and emitter
* @param target <Object> instance target, it could be a Mux instance
* @param props <Object> property value that has been walked
* @param kp <String> keyPath of target, use to diff instance keyPath changes or instance with the keyPath
*/
function _subInstance (target, props, kp) {
var ins
var _mux = target.__mux__
if (_mux && _mux.__kp__ === kp && _mux.__root__ === __muxid__) {
// reuse
ins = target
// emitter proxy
ins._$emitter(emitter)
// a private emitter for communication between instances
ins._$_emitter(_emitter)
} else {
ins = new Mux({
props: props,
emitter: emitter,
_emitter: _emitter,
__kp__: kp
})
}
if (!ins.__root__) {
$util.def(ins, '__root__', {
enumerable: false,
value: __muxid__
})
}
return ins
}
/**
* A hook method for setting value to "_props"
* @param name <String> property name
* @param value
* @param mountedPath <String> property's value mouted path
*/
function _walk (name, value, mountedPath) {
var tov = $type(value) // type of value
// initial path prefix is root path
var kp = mountedPath ? mountedPath : $join(_rootPath(), name)
/**
* Array methods hook
*/
if (tov == ARRAY) {
$arrayHook(value, function (self, methodName, nativeMethod, args) {
var pv = $util.copyArray(self)
var result = nativeMethod.apply(self, args)
// set value directly after walk
_props[name] = _walk(name, self, kp)
if (methodName == 'splice') {
_emitChange(kp, self, pv, methodName, args)
} else {
_emitChange(kp, self, pv, methodName)
}
return result
})
}
// deep observe into each property value
switch(tov) {
case OBJECT:
// walk deep into object items
var props = {}
var obj = value
if (instanceOf(value, Mux)) obj = value.$props()
$util.objEach(obj, function (k, v) {
props[k] = _walk(k, v, $join(kp, k))
})
return _subInstance(value, props, kp)
case ARRAY:
// walk deep into array items
value.forEach(function (item, index) {
value[index] = _walk(index, item, $join(kp, index))
})
return value
default:
return value
}
}
/*************************************************************
Function name start of "_$" are expose methods
*************************************************************/
/**
* Set key-value pair to private model's property-object
* @param kp <String> keyPath
* @return <Object> diff object
*/
function _$sync(kp, value, lazyEmit) {
var parts = $normalize(kp).split('.')
var prop = parts[0]
if ($indexOf(_computedKeys, prop)) {
// since Mux@2.4.0 computed property support setter
model[prop] = value
return
}
if (!$indexOf(_observableKeys, prop)) {
$warn('Property "' + prop + '" has not been observed')
// return false means sync prop fail
return
}
var pv = $keypath.get(_props, kp)
var isObj = instanceOf(value, Object)
var nKeypath = parts.join('.')
var name = parts.pop()
var parentPath = parts.join('.')
var parent = $keypath.get(_props, parentPath)
var isParentObserved = instanceOf(parent, Mux)
var changed
if (isParentObserved) {
if ($hasOwn(parent, name)) {
changed = parent._$set(name, value, lazyEmit)
} else {
parent._$add(name, value, lazyEmit)
changed = [$keypath.join(_rootPath(), kp), value]
}
} else {
$keypath.set(
_props,
kp,
isObj
? _walk(name, value, $join(_rootPath(), nKeypath))
: value
)
if ($util.diff(value, pv)) {
if (!lazyEmit) {
_emitChange(kp, value, pv)
} else {
changed = [$keypath.join(_rootPath(), kp), value, pv]
}
}
}
return changed
}
/**
* sync props value and trigger change event
* @param kp <String> keyPath
*/
function _$set(kp, value, lazyEmit) {
if (_destroy) return _destroyNotice()
return _$sync(kp, value, lazyEmit)
// if (!diff) return
/**
* Base type change of object type will be trigger change event
* next and pre value are not keypath value but property value
*/
// if ( kp == diff.mounted && $util.diff(diff.next, diff.pre) ) {
// var propname = diff.mounted
// // emit change immediately
// _emitChange(propname, diff.next, diff.pre)
// }
}
/**
* sync props's value in batch and trigger change event
* @param keyMap <Object> properties object
*/
function _$setMulti(keyMap) {
if (_destroy) return _destroyNotice()
if (!keyMap || $type(keyMap) != OBJECT) return
var changes = []
$util.objEach(keyMap, function (key, item) {
var cg = _$set(key, item, true)
if (cg) changes.push(cg)
})
changes.forEach(function (args) {
_emitChange.apply(null, args)
})
}
/**
* create a prop observer if not in observer,
* return true if no value setting.
* @param prop <String> property name
* @param value property value
*/
function _$add(prop, value, lazyEmit) {
if (prop.match(/[\.\[\]]/)) {
throw new Error('Propname shoudn\'t contains "." or "[" or "]"')
}
if ($indexOf(_observableKeys, prop)) {
// If value is specified, reset value
return arguments.length > 1 ? true : false
}
_props[prop] = _walk(prop, $util.copyValue(value))
_observableKeys.push(prop)
$util.def(model, prop, {
enumerable: true,
get: function() {
return _props[prop]
},
set: function (v) {
_$set(prop, v)
}
})
// add peroperty will trigger change event
if (!lazyEmit) {
_emitChange(prop, value)
} else {
return {
kp: prop,
vl: value
}
}
}
/**
* define computed prop/props of this model
* @param propname <String> property name
* @param deps <Array> computed property dependencies
* @param get <Function> computed property getter
* @param set <Function> computed property setter
* @param enumerable <Boolean> whether property enumerable or not
*/
function _$computed (propname, deps, getFn, setFn, enumerable) {
/**
* property is exist
*/
if ($indexOf(_computedKeys, propname)) return
_computedKeys.push(propname)
_computedProps[propname] = {
'deps': deps,
'get': getFn,
'set': setFn
}
/**
* Add to dependence-property mapping
*/
;(deps || []).forEach(function (dep) {
while(dep) {
_prop2CptDepsMapping(propname, dep)
dep = $keypath.digest(dep)
}
})
/**
* define getter
*/
$util.patch(_cptCaches, propname, {})
var dest = _cptCaches[propname]
dest.cur = getFn ? getFn.call(_computedCtx, model):undefined
$util.def(model, propname, {
enumerable: enumerable === undefined ? true : !!enumerable,
get: function () {
return dest.cur
},
set: function () {
setFn && setFn.apply(_computedCtx, arguments)
}
})
// emit change event when define
_emitChange(propname, dest.cur)
}
/*******************************
define instantiation's methods
*******************************/
/**
* define observerable prop/props
* @param propname <String> | <Array>
* @param defaultValue Optional
* ----------------------------
* @param propnameArray <Array>
* ------------------------
* @param propsObj <Object>
*/
_defPrivateProperty('$add', function(/* [propname [, defaultValue]] | propnameArray | propsObj */) {
var args = arguments
var first = args[0]
var pn, pv
switch($type(first)) {
case STRING:
// with specified value or not
pn = first
if (args.length > 1) {
pv = args[1]
if (_$add(pn, pv)) {
_$set(pn, pv)
}
} else {
_$add(pn)
}
break
case ARRAY:
// observe properties without value
first.forEach(function (item) {
_$add(item)
})
break
case OBJECT:
// observe properties with value, if key already exist, reset value only
var resetProps
$util.objEach(first, function (ipn, ipv) {
if (_$add(ipn, ipv)) {
!resetProps && (resetProps = {})
resetProps[ipn] = ipv
}
})
if (resetProps) _$setMulti(resetProps)
break
default:
$warn('Unexpect params')
}
return this
})
_defPrivateProperty('_$add', function (prop, value, lazyEmit) {
var result = _$add(prop, value, !!lazyEmit)
if (result === true) {
return _$set(prop, value, !!lazyEmit)
}
return result
})
/**
* define computed prop/props
* @param propname <String> property name
* @param deps <Array> computed property dependencies
* @param getFn <Function> computed property getter
* @param setFn <Function> computed property setter
* @param enumerable <Boolean> Optional, whether property enumerable or not
* --------------------------------------------------
* @param propsObj <Object> define multiple properties
*/
_defPrivateProperty('$computed', function (propname/*, deps, getFn, setFn, enumerable | [propsObj]*/) {
if ($type(propname) == STRING) {
_$computed.apply(null, arguments)
} else if ($type(propname) == OBJECT) {
$util.objEach(arguments[0], function (pn, pv /*propname, propnamevalue*/) {
_$computed(pn, pv.deps, pv.get, pv.set, pv.enum)
})
} else {
$warn('$computed params show be "(String, Array, Function, Function)" or "(Object)"')
}
return this
})
/**
* subscribe prop change
* change prop/props value, it will be trigger change event
* @param kp <String>
* ---------------------
* @param kpMap <Object>
*/
_defPrivateProperty('$set', function( /*[kp, value] | [kpMap]*/ ) {
var args = arguments
var len = args.length
if (len >= 2 || (len == 1 && $type(args[0]) == STRING)) {
return _$set(args[0], args[1])
} else if (len == 1 && $type(args[0]) == OBJECT) {
return _$setMulti(args[0])
} else {
$warn('Unexpect $set params')
}
})
_defPrivateProperty('_$set', function(key, value, lazyEmit) {
return _$set(key, value, !!lazyEmit)
})
/**
* Get property value by name, using for get value of computed property without cached
* change prop/props value, it will be trigger change event
* @param kp <String> keyPath
*/
_defPrivateProperty('$get', function(kp) {
if ($indexOf(_observableKeys, kp))
return _props[kp]
else if ($indexOf(_computedKeys, kp)) {
return (_computedProps[kp].get || NOOP).call(_computedCtx, model)
} else {
// keyPath
var normalKP = $normalize(kp)
var parts = normalKP.split('.')
if (!$indexOf(_observableKeys, parts[0])) {
return
} else {
return $keypath.get(_props, normalKP)
}
}
})
/**
* if params is (key, callback), add callback to key's subscription
* if params is (callback), subscribe any prop change events of this model
* @param key <String> optional
* @param callback <Function>
*/
_defPrivateProperty('$watch', function( /*[key, ]callback*/ ) {
var args = arguments
var len = args.length
var first = args[0]
var key, callback
if (len >= 2) {
key = CHANGE_EVENT + ':' + $normalize($join(_rootPath(), first))
callback = args[1]
} else if (len == 1 && $type(first) == FUNCTION) {
key = '*'
callback = first
} else {
$warn('Unexpect $watch params')
return NOOP
}
emitter.on(key, callback, __muxid__/*scopre*/)
var that = this
// return a unsubscribe method
return function() {
that.$unwatch.apply(that, args)
}
})
/**
* unsubscribe prop change
* if params is (key, callback), remove callback from key's subscription
* if params is (callback), remove all callbacks from key's subscription
* if params is empty, remove all callbacks of current model
* @param key <String>
* @param callback <Function>
*/
_defPrivateProperty('$unwatch', function( /*[key, ] [callback] */ ) {
var args = arguments
var len = args.length
var first = args[0]
var params
var prefix
switch (true) {
case (len >= 2):
params = [args[1]]
case (len == 1 && $type(first) == STRING):
!params && (params = [])
prefix = CHANGE_EVENT + ':' + $normalize($join(_rootPath(), first))
params.unshift(prefix)
break
case (len == 1 && $type(first) == FUNCTION):
params = ['*', first]
break
case (len === 0):
params = []
break
default:
$warn('Unexpect param type of ' + first)
}
if (params) {
params.push(__muxid__)
emitter.off.apply(emitter, params)
}
return this
})
/**
* Return all properties without computed properties
* @return <Object>
*/
_defPrivateProperty('$props', function() {
return $util.copyObject(_props)
})
/**
* Reset event emitter
* @param em <Object> emitter
*/
_defPrivateProperty('$emitter', function (em, _pem) {
// return emitter instance if args is empty,
// for share some emitter with other instance
if (arguments.length === 0) return emitter
emitter = em
_walkResetEmiter(this.$props(), em, _pem)
return this
})
/**
* set emitter directly
*/
_defPrivateProperty('_$emitter', function (em) {
emitter = em
})
/**
* set private emitter directly
*/
_defPrivateProperty('_$_emitter', function (em) {
instanceOf(em, $Message) && (_emitter = em)
})
/**
* Call destroy will release all private properties and variables
*/
_defPrivateProperty('$destroy', function () {
// clean up all proto methods
$util.objEach(_privateProperties, function (k, v) {
if ($type(v) == FUNCTION && k != '$destroyed') _privateProperties[k] = _destroyNotice
})
if (!_isExternalEmitter) emitter.off()
else emitter.off(__muxid__)
if (!_isExternalPrivateEmitter) _emitter.off()
else _emitter.off(__muxid__)
emitter = null
_emitter = null
_computedProps = null
_computedKeys = null
_cptDepsMapping = null
_cptCaches = null
_observableKeys = null
_props = null
// destroy external flag
_destroy = true
})
/**
* This method is used to check the instance is destroyed or not
*/
_defPrivateProperty('$destroyed', function () {
return _destroy
})
/**
* A shortcut of $set(props) while instancing
*/
_$setMulti(receiveProps)
}
/**
* Reset emitter of the instance recursively
* @param ins <Mux>
*/
function _walkResetEmiter (ins, em, _pem) {
if ($type(ins) == OBJECT) {
var items = ins
if (instanceOf(ins, Mux)) {
ins._$emitter(em, _pem)
items = ins.$props()
}
$util.objEach(items, function (k, v) {
_walkResetEmiter(v, em, _pem)
})
} else if ($type(ins) == ARRAY) {
ins.forEach(function (v) {
_walkResetEmiter(v, em, _pem)
})
}
}
function NOOP() {}
function instanceOf(a, b) {
return a instanceof b
}
module.exports = Mux |
/**
* @author ddchen
*/
var objectRinser = require("./objectRinser.js");
var originalEventRinser = require("./originalEventRinser.js");
var cleanRules = [];
var confs = null;
var addCleanRule = function(rule) {
cleanRules.push(rule);
}
var isFunction = function(fn) {
return !!fn && !fn.nodeName && fn.constructor != String &&
fn.constructor != RegExp && fn.constructor != Array &&
/function/i.test(fn + "");
}
addCleanRule(function() {
objectRinser.clean();
if (confs.events && confs.events.on === true) {
originalEventRinser.clean();
}
});
module.exports = {
addCleanRule: addCleanRule,
addEventIgnore: originalEventRinser.addEventIgnore,
record: function(opts) {
confs = opts || {};
objectRinser.record(confs.objects);
if (confs.events && confs.events.on === true) {
originalEventRinser.record(confs.events);
}
},
clean: function() {
for (var i = 0; i < cleanRules.length; i++) {
var rule = cleanRules[i];
isFunction(rule) && rule();
}
},
generalConf: {
windowIgnore: [/webkit/, "location", "document.location", "localStorage", "name", "sessionStorage", "history"]
}
} |
function verifica(){
/*
const database = firebase.database();
const ref = database.ref("dados");
var data = {
nome: 'claudinho bochecha',
nivel: '111'
};
var myRef = ref.push(data);
alert('teste: ' + myRef);*/
}
const txtEmail = document.getElementById('email');
const txtPassword = document.getElementById('senha');
const btnLogin = document.getElementById('btnLogin');
btnLogin.addEventListener('click', e => {
const email = txtEmail.value;
const senha = txtPassword.value;
const auth = firebase.auth();
const promise = auth.signInWithEmailAndPassword(email, senha);
promise.catch(e => console.log(e.message));
});
firebase.auth().onAuthStateChanged(firebaseUser => {
if (firebaseUser){
console.log(firebaseUser);
}else{
console.log('não estã logado');
}
});
|
Settings.authToken = Assets.getText('apiKey.txt').trim();
Settings.timeout = 120 * 1000;
var Future = Npm.require('fibers/future');
var get = Future.wrap(HTTP.get);
var getBins = function() {
var bins = [];
var binStart = Date.now();
// Setup our bins with their boundaries
// This is all in reverse chrono
_(Settings.numBins).times(function(i) {
var binEnd = binStart - Settings.binWidth.asMilliseconds();
bins[i] = {
start: binStart, // Inclusive
end: binEnd, // Inclusive
urlCount: 0,
noticeCount: 0
};
binStart = binEnd - 1;
});
return bins;
};
var binRequest = function(bin) {
return { url: 'https://www.lumendatabase.org/notices/search',
options: {
headers: {
'X-Authentication-Token': Settings.authToken,
'Accept': 'application/json',
'Content-type': 'application/json',
},
params: {
per_page: 1,
date_received_facet: bin.end + '..' + bin.start
}
}
};
};
var countNoticeUrls = function(notice) {
return _.reduce(notice.works, function(memo, work) {
return memo + (work.infringing_urls ? work.infringing_urls.length : 0);
}, 0);
};
var countBinUrls = function(bin) {
var request = binRequest(bin);
request.options.params.per_page = Settings.perPage;
request.options.timeout = Settings.timeout;
var totalPages = get(request.url, request.options).wait().data.meta.total_pages;
_(totalPages).times(function(i) {
var page = i + 1;
request.options.params.page = page;
request.options.timeout = Settings.timeout;
console.log('Lumen: Fetching url counts (page ' + page + ' of ' + totalPages +
') from ' + new Date(bin.end).toUTCString() + ' to ' +
new Date(bin.start).toUTCString());
var result = get(request.url, request.options).wait();
_.each(result.data.notices, function(notice) {
bin.urlCount += countNoticeUrls(notice);
});
});
return bin.urlCount;
};
var updateLumenCounts = function() {
console.log('Lumen: Fetching notice counts');
var bins = getBins();
var futures = [];
LumenCounts.remove({});
_.each(bins, function(bin) {
var request = binRequest(bin);
request.options.timeout = Settings.timeout;
var future = get(request.url, request.options);
futures.push(future);
var result;
try {
result = future.wait();
} catch (error) {
console.error('Lumen: Fetch error');
console.error(error);
throw new Error(error);
}
bin.noticeCount = result.data.meta.total_entries;
if (Settings.countUrls) {
bin.urlCount = countBinUrls(bin);
}
LumenCounts.insert(bin);
});
Future.wait(futures);
console.log('Lumen: Fetched notice counts');
};
if (Meteor.settings.doJobs) {
// If we don't have any counts or our most recent is older than our update
// interval...
if (LumenCounts.find().count() < Settings.numBins ||
LumenCounts.findOne({}, { sort: { start: -1 } }).start.valueOf() +
Settings.updateEvery.asMilliseconds() < Date.now()) {
Future.task(updateLumenCounts);
} else {
console.log('Lumen: Not updating notice counts');
}
Meteor.setInterval(updateLumenCounts.future(),
Settings.updateEvery.asMilliseconds());
}
Meteor.publish('lumen_counts', function() {
return LumenCounts.find();
});
|
angular.module('bucketList.controllers', ['ionic', 'bucketList.services', 'services', 'directive'])
/**
*
*/
.controller('AppController', function ($rootScope, $scope, $state, AuthService) {
})
/**
* Controller qui permet de faire la connexion de l'utilisateur
* @since 1.0 [Cédric TESNIERE] 26/05/2014 Création de la méthode
*/
.controller('SignInCtrl', function ($rootScope, $state, $http, $scope, API, $window, AuthService) {
AuthService.isAuthorized($state);
$scope.user = {};
$scope.validateUser = function () {
if(!this.user.email || !this.user.password) {
$rootScope.notify("S'il vous plaît entrer les informations d'identification valides.");
return false;
}
$rootScope.show("S'il vous plaît patienter... Authentification");
API.signin({
email: this.user.email,
password: this.user.password
}).success(function (data, status) {
if (data.status != 200) {
$rootScope.hide();
var msg = "Nom d'utilisateur ou mot de passe invalide.";
if (data.msg != null)
msg = data.msg;
$rootScope.notify(msg);
} else {
$rootScope.setUser(data.person);
$rootScope.hide();
$window.location.href = ('#/app/search');
}
}).error(function (data, status) {
$rootScope.notify("Oops quelque chose n'allait pas, veuillez contacter un développeur !");
});
};
$scope.signinWithFaceBook = function() {
//TODO connexion avec facebook
alert("//TODO connexion avec facebook");
};
$scope.signinWithGoogle = function() {
//TODO connexion avec Google
alert("//TODO connexion avec Google");
};
})
/**
* Inscription d'un nouvelle utilisateur
* @since 1.0 [Cédric TESNIERE] 26/05/2014 Création de la méthode
*/
.controller('SignUpCtrl', function ($rootScope, $scope, API, $window, $state, AuthService, CheckData) {
AuthService.isAuthorized($state);
$scope.user = {
email: "",
password: "",
name: ""
};
$scope.createUser = function () {
if(!this.user.password || !CheckData.email(this.user.email) || !CheckData.username(this.user.username)) {
$rootScope.notify("S'il vous plaît entrer des données valides");
return false;
}
$rootScope.show("S'il vous plaît patienter... Enregistrement");
API.signup({
email: this.user.email,
password: this.user.password,
username: this.user.username
}).success(function (data, status) {
if (status != 200) {
var msg = "Erreur lors de l'inscription";
if (data.msg != null)
msg = data.msg;
$rootScope.notify(msg);
} else {
$rootScope.hide();
$rootScope.notify("Inscription effectuée");
$window.location.href = ('#/app/signin');
}
}).error(function (data, status) {
$rootScope.hide();
$rootScope.notify("Oops quelque chose n'allait pas, veuillez contacter un développeur !");
});
}
})
/**
* @since 1.0 [Cédric TESNIERE] 15/06/2014 Création de la méthode
*/
.controller('MyFavorites', function($rootScope, $scope, $state, AuthService, $http, API, $ionicPopup) {
AuthService.isAuthorized($state);
$scope.getAllFavorites = function() {
API.getAllFavorites({
token: AuthService.getUser().api_key
}).success(function (data) {
if (data.status != 200) {
$rootScope.notify("Erreur lors de la récupération des parkings favoris");
} else {
$scope.items = data.parkings;
}
}).error(function (response, status) {
$rootScope.notify("Oops quelque chose n'allait pas, veuillez contacter un développeur !");
}).finally(function() {
// Stop the ion-refresher from spinning
$scope.$broadcast('scroll.refreshComplete');
});
};
$scope.doRefresh = function() {
this.getAllFavorites();
};
$scope.deleteItem = function (id) {
var confirmPopup = $ionicPopup.confirm({
title: 'Suppression',
template: 'Êtes-vous sûr de vouloir le supprimer de vos favoris ?'
});
confirmPopup.then(function(res) {
if (res) {
$rootScope.show("Please wait... Deleting from List");
API.deleteItemFavorites({
id: id,
token: AuthService.getUser().api_key
}).success(function (data, status) {
$rootScope.hide();
$scope.getAllFavorites();
$rootScope.notify("Le parking est supprimer");
}).error(function (data, status) {
$rootScope.hide();
$rootScope.notify("Oops quelque chose n'allait pas, veuillez contacter un développeur !");
});
}
});
};
$scope.shareItem = function (id) {
window.alert("// TODO");
};
$scope.getAllFavorites();
})
/**
* @since 1.0 [Cédric TESNIERE] 15/06/2014 Création de la méthode
*/
.controller('Search' , function($rootScope, $scope, $state, $ionicLoading, $window, API, AuthService) {
AuthService.isAuthorized($state);
$scope.items = null;
$scope.searchAddress = function () {
$ionicLoading.show({
template: 'Chargement ...'
});
if (!!this.address) {
API.addressGeocode(this.address)
.success(function (data, status) {
console.log(data);
$scope.items = data.address;
}).error(function (data, status) {
console.log(data);
$rootScope.notify("Oops quelque chose n'allait pas, veuillez contacter un développeur !");
}).finally(function (data, status) {
$ionicLoading.hide();
});
} else {
$rootScope.notify("Veuillez saisir une adresse");
}
}
$scope.parkingsNearMe = function () {
$rootScope.parkingsFound = null;
$window.location.href = ("#/app/parkingsNearMe");
}
})
/**
*
*/
.controller('MyAccount', function($rootScope, $scope, $state, AuthService, $ionicPopup) {
AuthService.isAuthorized($state);
$scope.user = AuthService.getUser();
$scope.logoutUser = function() {
var confirmPopup = $ionicPopup.confirm({
title: 'Déconnexion',
template: 'Êtes-vous sûr de vouloir vous déconnecter ?'
});
confirmPopup.then(function(res) {
if(res) {
$rootScope.logout();
}
});
};
})
.controller('Historique', function ($rootScope, $scope, $state, API, AuthService) {
AuthService.isAuthorized($state);
$scope.items = [];
$scope.getHistoricalRoute = function() {
API.getHistoricalRoute({
token: AuthService.getUser().api_key
}).success(function (data) {
if (data.status != 200) {
$rootScope.notify("Erreur lors de la récupération des historiques");
} else {
$scope.items = data.historical_route;
}
}).error(function (response, status) {
$rootScope.notify("Oops quelque chose n'allait pas, veuillez contacter un développeur !");
}).finally(function(data, status) {
// Stop the ion-refresher from spinning
$scope.$broadcast('scroll.refreshComplete');
});
};
$scope.doRefresh = function() {
this.getHistoricalRoute();
};
$scope.getHistoricalRoute();
})
/**
*
*/
.controller('AddParkingModal', function($rootScope, $scope, $state, $ionicModal, $ionicLoading, API, AuthService) {
AuthService.isAuthorized($state);
$scope.parking = {
feeSchedule: "",
latitude: "",
longitude: "",
name: "",
nbPlaceMoto: "",
numberPhone: "",
paying: "",
schedule: "",
address: "",
additionalDescription: "",
motorcycleClip: "false"
};
$scope.items = [];
//init the modal
$ionicModal.fromTemplateUrl('modal.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function (modal) {
$scope.modal = modal;
});
// function to open the modal
$scope.chooseAddress = function () {
$scope.modal.show();
};
//Cleanup the modal when we're done with it!
$scope.$on('$destroy', function () {
$scope.modal.remove();
});
$scope.searchAddress = function () {
$ionicLoading.show({
template: 'Chargement ...'
});
if (!!this.address) {
API.addressGeocode(this.address)
.success(function (data, status) {
$scope.items = data.address;
}).error(function (data, status) {
$rootScope.notify("Oops quelque chose n'allait pas, veuillez contacter un développeur !");
}).finally(function (data, status) {
$ionicLoading.hide();
});
} else {
$rootScope.notify("Veuillez saisir une adresse");
}
};
//function to add items to the existing list
$scope.AddAddress = function (address, lat, lng) {
this.parking.address = address;
this.parking.latitude = lat;
this.parking.longitude = lng;
$scope.modal.hide();
};
$scope.saveParking = function () {
if (!!this.parking.name == false) {
$rootScope.notify("Veuillez saisir un nom de parking");
return;
}
if (!!this.parking.address == false) {
$rootScope.notify("Veuillez saisir une adresse");
return;
}
if (this.parking.isPaying && !!this.parking.feeSchedule == false) {
$rootScope.notify("Veuillez préciser les prix");
return;
}
if (!!this.parking.schedule == false) {
$rootScope.notify("Veuillez saisir les horaires");
return;
}
if (!!this.parking.nbPlaceMoto == false) {
$rootScope.notify("Veuillez saisir le nombre de place moto");
return;
}
if (!!this.parking.numberPhone == false) {
$rootScope.notify("Veuillez saisir le numéro de téléphone");
return;
}
console.log(AuthService.getUser().api_key);
API.saveParking({
parking: this.parking,
token: AuthService.getUser().api_key
}).success(function (data, status) {
if (data.status != 200) {
var msg = "Erreur lors de l'enregistrement du parking";
if (data.msg != null)
msg = data.msg;
$rootScope.notify(msg);
} else {
$rootScope.notify("Le parking est enregistré");
}
}).error(function (data, status) {
$rootScope.notify("Oops quelque chose n'allait pas, veuillez contacter un développeur !");
});
}
})
/**
* @since 1.0 [Philippe YUEN] 14/06/2014 Création de la méthode
*/
.controller('startNavigation', function ($rootScope, $scope, API, $timeout, $ionicModal, $window, $stateParams) {
navigator.geolocation.getCurrentPosition(function (position) {
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i);
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
var lat = position.coords.latitude;
var long = position.coords.longitude;
if (isMobile.Android()) {
navigator.app.loadUrl("http://maps.google.com/maps?saddr=" + lat + "," + long + "&daddr=" + $stateParams.destination, { openExternal:true });
} else if (isMobile.iOS()) {
window.location = "maps:saddr=" + lat + "," + long + "&daddr=" + $stateParams.destination;
} else {
$rootScope.notify("Unsupported platform");
}
history.back();
});
})
.controller('listeParkingsCtrl', function ($scope, API) {
API.getAllParkings().success(function (data) {
$scope.parkings = data.parkings
}).error(function(data) {
// TODO Afficher un msg d'erreur
}).finally(function() {
// Stop the ion-refresher from spinning
$scope.$broadcast('scroll.refreshComplete');
});
})
.controller('parkingsNearMeCtrl', function ($rootScope, $scope,$window, $ionicLoading, API) {
$scope.parkings = null;
$scope.info = "";
$scope.lat = "0";
$scope.lng = "0";
$scope.accuracy = "0";
$scope.error = "";
// $scope.goBack = function () {
// $window.location.href = ('#/app/search');
// };
// $scope.openDetail = function (parking) {
// $window.location.href = (");
// };
// $scope.onError = function(error) {
// $scope.$broadcast('scroll.refreshComplete');
// alert("error GPS ");
// // TODO Gerer les différentes erreur
// // https://cordova.apache.org/docs/en/3.0.0/cordova_geolocation_geolocation.md.html#PositionError
// };
// $scope.getParkingByPosition = function (position) {
// alert(position.coords.latitude);
// $scope.lat = position.coords.latitude;
// $scope.lon = position.coords.longitude;
// API.getAllParkingsNearPosition(
// $scope.lat,
// $scope.lon
// ).success(function(data) {
// $rootScope.parkingsFound = data.parkings;
// $rootScope.origin_addresses = data.parkings[0]['origin_addresses'];
// }).error(function(data) {
// $rootScope.notify(data);
// }).finally(function (data) {
// $scope.$broadcast('scroll.refreshComplete');
// });
// };
//
// $scope.currentPosition = function () {
// $scope.info = ("recherche gps ... ");
// navigator.geolocation.getCurrentPosition(
// this.getParkingByPosition,
// this.onError
// )
// };
//
// if (!!$rootScope.parkingsFound == false) {
// $scope.currentPosition();
// }
//
// $scope.doRefresh = function () {
// $scope.currentPosition();
// }
$scope.showPosition = function (position) {
$scope.lat = position.coords.latitude;
$scope.lng = position.coords.longitude;
$scope.accuracy = position.coords.accuracy;
$scope.$apply();
};
$scope.showError = function (error) {
switch (error.code) {
case error.PERMISSION_DENIED:
$scope.error = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
$scope.error = "Location information is unavailable."
break;
case error.TIMEOUT:
$scope.error = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
$scope.error = "An unknown error occurred."
break;
}
$scope.$apply();
};
$scope.getLocation = function () {
if (navigator.geolocation) {
console.log(navigator.geolocation);
navigator.geolocation.getCurrentPosition($scope.showPosition, $scope.showError);
}
else {
$scope.error = "Geolocation is not supported by this browser.";
}
};
$scope.getLocation();
})
.controller('parkingDetailCtrl', function ($rootScope, $scope, $window, API, $ionicTabsDelegate, $stateParams, $ionicModal, AuthService) {
$scope.tab = 0;
$scope.parking = null;
$scope.commentaires = null;
$scope.goBack = function () {
$window.location.href = ('#/app/parkingsNearMe');
};
//init the modal
$ionicModal.fromTemplateUrl('addCommentaire.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function (modal) {
$scope.modal = modal;
});
$scope.getCommentaire = function () {
API.getCommentaireForParking({
id: $stateParams.id
}).success(function (data, status) {
console.log(data);
$scope.commentaires = data.message;
}).error(function (data, status) {
console.log("error");
$rootScope.hide();
$rootScope.notify("Oops quelque chose n'allait pas, veuillez contacter un développeur !");
}).finally(function () {
$scope.$broadcast('scroll.refreshComplete');
});
};
$scope.addCommentaire = function () {
};
$scope.showCommentaire = function () {
$scope.tab = $ionicTabsDelegate.selectedIndex();
$scope.getCommentaire();
console.log("showCommentaire");
};
$scope.showParking = function () {
$scope.tab = $ionicTabsDelegate.selectedIndex();
console.log("showParking");
};
$scope.showHistorique = function () {
$scope.tab = $ionicTabsDelegate.selectedIndex();
console.log("showHistorique");
};
$scope.getParkings = function () {
API.getParking(
$stateParams
).success(function (data, status) {
console.log(data);
$scope.parking = data.parking;
}).error(function (data, status) {
console.log("error");
$rootScope.hide();
$rootScope.notify("Oops quelque chose n'allait pas, veuillez contacter un développeur !");
}).finally(function () {
$scope.$broadcast('scroll.refreshComplete');
});
};
if (!!$rootScope.parkingsFound) {
angular.forEach($rootScope.parkingsFound, function(value) {
if (value.id == $stateParams.id)
$scope.parking = value;
});
// Si on le trouve pas dans parkingFound
if ($scope.parking == null) {
$scope.getParkings();
}
} else {
if ($scope.parking == null) {
$scope.getParkings();
}
}
}); |
function testFunc1() {
alert("Standard type");
}
function testFunc2(a, b, c) {
alert("Function with arguments");
}
var testFunc3 = function() {
var x = 7;
}
(function() {
alert("No name function");
}) |
var Goal = function() {
var defaultHoursPerDay = 8;
var defaultHoursPerWeek = 40;
var hoursPerDay;
var hoursPerWeek;
var dailyChart;
var weeklyChart;
var dailyContainer;
var weeklyContainer;
var weeklyCalculator;
var durationCalculator;
var chartBuilder;
var spans;
var init = function() {
calcInitialHoursPerDay();
calcInitialHoursPerWeek();
buildDependencies();
Chart.platform.disableCSSInjection = true;
build();
gatherComponents();
addBehavior();
registerSettings();
};
var buildDependencies = function() {
durationCalculator = new GoalSpanDurationCalculator();
weeklyCalculator = new GoalWeeklyCalculator(durationCalculator);
chartBuilder = new GoalPieChartBuilder();
};
var build = function() {
jQuery('#Goal').html(GoalTemplate);
dailyChart = chartBuilder.build('GoalTodayChart', '#5bdd81', '#e7f9ec');
weeklyChart = chartBuilder.build('GoalWeeklyChart', '#2982db', '#f3f9ff');
};
var gatherComponents = function() {
dailyContainer = jQuery('#GoalToday');
weeklyContainer = jQuery('#GoalWeekly');
};
var addBehavior = function() {
App.dispatcher.subscribe('DATE_CHANGED', onDateChanged);
App.dispatcher.subscribe('SPAN_SAVED', onSpanSaved);
App.dispatcher.subscribe('SPAN_DELETED', onSpanDeleted);
};
var onSpanSaved = function(data) {
spans = data.record.spans;
updateProgress();
};
var onSpanDeleted = function(data) {
spans = data.spans
updateProgress();
};
var onDateChanged = function(record) {
spans = record.spans;
updateProgress();
};
var updateProgress = function() {
var dailyHours = durationCalculator.calcHours(spans);
updateChart(dailyChart, dailyHours, hoursPerDay);
updateChartNumbers(dailyContainer, dailyHours, hoursPerDay);
var weeklyHours = weeklyCalculator.getTotal();
updateChart(weeklyChart, weeklyHours, hoursPerWeek);
updateChartNumbers(weeklyContainer, weeklyHours, hoursPerWeek);
};
var updateChartNumbers = function(container, value, goal) {
var hours = Number.parseFloat(value).toFixed(2);
var remaining = Number.parseFloat(goal - hours).toFixed(2);
if (remaining < 0)
remaining = 0;
var percent = Math.round((value/goal)*100);
container.find('.hour_value').text(hours);
container.find('.percent_value').text(percent);
container.find('.hours_remaining').text(remaining);
};
var updateChart = function(chart, value, goal) {
var percent = calcMaxPercent(value/goal);
chart.data.datasets[0].data = [
percent, 100-percent
];
chart.update();
};
var calcMaxPercent = function(ratio) {
var percent = Math.round(ratio*100);
if (percent > 100)
percent = 100;
return percent;
};
var calcInitialHoursPerDay = function() {
var savedValue = parseInt(localStorage.getItem('goal_hours_day'));
if (isNaN(savedValue))
hoursPerDay = defaultHoursPerDay;
else
hoursPerDay = savedValue;
};
var calcInitialHoursPerWeek = function() {
var savedValue = parseInt(localStorage.getItem('goal_hours_week'));
if (isNaN(savedValue))
hoursPerWeek = defaultHoursPerWeek;
else
hoursPerWeek = savedValue;
};
var onHoursPerDayChange = function(newValue) {
hoursPerDay = newValue;
localStorage.setItem('goal_hours_day', newValue);
updateProgress();
};
var onHoursPerWeekChange = function(newValue) {
hoursPerWeek = newValue;
localStorage.setItem('goal_hours_week', newValue);
updateProgress();
};
var registerSettings = function() {
App.settings.register([{
section:'Goal',
label:'Hours per day',
value:hoursPerDay,
type:'integer',
callback:onHoursPerDayChange
},{
section:'Goal',
label:'Hours per week',
value:hoursPerWeek,
type:'integer',
callback:onHoursPerWeekChange
}]);
};
init();
};
|
c: {
a();
switch (1) {
case 2:
b();
if (a) break c;
for (var b = 3; b < 4; b++) {
if (b > 5) break; // this break refers to the for, not to the switch; thus it
// shouldn't ruin our optimization
d.e(b);
}
f();
case 6+7:
g();
break;
default:
h();
}
} |
function subtract() {
let num1 = document.getElementById('firstNumber').value;
let num2 = document.getElementById('secondNumber').value;
let subtract = document.getElementById('result');
subtract.textContent = Number(num1) - Number(num2);
} |
;(function($, undefined) {
$.fn.convenience_store = function(brand_name, options) {
var brands = $.fn.convenience_store.available_brands;
if(brand_name === undefined || brand_name == '' || (brands.indexOf(brand_name) == -1)) return;
return this.each(function() {
$.fn.convenience_store.style($(this), brand_name);
});
};
$.fn.convenience_store.available_brands = ['seveneleven', 'familymart', 'lawson', 'owson'];
$.fn.convenience_store.load_font = function(font) {
WebFontConfig = {
google: { families: [ font ] }
};
(function() {
var wf = document.createElement('script');
wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
'://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
})();
}
$.fn.convenience_store.style = function($this, brand_name) {
var title = $this.html();
// ============
// SEVEN ELEVEN
// ============
if(brand_name == 'seveneleven') {
$.fn.convenience_store.load_font("Oswald:700:latin");
$this.css({
"background-color": "#fff",
"position": "relative"
}).html('');
var p = 5;
var m = 5;
var style1 = {
"background-color": "#f60",
"position": "relative",
"top": "0",
"margin-bottom": m + "px"
};
var style2 = {
"background-color": "#008837",
"position": "relative",
"top": "0",
"margin-bottom": m + "px"
};
var style3 = {
"background-color": "#f00",
"position": "relative",
"top": "0",
};
var style_title = {
"background-color": "#fff",
"color": "#f00",
"font-family": "Oswald",
"font-style": "normal",
"font-weight": "bold",
"left": "2%",
"letter-spacing": "-0.01em",
"line-height": "1.2",
"padding": p + "px 1.5%",
"position": "absolute",
"text-transform": "uppercase",
"top": "0"
};
var $line1 = $('<div>').css(style1);
var $line2 = $('<div>').css(style2);
var $line3 = $('<div>').css(style3);
$title = $('<div>').css(style_title).html(title);
$this.append($line1, $line2, $line3, $title);
var h_ttl_int = $title.height()*3/4;
var h = (h_ttl_int + p*2 - m*3)/3 + 'px';
$title.css({'height': h_ttl_int + 'px', 'font-size': (h_ttl_int*4/5) + 'px'});
$line1.css('height', h);
$line2.css('height', h);
$line3.css('height', h);
}
// ==========
// FamilyMart
// ==========
else if(brand_name == 'familymart') {
$.fn.convenience_store.load_font("PT+Sans:700:latin");
$this.css({
"background-color": "#fff",
"line-height": "1.0",
"overflow": "hidden"
}).html('');
var p = 5;
var style_title = {
"color": "#018bd4",
"display": "inline-block",
"font-family": "PT Sans",
"font-style": "normal",
"font-weight": "bold",
"left": "2%",
"padding": "6px 0.1% 0",
"text-transform": "capitalize"
};
$title = $('<div>').css(style_title).html(title);
$this.append($title);
$title.css({"position": "relative", "top": "0px"});
var h = ($title.height() + p*2)/8;
$this.css('border-top', 'solid ' + (h*3) + 'px #00a040');
$this.css('border-bottom', 'solid ' + (h) + 'px #00a040');
}
// ===============
// LAWSON or OWSON
// ===============
else if(brand_name == 'lawson' || brand_name == 'owson') {
$.fn.convenience_store.load_font("Graduate"); // 'Kameron:700', 'Podkova:700', 'Noticia+Text:700', 'Crete+Round', 'Kreon:700', 'Maiden+Orange::latin','Smokum::latin', 'Bevan::latin', 'Wellfleet::latin'
$this.css({
"background-color": "#1c7dc2",
"line-height": "1.0",
"padding": "7px 0 7px",
"position": "relative"
}).html('');
var style = {
"border-top": "solid 3px #fff",
"background-color": "#e74c98",
"display": "block",
"height": "8px",
"width": "100%"
};
var style_title = {
"border-top": "solid 3px #fff",
"border-bottom": "solid 3px #fff",
"color": "#fff",
"display": "block",
"font-family": "Graduate", // Kameron, Podkova, Noticia Text, Crete Round, Kreon, Maiden Orange
"font-style": "normal",
"font-weight": "bold",
"left": "2%",
"letter-spacing": "0",
"padding": "6px 1% 16px",
"text-transform": "uppercase"
};
var $line = $('<div>').css(style);
$title = $('<div>').css(style_title).html(title);
$this.append($title, $line);
$line.css({"bottom": "10px", "position": "absolute"});
}
}
})(jQuery);
|
const releases = require('../data/releases.json')
module.exports = (req, res) => {
const context = Object.assign(req.context, {
releases: releases
})
res.render('releases', context)
}
|
// sections model
// - we get passed the list of questions and then we generate the sections
define(function (require) {
"use strict";
var $ = require('jquery'),
Backbone = require('backbone'),
Questions = require('./questions.js')
var Section = Backbone.Model.extend({
questions: null,
title: 'Section',
order: 0
});
var Sections = Backbone.Collection.extend({
model: Section,
initialize: function(questions){
this.gqs = questions.groupBy('area')
console.log(this.gqs)
},
});
return Sections;
});
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var mongoosePaginate = require('mongoose-paginate');
/**
* Article Schema
*/
var CategorySchema = new Schema({
created: {
type: Date,
default: Date.now
},
title: {
type: String,
default: '',
trim: true,
required: 'Title cannot be blank'
},
link: {
type: String,
default: '',
trim: true
},
sourceImage: {
type: String,
default: '',
trim: true
},
sourceName: {
type: String,
default: '',
trim: true
},
// items: [{type: Schema.Types.ObjectId,ref: 'Item'}]
// user: {
// type: Schema.ObjectId,
// ref: 'User'
// }
});
CategorySchema.plugin(mongoosePaginate);
mongoose.model('Category', CategorySchema);
|
/*
Copyright (c) 2017 Andre Santos
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
(function () {
"use strict";
var views = window.App.Views;
views.ProgressBoard = views.BaseView.extend({
id: "progress-board",
navigateOptions: { trigger: true, replace: true },
events: {
"click .clickable.panel": "abortMission",
"touchstart .clickable.panel": "abortMission"
},
initialize: function (options) {
this.router = options.router;
},
render: function () {
if (!this.visible) return this;
return this;
},
build: function () {
return this;
},
abortMission: function () {
this.model.abortMission();
this.hide();
}
});
})(); |
define([
'underscore',
'backbone'
], function(_, Backbone){
var AboutmeModel = Backbone.Model.extend({
urlRoot: '/static/js/data/data-aboutme.json',
initialize: function(){
}
});
return AboutmeModel;
}); |
function showSuccessTip(tip,url) {
swal({
title: tip || '操作成功!',
text: '',
type: "success",
timer: 800,
confirmButtonText: "关闭"
},function () {
if(url){
location.href = url
}
});
}
// 显示操作失败提示,不会自动关闭
function showFailTip(tip) {
swal({
title: tip||'操作失败!',
text: '',
type: "error",
confirmButtonText: "关闭"
});
}
function showInfoTip(tip) {
swal({
title: tip,
text: '',
type: "info",
timer: 800,
confirmButtonText: "关闭"
});
}
function deleteObj(href,nextUrl) {
swal({
title: "确认是否删除?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "确认",
cancelButtonText:'取消',
closeOnConfirm: false
},
function(){
swal.close();
$.ajax(href,{'method':'DELETE'}).then(function () {
location.href = nextUrl;
});
});
}
function request(url,nextUrl) {
$.ajax(url,{'method':'POST'}).then(function () {
showSuccessTip('',nextUrl);
});
}
// 绑定编辑器
function bindEditor(id) {
window.setTimeout(function() {
editor = KindEditor.create('#' + id, {
width : '680px',
height : '300px',
items : [ 'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',
'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright', 'justifyfull', 'insertorderedlist',
'insertunorderedlist', 'indent', 'outdent', 'subscript', 'superscript', 'clearhtml', 'quickformat', 'selectall', '|',
'fullscreen', '/', 'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons',
'baidumap', 'pagebreak', 'anchor', 'link', 'unlink' ],
uploadJson : '/file/upload',
fileManagerJson : '/file/fileManage',
allowFileManager : true
});
}, 1);
}
// 绑定上传按钮,上传单个或多个文件,默认上传多个,如上传单个,设置multi=false
function bindUploadbutton(dir,btnId,infoId,valueId,multi) {
if(btnId == true || btnId == false){// 参数后移处理,调用时方便省略参数
valueId = multi;
multi = btnId;
btnId = infoId;
infoId = valueId;
}
btnId = btnId || 'uploadButton';
infoId = infoId || 'attachmentInfo';
valueId = valueId || 'attachment';
if(multi == false){// 上传单个
var type = 'file';
if(tagName(infoId) == 'IMG'){
type = 'image';
}
window.setTimeout(function() {
var uploadBtn = KindEditor.uploadbutton({
button : $('#' + btnId),
url : '/file/upload?type=' + type + '&dir=' + dir,
afterUpload : function(data) {
if (data.error === 0) {
$('#' + valueId).val(data.url);
var info = $('#' + infoId);
if(info){
var tagName = info.prop('tagName');
if(tagName == 'A'){// 比如检测项目testproject上传原始记录模板后显示
info.attr('href','' + data.url);
info.html(data.name);
}else if(tagName == 'IMG'){// 比如user管理上传签名图片后显示图片
info.attr('src','' + data.url);
}
}
} else {
showFailTip(data.message);
}
},
afterError : function(str) {
showFailTip('错误: ' + str);
}
});
uploadBtn.fileBox.change(function(e) {
uploadBtn.submit();
});
}, 1);
}else{
window.setTimeout(function() {
var uploadBtn = KindEditor.uploadbutton({
button : $('#' + btnId),
url : '/file/upload?type=file&dir=' + dir,
afterUpload : function(data) {
if (data.error === 0) {
$('#' + infoId).append('<div class="inline-block"><a href="' + data.url+ '" class="span4" target="_blank">'
+ data.name + '</a><input type="button" value="删除" onclick="removeObj(this,\'' + infoId + '\',\'' + valueId + '\')"></div>');
mergeUploadInfo(infoId,valueId);
} else {
showFailTip(data.message);
}
},
afterError : function(str) {
showFailTip('错误: ' + str);
}
});
uploadBtn.fileBox.change(function(e) {
uploadBtn.submit();
});
}, 1);
}
}
// 获取元素的标签名称,比如div,a,img等
function tagName(id) {
var info = $('#' + id);
if(info){
return info.prop('tagName');
}
}
// 将上传的附件信息设置到valueId对应的字段,类似:/aaa.jpg,/bbb.jpg
function mergeUploadInfo(infoId,valueId) {
var urls = '';
$('#' + infoId).find('a').each(function(){
urls += $(this).attr('href') + ',';
});
urls = urls.substr(0,urls.length-1);
$('#' + valueId).val(urls);
}
// form表单提交时按需检查是否已上传附件
function existAttachments(valueId) {
valueId = valueId || 'attachment';
if($('#' + valueId).val() == ''){
showInfoTip('请上传附件!');
return false;
}
return true;
}
// 显示上传的附件信息到infoId对应的div中
function showAttachments(infos,canDelete,infoId,valueId) {
infoId = infoId || 'attachmentInfo';
valueId = valueId || 'attachment';
var valueDiv = $('#' + valueId);
if(valueDiv){
valueDiv.val(infos);
}
if(!infos){
return;
}
var arr = infos.split(',');
var frag;
for(var i in arr){
frag = '<div class="inline-block"><a href="' + arr[i]+ '" class="span4" target="_blank">' + arr[i].substr(arr[i].lastIndexOf('/') + 1) + '</a>';
if(canDelete){
frag += '<input type="button" value="删除" onclick="removeObj(this,\'' + infoId + '\',\'' + valueId + '\')">';
}
frag += '</div>';
$('#' + infoId).append(frag);
}
}
function removeObj(obj,infoId,valueId){
$(obj).parent().remove();
mergeUploadInfo(infoId,valueId);
} |
import {Provider} from 'react-redux';
import store from './src/redux/store';
import AppViewContainer from './src/modules/AppViewContainer';
import React from 'react';
import {AppRegistry} from 'react-native';
const Mojifi = React.createClass({
render() {
return (
<Provider store={store}>
<AppViewContainer />
</Provider>
);
}
});
AppRegistry.registerComponent('Mojifi', () => Mojifi);
|
var NavbarController = function($scope){
var _this = this;
this.type = function(){
if($scope.static != null && $scope.static == true){
return 'navbar-static-top';
}
else{
return 'navbar-fixed-top';
}
}
$scope.classes = function(){
var result = [];
result.push(_this.type());
return result;
}
}
|
import renderWrapper from './renderWrapper';
export default renderWrapper();
|
import React, { useState } from 'react';
import ReactNodeGraph from '../index';
const exampleGraph = {
"nodes":[
{"nid":1,"type":"WebGLRenderer","x":1479,"y":351,"fields":{"in":[{"name":"width"},{"name":"height"},{"name":"scene"},{"name":"camera"},{"name":"bg_color"},{"name":"postfx"},{"name":"shadowCameraNear"},{"name":"shadowCameraFar"},{"name":"shadowMapWidth"},{"name":"shadowMapHeight"},{"name":"shadowMapEnabled"},{"name":"shadowMapSoft"}],"out":[]}},
{"nid":14,"type":"Camera","x":549,"y":478,"fields":{"in":[{"name":"fov"},{"name":"aspect"},{"name":"near"},{"name":"far"},{"name":"position"},{"name":"target"},{"name":"useTarget"}],"out":[{"name":"out"}]}},
{"nid":23,"type":"Scene","x":1216,"y":217,"fields":{"in":[{"name":"children"},{"name":"position"},{"name":"rotation"},{"name":"scale"},{"name":"doubleSided"},{"name":"visible"},{"name":"castShadow"},{"name":"receiveShadow"}],"out":[{"name":"out"}]}},
{"nid":35,"type":"Merge","x":948,"y":217,"fields":{"in":[{"name":"in0"},{"name":"in1"},{"name":"in2"},{"name":"in3"},{"name":"in4"},{"name":"in5"}],"out":[{"name":"out"}]}},
{"nid":45,"type":"Color","x":950,"y":484,"fields":{"in":[{"name":"rgb"},{"name":"r"},{"name":"g"},{"name":"b"}],"out":[{"name":"rgb"},{"name":"r"},{"name":"g"},{"name":"b"}]}},
{"nid":55,"type":"Vector3","x":279,"y":503,"fields":{"in":[{"name":"xyz"},{"name":"x"},{"name":"y"},{"name":"z"}],"out":[{"name":"xyz"},{"name":"x"},{"name":"y"},{"name":"z"}]}},
{"nid":65,"type":"ThreeMesh","x":707,"y":192,"fields":{"in":[{"name":"children"},{"name":"position"},{"name":"rotation"},{"name":"scale"},{"name":"doubleSided"},{"name":"visible"},{"name":"castShadow"},{"name":"receiveShadow"},{"name":"geometry"},{"name":"material"},{"name":"overdraw"}],"out":[{"name":"out"}]}},
{"nid":79,"type":"Timer","x":89,"y":82,"fields":{"in":[{"name":"reset"},{"name":"pause"},{"name":"max"}],"out":[{"name":"out"}]}},
{"nid":84,"type":"MathMult","x":284,"y":82,"fields":{"in":[{"name":"in"},{"name":"factor"}],"out":[{"name":"out"}]}},
{"nid":89,"type":"Vector3","x":486,"y":188,"fields":{"in":[{"name":"xyz"},{"name":"x"},{"name":"y"},{"name":"z"}],"out":[{"name":"xyz"},{"name":"x"},{"name":"y"},{"name":"z"}]}}
],
"connections":[
{"from_node":23,"from":"out","to_node":1,"to":"scene"},
{"from_node":14,"from":"out","to_node":1,"to":"camera"},
{"from_node":14,"from":"out","to_node":35,"to":"in5"},
{"from_node":35,"from":"out","to_node":23,"to":"children"},
{"from_node":45,"from":"rgb","to_node":1,"to":"bg_color"},
{"from_node":55,"from":"xyz","to_node":14,"to":"position"},
{"from_node":65,"from":"out","to_node":35,"to":"in0"},
{"from_node":79,"from":"out","to_node":84,"to":"in"},
{"from_node":89,"from":"xyz","to_node":65,"to":"rotation"},
{"from_node":84,"from":"out","to_node":89,"to":"y"}
]
};
export const App = () => {
const [state, setState] = useState(exampleGraph);
const onNewConnector = (fromNode, fromPin, toNode, toPin) => {
let connections = [...state.connections, {
from_node: fromNode,
from: fromPin,
to_node: toNode,
to: toPin
}];
console.log({...state, ...connections});
setState(old => {
return {
...old,
"connections": connections
}
});
}
const onRemoveConnector = (connector) => {
let connections = [...state.connections];
connections = connections.filter(connection => {
return connection !== connector;
});
setState(old => {
return {
...old,
"connections": connections
}
});
}
const onNodeMove = (nid, pos) => {
console.log(`end move:`, nid, pos);
}
const onNodeStartMove = nid => {
console.log(`start move:`, nid);
}
const handleNodeSelect = nid => {
console.log(`node selected:`, nid);
}
const handleNodeDeselect = nid => {
console.log(`node deselected:`, nid);
}
return <ReactNodeGraph
data={state}
onNodeMove={(nid, pos) => onNodeMove(nid, pos)}
onNodeStartMove={nid => onNodeStartMove(nid)}
onNewConnector={(n1, o, n2, i) => onNewConnector(n1, o, n2, i)}
onRemoveConnector={connector => onRemoveConnector(connector)}
onNodeSelect={nid => handleNodeSelect(nid)}
onNodeDeselect={nid => handleNodeDeselect(nid)}
/>;
}
export default App; |
class Foo {}
export default new Foo();
|
/**
/* Script name : config.js
/* Description : Configuration file
/* Author : Redek Project
**/
'use strict';
// CONFIGURATIONS VARIABLES
// ----------------------------------------------------------------------------
let initialConfig = {
showDebug: true,
userModelName: 'User',
defaultRoleUser: {
name: 'superadmin',
description: 'Role having all access and no restrictions (Provider : loopback-boot-create-access-token).',
user: {
username: 'DeveloperAdmin',
email: 'developer.admin@domain.com',
emailVerified: true,
password: '@dminD€v'
}
}
};
// CONFIGURATIONS METHODS
// ----------------------------------------------------------------------------
/**
* Get create access token configurations.
* @returns {initialConfig}
*/
let get = () => {
return initialConfig;
}
/**
* Set new create access token configurations.
* @param {initialConfig} config
*/
let set = (config) => {
initialConfig = Object.assign(initialConfig, config);
}
// EXPORTS
// ----------------------------------------------------------------------------
module.exports = {
initialConfig,
get,
set
} |
$(document).ready(function(){
$(document).unbind('rebind.showdown.gui');
$(document).bind('rebind.showdown.gui', function() {
startGui();
})
$(document).trigger('rebind.showdown.gui');
}) |
var connect = require('connect');
var static = require('serve-static');
var compression = require('compression');
function filter(req, res) {
var type = res.getHeader('Content-Type') || '';
console.log(type);
return type.match(/json|text|javascript|css/);
}
var app = connect()
.use(compression({ threshold: 0, filter: filter }))
.use(static(__dirname + '/public'))
.use(function (req, res, next) {
res.end('hello\n');
})
.listen(3000);
|
"use strict";
const SunUtils = require("../../../lib/time/SunUtils");
describe("SunUtils", () => {
it("should be exported", () => {
expect(typeof SunUtils).toEqual("object");
});
describe("sunrise angle constant", () => {
it("should be exported", () => {
expect(typeof SunUtils.SUNRISE_ANGLE).toEqual("number");
});
});
describe("sunset angle constant", () => {
it("should be exported", () => {
expect(typeof SunUtils.SUNSET_ANGLE).toEqual("number");
});
});
describe("date and latitude initializer", () => {
it("should be exported", () => {
expect(typeof SunUtils.init).toEqual("function");
});
it("should return the initialized functions", () => {
const initedUtils = SunUtils.init(1, 1);
expect(typeof initedUtils.computeMidday).toEqual("function");
expect(typeof initedUtils.computeMidnight).toEqual("function");
expect(typeof initedUtils.computeTime).toEqual("function");
expect(typeof initedUtils.computeAsr).toEqual("function");
const doCompute = () => {
const initedMidday = initedUtils.computeMidday(1);
const initedMidnight = initedUtils.computeMidnight();
const initedTime = initedUtils.computeTime(1, 1);
const initedAsr = initedUtils.computeAsr(1, 1);
expect(typeof initedMidday).toEqual("number");
expect(typeof initedMidnight).toEqual("number");
expect(typeof initedTime).toEqual("number");
expect(typeof initedAsr).toEqual("number");
}
expect(doCompute).not.toThrowError();
});
});
});
|
var optionsApp = angular.module('twBlockchain', ['ngRoute','kcd.directives','datatables'])
optionsApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/receipts', {
templateUrl: 'partial_receipts.html',
controller: 'ReceiptsController'
}).
when('/protected', {
templateUrl: 'partial_protects.html',
controller: 'ProtectedController'
}).
when('/add-protection', {
templateUrl: 'partial_add_protection.html',
controller: 'AddProtectionController'
}).
otherwise({
redirectTo: '/receipts'
});
}]);
optionsApp.factory('StorageService', function() {
var storage = new ExtensionStorage();
return storage;
});
optionsApp.controller('ReceiptsController', ['StorageService', '$scope', function(StorageService, $scope) {
$scope.currentPage = 0;
$scope.pages = [];
$scope.data = {
search: ''
};
var originalDataset = null;
const amount = 50;
StorageService.getLocal("blockingReceipts",function(items) {
var dataset = [];
for(var username in items.blockingReceipts) {
var receipt = items.blockingReceipts[username];
receipt.username = username;
dataset.push( receipt );
}
originalDataset = dataset;
$scope.receipts = dataset;
sliceReceipts();
makePageArray();
$scope.$apply();
});
$scope.setPage = setPage;
$scope.getNumOfPages = getNumOfPages;
$scope.$watch('data.search', function() {
if (originalDataset) {
filterDataset();
sliceReceipts();
makePageArray();
}
});
function filterDataset() {
$scope.receipts = originalDataset.filter((item) => {
return item.username.toLowerCase().indexOf($scope.data.search.toLowerCase()) > -1
|| item.connection.toLowerCase().indexOf($scope.data.search.toLowerCase()) > -1;
});
}
function sliceReceipts() {
$scope.slicedReceipts = $scope.receipts.slice($scope.currentPage * amount, ($scope.currentPage + 1) * amount);
}
function getNumOfPages() {
return Math.floor($scope.receipts.length / amount) + 1;
}
function makePageArray() {
$scope.pages = [];
for (var i = 0; i < getNumOfPages(); i++) {
$scope.pages.push(i);
}
}
function setPage(num) {
if (num >= 0 && num < getNumOfPages())
$scope.currentPage = num;
sliceReceipts();
}
}]);
optionsApp.controller('ProtectedController', ['StorageService', '$scope', function(StorageService, $scope) {
$scope.should = {};
$scope.should.refreshTable = false;
StorageService.getSync("protectedUsers",function(items) {
$scope.protectedUsers=[];
for(var username in items.protectedUsers) {
$scope.protectedUsers.push(items.protectedUsers[username]);
}
$scope.should.refreshTable = true;
$scope.$apply();
});
$scope.deleteProtection = function(user) {
var response = confirm("Are you sure you want to remove "+user.username+" from the protected users list?");
if (!response)
return;
StorageService.getSync("protectedUsers",function(items) {
if (typeof items.protectedUsers === "undefined") {
items.protectedUsers = {};
}
delete items.protectedUsers[user.username];
StorageService.setSync({ protectedUsers: items.protectedUsers }, function() {
$scope.protectedUsers = items.protectedUsers;
$scope.should.refreshTable = true;
$scope.$apply();
});
});
}
}]);
optionsApp.controller('AddProtectionController', ['StorageService', '$scope', '$location', function(StorageService, $scope, $location) {
$scope.user = {username: "", on: Date.now()};
$scope.error = false;
$scope.submit = function() {
$scope.error = false;
if ($scope.user.username == "" || !$scope.user.username) {
$scope.error = "You must enter a username";
return;
}
StorageService.getSync("protectedUsers",function(items) {
if (typeof items.protectedUsers === "undefined") {
items.protectedUsers = {};
}
items.protectedUsers[$scope.user.username] = $scope.user;
StorageService.setSync({ protectedUsers: items.protectedUsers }, function() {
$location.url('/protected');
$scope.$apply();
});
});
};
}]);
optionsApp.controller('NavigationController', ['$scope', '$location', function($scope, $location) {
$scope.isActive = function(path) {
return ($location.url().indexOf(path) > -1);
}
}]);
angular.module('kcd.directives',[]).directive('kcdRecompile', function($compile, $parse) {
'use strict';
return {
scope: true, // required to be able to clear watchers safely
compile: function(el) {
var template = el.html();
return function link(scope, $el, attrs) {
scope.$parent.$watch(attrs.kcdRecompile, function(_new, _old) {
var useBoolean = attrs.hasOwnProperty('useBoolean');
if ((useBoolean && (!_new || _new === 'false')) || (!useBoolean && (!_new || _new === _old))) {
return;
}
// remove all watchers because the recompiled version will set them up again.
removeChildrenWatchers($el);
// reset kcdRecompile to false if we're using a boolean
if (useBoolean) {
$parse(attrs.kcdRecompile).assign(scope.$parent, false);
}
// recompile
var newEl = $compile(template)(scope.$parent.$new());
$el.html(newEl);
});
};
}
};
function removeChildrenWatchers(element) {
angular.forEach(element.children(), function(childElement) {
removeAllWatchers(angular.element(childElement));
});
}
function removeAllWatchers(element) {
if (element.data().hasOwnProperty('$scope')) {
element.data().$scope.$$watchers = [];
}
removeChildrenWatchers(element);
}
}); |
import MarkdownIt from 'markdown-it'
const handlePlugin = (plugin) => plugin.default || plugin
export default ({ app }, inject) => {
<%
const preset = options.preset || 'default'
delete options.preset
const plugins = options.use || []
delete options.use
options = serialize(options)
options = options === '{}' ? undefined : options
%>
const md = new MarkdownIt('<%= preset %>', <%= options %>)
<%
for (config of plugins) {
const hasOpts = Array.isArray(config);
const plugin = hasOpts ? config.shift(): config
const opts = hasOpts ? config : []
%>
md.use(handlePlugin(require('<%= plugin %>'))<% for(opt of opts) { %>, <%= serialize(opt) %> <% } %>)
<% } %>
inject('md', md)
}
|
var path = require('path'),
rootPath = path.normalize(__dirname + '/..'),
env = process.env.NODE_ENV || 'development';
var config = {
development: {
root: rootPath,
app: {
name: 'kiosk-node-service'
},
port: 3000,
db: 'mysql://localhost/kiosk-node-service-development'
},
test: {
root: rootPath,
app: {
name: 'kiosk-node-service'
},
port: 3000,
db: 'mysql://localhost/kiosk-node-service-test'
},
production: {
root: rootPath,
app: {
name: 'kiosk-node-service'
},
port: 3000,
db: 'mysql://localhost/kiosk-node-service-production'
}
};
module.exports = config[env];
|
Ext.define('sisprod.model.ActivityOtModel', {
extend: 'Ext.data.Model',
require: [
'Ext.data.Model'
],
fields:[
{name: 'idActivityOt', type: 'int', visible: false}, // Ext.data.Types.FLOAT
{name: 'description', type: 'string', visible: true}
],
idProperty: 'idActivityOt'
}); |
//artificial intelligence class
//handles AI decision-making by means of sensor input from entity body (which should contain sensory fixtures)
ig.module('game.AI')
.requires('game.entities.physEnt').
defines( function() {
ig.AI = ig.Class.extend({
});
}); |
/* Tabulator v4.8.3 (c) Oliver Folkerd */
var MoveColumns = function MoveColumns(table) {
this.table = table; //hold Tabulator object
this.placeholderElement = this.createPlaceholderElement();
this.hoverElement = false; //floating column header element
this.checkTimeout = false; //click check timeout holder
this.checkPeriod = 250; //period to wait on mousedown to consider this a move and not a click
this.moving = false; //currently moving column
this.toCol = false; //destination column
this.toColAfter = false; //position of moving column relative to the desitnation column
this.startX = 0; //starting position within header element
this.autoScrollMargin = 40; //auto scroll on edge when within margin
this.autoScrollStep = 5; //auto scroll distance in pixels
this.autoScrollTimeout = false; //auto scroll timeout
this.touchMove = false;
this.moveHover = this.moveHover.bind(this);
this.endMove = this.endMove.bind(this);
};
MoveColumns.prototype.createPlaceholderElement = function () {
var el = document.createElement("div");
el.classList.add("tabulator-col");
el.classList.add("tabulator-col-placeholder");
return el;
};
MoveColumns.prototype.initializeColumn = function (column) {
var self = this,
config = {},
colEl;
if (!column.modules.frozen) {
colEl = column.getElement();
config.mousemove = function (e) {
if (column.parent === self.moving.parent) {
if ((self.touchMove ? e.touches[0].pageX : e.pageX) - Tabulator.prototype.helpers.elOffset(colEl).left + self.table.columnManager.element.scrollLeft > column.getWidth() / 2) {
if (self.toCol !== column || !self.toColAfter) {
colEl.parentNode.insertBefore(self.placeholderElement, colEl.nextSibling);
self.moveColumn(column, true);
}
} else {
if (self.toCol !== column || self.toColAfter) {
colEl.parentNode.insertBefore(self.placeholderElement, colEl);
self.moveColumn(column, false);
}
}
}
}.bind(self);
colEl.addEventListener("mousedown", function (e) {
self.touchMove = false;
if (e.which === 1) {
self.checkTimeout = setTimeout(function () {
self.startMove(e, column);
}, self.checkPeriod);
}
});
colEl.addEventListener("mouseup", function (e) {
if (e.which === 1) {
if (self.checkTimeout) {
clearTimeout(self.checkTimeout);
}
}
});
self.bindTouchEvents(column);
}
column.modules.moveColumn = config;
};
MoveColumns.prototype.bindTouchEvents = function (column) {
var self = this,
colEl = column.getElement(),
startXMove = false,
//shifting center position of the cell
dir = false,
currentCol,
nextCol,
prevCol,
nextColWidth,
prevColWidth,
nextColWidthLast,
prevColWidthLast;
colEl.addEventListener("touchstart", function (e) {
self.checkTimeout = setTimeout(function () {
self.touchMove = true;
currentCol = column;
nextCol = column.nextColumn();
nextColWidth = nextCol ? nextCol.getWidth() / 2 : 0;
prevCol = column.prevColumn();
prevColWidth = prevCol ? prevCol.getWidth() / 2 : 0;
nextColWidthLast = 0;
prevColWidthLast = 0;
startXMove = false;
self.startMove(e, column);
}, self.checkPeriod);
}, { passive: true });
colEl.addEventListener("touchmove", function (e) {
var halfCol, diff, moveToCol;
if (self.moving) {
self.moveHover(e);
if (!startXMove) {
startXMove = e.touches[0].pageX;
}
diff = e.touches[0].pageX - startXMove;
if (diff > 0) {
if (nextCol && diff - nextColWidthLast > nextColWidth) {
moveToCol = nextCol;
if (moveToCol !== column) {
startXMove = e.touches[0].pageX;
moveToCol.getElement().parentNode.insertBefore(self.placeholderElement, moveToCol.getElement().nextSibling);
self.moveColumn(moveToCol, true);
}
}
} else {
if (prevCol && -diff - prevColWidthLast > prevColWidth) {
moveToCol = prevCol;
if (moveToCol !== column) {
startXMove = e.touches[0].pageX;
moveToCol.getElement().parentNode.insertBefore(self.placeholderElement, moveToCol.getElement());
self.moveColumn(moveToCol, false);
}
}
}
if (moveToCol) {
currentCol = moveToCol;
nextCol = moveToCol.nextColumn();
nextColWidthLast = nextColWidth;
nextColWidth = nextCol ? nextCol.getWidth() / 2 : 0;
prevCol = moveToCol.prevColumn();
prevColWidthLast = prevColWidth;
prevColWidth = prevCol ? prevCol.getWidth() / 2 : 0;
}
}
}, { passive: true });
colEl.addEventListener("touchend", function (e) {
if (self.checkTimeout) {
clearTimeout(self.checkTimeout);
}
if (self.moving) {
self.endMove(e);
}
});
};
MoveColumns.prototype.startMove = function (e, column) {
var element = column.getElement();
this.moving = column;
this.startX = (this.touchMove ? e.touches[0].pageX : e.pageX) - Tabulator.prototype.helpers.elOffset(element).left;
this.table.element.classList.add("tabulator-block-select");
//create placeholder
this.placeholderElement.style.width = column.getWidth() + "px";
this.placeholderElement.style.height = column.getHeight() + "px";
element.parentNode.insertBefore(this.placeholderElement, element);
element.parentNode.removeChild(element);
//create hover element
this.hoverElement = element.cloneNode(true);
this.hoverElement.classList.add("tabulator-moving");
this.table.columnManager.getElement().appendChild(this.hoverElement);
this.hoverElement.style.left = "0";
this.hoverElement.style.bottom = "0";
if (!this.touchMove) {
this._bindMouseMove();
document.body.addEventListener("mousemove", this.moveHover);
document.body.addEventListener("mouseup", this.endMove);
}
this.moveHover(e);
};
MoveColumns.prototype._bindMouseMove = function () {
this.table.columnManager.columnsByIndex.forEach(function (column) {
if (column.modules.moveColumn.mousemove) {
column.getElement().addEventListener("mousemove", column.modules.moveColumn.mousemove);
}
});
};
MoveColumns.prototype._unbindMouseMove = function () {
this.table.columnManager.columnsByIndex.forEach(function (column) {
if (column.modules.moveColumn.mousemove) {
column.getElement().removeEventListener("mousemove", column.modules.moveColumn.mousemove);
}
});
};
MoveColumns.prototype.moveColumn = function (column, after) {
var movingCells = this.moving.getCells();
this.toCol = column;
this.toColAfter = after;
if (after) {
column.getCells().forEach(function (cell, i) {
var cellEl = cell.getElement();
cellEl.parentNode.insertBefore(movingCells[i].getElement(), cellEl.nextSibling);
});
} else {
column.getCells().forEach(function (cell, i) {
var cellEl = cell.getElement();
cellEl.parentNode.insertBefore(movingCells[i].getElement(), cellEl);
});
}
};
MoveColumns.prototype.endMove = function (e) {
if (e.which === 1 || this.touchMove) {
this._unbindMouseMove();
this.placeholderElement.parentNode.insertBefore(this.moving.getElement(), this.placeholderElement.nextSibling);
this.placeholderElement.parentNode.removeChild(this.placeholderElement);
this.hoverElement.parentNode.removeChild(this.hoverElement);
this.table.element.classList.remove("tabulator-block-select");
if (this.toCol) {
this.table.columnManager.moveColumnActual(this.moving, this.toCol, this.toColAfter);
}
this.moving = false;
this.toCol = false;
this.toColAfter = false;
if (!this.touchMove) {
document.body.removeEventListener("mousemove", this.moveHover);
document.body.removeEventListener("mouseup", this.endMove);
}
}
};
MoveColumns.prototype.moveHover = function (e) {
var self = this,
columnHolder = self.table.columnManager.getElement(),
scrollLeft = columnHolder.scrollLeft,
xPos = (self.touchMove ? e.touches[0].pageX : e.pageX) - Tabulator.prototype.helpers.elOffset(columnHolder).left + scrollLeft,
scrollPos;
self.hoverElement.style.left = xPos - self.startX + "px";
if (xPos - scrollLeft < self.autoScrollMargin) {
if (!self.autoScrollTimeout) {
self.autoScrollTimeout = setTimeout(function () {
scrollPos = Math.max(0, scrollLeft - 5);
self.table.rowManager.getElement().scrollLeft = scrollPos;
self.autoScrollTimeout = false;
}, 1);
}
}
if (scrollLeft + columnHolder.clientWidth - xPos < self.autoScrollMargin) {
if (!self.autoScrollTimeout) {
self.autoScrollTimeout = setTimeout(function () {
scrollPos = Math.min(columnHolder.clientWidth, scrollLeft + 5);
self.table.rowManager.getElement().scrollLeft = scrollPos;
self.autoScrollTimeout = false;
}, 1);
}
}
};
Tabulator.prototype.registerModule("moveColumn", MoveColumns); |
/*!
* Paper.js v*#=* options.version
*
* This file is part of Paper.js, a JavaScript Vector Graphics Library,
* based on Scriptographer.org and designed to be largely API compatible.
* http://paperjs.org/
* http://scriptographer.org/
*
* Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
* http://lehni.org/ & http://jonathanpuckey.com/
*
* Distributed under the MIT license. See LICENSE file for details.
*
* All rights reserved.
*
* Date: *#=* options.date
*
***
*
* Bootstrap.js JavaScript Framework.
* http://bootstrapjs.org/
*
* Copyright (c) 2006 - 2011 Juerg Lehni
* http://lehni.org/
*
* Distributed under the MIT license.
*
***
*
* Parse-js
*
* A JavaScript tokenizer / parser / generator, originally written in Lisp.
* Copyright (c) Marijn Haverbeke <marijnh@gmail.com>
* http://marijn.haverbeke.nl/parse-js/
*
* Ported by to JavaScript by Mihai Bazon
* Copyright (c) 2010, Mihai Bazon <mihai.bazon@gmail.com>
* http://mihai.bazon.net/blog/
*
* Modifications and adaptions to browser (c) 2011, Juerg Lehni
* http://lehni.org/
*
* Distributed under the BSD license.
*/
var paper = new function() {
// Inline Bootstrap core (the Base class) inside the paper scope first:
/*#*/ include('../lib/bootstrap.js');
/*#*/ if (options.version == 'dev') {
/*#*/ include('constants.js');
/*#*/ } // options.version == 'dev'
/*#*/ if (options.stats) {
/*#*/ include('../lib/stats.js');
/*#*/ } // options.stats
/*#*/ include('core/Base.js');
/*#*/ include('core/Callback.js');
/*#*/ include('core/PaperScope.js');
/*#*/ include('core/PaperScopeItem.js');
// Include Paper classes, which are later injected into PaperScope by setting
// them on the 'this' object, e.g.:
// var Point = this.Point = Base.extend(...);
/*#*/ include('basic/Point.js');
/*#*/ include('basic/Size.js');
/*#*/ include('basic/Rectangle.js');
/*#*/ include('basic/Matrix.js');
/*#*/ include('basic/Line.js');
/*#*/ include('project/Project.js');
/*#*/ include('project/Symbol.js');
/*#*/ include('item/Item.js');
/*#*/ include('item/Group.js');
/*#*/ include('item/Layer.js');
/*#*/ include('item/PlacedItem.js');
/*#*/ include('item/Raster.js');
/*#*/ include('item/PlacedSymbol.js');
/*#*/ include('item/HitResult.js');
/*#*/ include('path/Segment.js');
/*#*/ include('path/SegmentPoint.js');
/*#*/ include('path/Curve.js');
/*#*/ include('path/CurveLocation.js');
/*#*/ include('path/PathItem.js');
/*#*/ include('path/Path.js');
/*#*/ include('path/Path.Constructors.js');
/*#*/ include('path/CompoundPath.js');
/*#*/ include('path/PathFlattener.js');
/*#*/ include('path/PathFitter.js');
/*#*/ include('text/TextItem.js');
/*#*/ include('text/PointText.js');
/*#*/ include('svg/SvgStyles.js');
/*#*/ include('svg/SvgExport.js');
/*#*/ include('svg/SvgImport.js');
/*#*/ include('style/Style.js');
/*#*/ include('style/PathStyle.js');
/*#*/ include('style/ParagraphStyle.js');
/*#*/ include('style/CharacterStyle.js');
/*#*/ include('color/Color.js');
/*#*/ include('color/GradientColor.js');
/*#*/ include('color/Gradient.js');
/*#*/ include('color/GradientStop.js');
/*#*/ if (options.browser) {
/*#*/ include('browser/DomElement.js');
/*#*/ include('browser/DomEvent.js');
/*#*/ } // options.browser
/*#*/ include('ui/View.js');
/*#*/ include('ui/CanvasView.js');
/*#*/ if (options.browser) {
/*#*/ include('ui/Event.js');
/*#*/ include('ui/KeyEvent.js');
/*#*/ include('ui/Key.js');
/*#*/ include('ui/MouseEvent.js');
/*#*/ include('ui/Palette.js');
/*#*/ include('ui/Component.js');
/*#*/ include('tool/ToolEvent.js');
/*#*/ include('tool/Tool.js');
/*#*/ } // options.browser
/*#*/ include('util/CanvasProvider.js');
/*#*/ include('util/Numerical.js');
/*#*/ include('util/BlendMode.js');
/*#*/ if (options.version == 'dev') {
/*#*/ include('util/ProxyContext.js');
/*#*/ } // options.browser
/*#*/ include('core/PaperScript.js');
/*#*/ if (options.browser) {
/*#*/ include('core/initialize.js');
/*#*/ } // options.browser
/*#*/ if (options.version != 'dev') {
// Finally inject the classes set on 'this' into the PaperScope class and create
// the first PaperScope and return it, all in one statement.
// The version for 'dev' of this happens in core/initialize.js, since it depends
// on sequentiality of include() loading.
// Mark this object as enumerable, so all the injected classes can be enumerated
// again in PaperScope#install().
this.enumerable = true;
return new (PaperScope.inject(this));
/*#*/ } // options.version != 'dev'
};
|
// [导出]
exports = module.exports = Engine;
// [模块]
var path = require('path');
// [函数]
function Engine() {
this.instructionHandler = undefined;
this.context = undefined;
this.isRunning = undefined;
this.instructionList = [];
this.nextIndex = 0;
// 指令模块文件所在目录
this.moduleDir = undefined;
}
Engine.prototype._append = function(instructions) {
var self = this;
if (!Array.isArray(instructions)) {
return;
}
if (instructions.length < 1) {
return;
}
while(instructions.length > 0) {
self.instructionList.push(instructions.shift());
}
self._run();
}
Engine.prototype._run = function() {
var self = this;
// 已经在执行了,无需重复调用
if (self.isRunning) {
return;
}
self.isRunning = true;
execNextInstruction();
function execNextInstruction() {
// 队列中没有需要执行的指令
if (self.nextIndex >= self.instructionList.length) {
self.isRunning = false;
return;
}
// 取出一条指令
var ins = self.instructionList[self.nextIndex++];
// 根据指令名找到对应的处理过程
var handler = self.instructionHandler[ins.name];
// 哦哦,没有找到对应名字的处理过程
// 忽略它
if (!handler) {
console.log('unknown instruction: ' + ins.name);
return;
}
// 调用处理过程
try {
ins.context = self.context;
ins.result = handler.call(ins, ins.args);
ins.callback(ins.result);
} catch(err) {
console.log(err.toString());
}
// 继续执行下一条指令
process.nextTick(execNextInstruction);
}
}
/* 扩展部分 */
// # callback(result)
Engine.prototype.append = function(instructions, callback) {
var self = this;
if (!Array.isArray(instructions)) {
instructions = [instructions];
}
for (var i = instructions.length - 1; i >= 0; --i) {
var ins = instructions[i];
// 这样做才能够保证查询后能把结果返回给客户端
ins.callback = callback;
// 加载指令对应的模块
var modulePath = path.resolve(self.moduleDir , ins.name + '.js');
var m = reloadModule(modulePath);
self.instructionHandler[m.name] = m.handler;
}
// 把指令加入到引擎中去
self._append(instructions);
// [函数]
// 重新加载模块,并且忽略缓存
function reloadModule(modulePath) {
// 删除模块缓存
delete require.cache[modulePath];
// 重新加载
return require(modulePath);
}
} |
var storage = {
l_storage:chrome.storage.local,
_getEmptyFun:function(){
return function(){};
},
set:function(obj,cb){
cb = cb || this._getEmptyFun;
this.l_storage.set(obj,cb)
},
get:function(key,cb){
cb = cb || this._getEmptyFun;
this.l_storage.get(key,cb);
},
getUsed:function(key,cb){
cb = cb || this._getEmptyFun;
this.l_storage.getBytesInUse(key,cb);
},
remove:function(key,cb){
cb = cb || this._getEmptyFun;
this.l_storage.remove(key,cb);
},
clear:function(cb){
cb = cb || this._getEmptyFun;
this._storage.clear(cb);
},
bindChange:function(cb){
cb = cb || this._getEmptyFun;
chrome.storage.onChanged.addListener(cb);
}
} |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var testHelper_1 = require("./testHelper");
describe('use-view-encapsulation', function () {
describe('invalid view encapsulation', function () {
it('should fail if ViewEncapsulation.None is set', function () {
var source = "\n @Component({\n selector: 'sg-foo-bar',\n encapsulation: ViewEncapsulation.None\n ~~~~~~~~~~~~~~~~~~~~~~\n })\n export class TestComponent { }\n ";
testHelper_1.assertAnnotated({
ruleName: 'use-view-encapsulation',
message: 'Using "ViewEncapsulation.None" will make your styles global which may have unintended effect',
source: source
});
});
});
describe('valid view encapsulation', function () {
it('should succeed if ViewEncapsulation.Native is set', function () {
var source = "\n @Component({\n selector: 'sg-foo-bar',\n encapsulation: ViewEncapsulation.Native\n })\n export class TestComponent { }\n ";
testHelper_1.assertSuccess('use-view-encapsulation', source);
});
it('should succeed if ViewEncapsulation.Emulated is set', function () {
var source = "\n @Component({\n selector: 'sg-foo-bar',\n encapsulation: ViewEncapsulation.Emulated\n })\n export class TestComponent { }\n ";
testHelper_1.assertSuccess('use-view-encapsulation', source);
});
it('should succeed if no ViewEncapsulation is set explicitly', function () {
var source = "\n @Component({\n selector: 'sg-foo-bar',\n })\n export class TestComponent { }\n ";
testHelper_1.assertSuccess('use-view-encapsulation', source);
});
});
});
|
import {readdirSync as directory, readFileSync as file} from 'fs'
import {join} from 'path'
import unified from 'unified'
import reParse from 'remark-parse'
import footnotes from 'remark-footnotes'
import stringify from 'rehype-stringify'
import remark2rehype from 'remark-rehype'
const base = join(__dirname, 'fixtures')
const specs = directory(base).reduce((tests, contents) => {
const parts = contents.split('.')
if (!tests[parts[0]]) {
tests[parts[0]] = {}
}
tests[parts[0]][parts[1]] = file(join(base, contents), 'utf-8')
return tests
}, {})
const configs = [
{
gfm: true,
commonmark: false,
},
{
gfm: false,
commonmark: false,
},
{
gfm: false,
commonmark: true,
},
{
gfm: true,
commonmark: true,
},
]
configs.forEach(config => {
describe(JSON.stringify(config), () => {
test('footnotes', () => {
const {contents} = unified()
.use(reParse, config)
.use(footnotes, {inlineNotes: true})
.use(require('../src'))
.use(remark2rehype)
.use(stringify)
.processSync(specs['footnotes'].fixture)
expect(contents).toMatchSnapshot()
})
test('regression-1', () => {
const {contents} = unified()
.use(reParse, config)
.use(footnotes, {inlineNotes: true})
.use(require('../src'))
.use(remark2rehype)
.use(stringify)
.processSync(specs['regression-1'].fixture)
expect(contents).toMatchSnapshot()
})
test('regression-2', () => {
const {contents} = unified()
.use(reParse, config)
.use(footnotes, {inlineNotes: true})
.use(require('../src'))
.use(remark2rehype)
.use(stringify)
.processSync(specs['regression-2'].fixture)
expect(contents).toMatchSnapshot()
})
test('footnote-split', () => {
const {contents} = unified()
.use(reParse, config)
.use(footnotes, {inlineNotes: true})
.use(require('../src'))
.use(remark2rehype)
.use(stringify)
.processSync(specs['footnote-split'].fixture)
expect(contents).toMatchSnapshot()
})
})
})
|
const chunks = {} // chunkId => exports
const chunksInstalling = {} // chunkId => Promise
const failedChunks = {}
function importChunk(chunkId, src) {
// Already installed
if (chunks[chunkId]) {
return Promise.resolve(chunks[chunkId])
}
// Failed loading
if (failedChunks[chunkId]) {
return Promise.reject(failedChunks[chunkId])
}
// Installing
if (chunksInstalling[chunkId]) {
return chunksInstalling[chunkId]
}
// Set a promise in chunk cache
let resolve, reject
const promise = chunksInstalling[chunkId] = new Promise((_resolve, _reject) => {
resolve = _resolve
reject = _reject
})
// Clear chunk data from cache
delete chunks[chunkId]
// Start chunk loading
const script = document.createElement('script')
script.charset = 'utf-8'
script.timeout = 120
script.src = src
let timeout
// Create error before stack unwound to get useful stacktrace later
const error = new Error()
// Complete handlers
const onScriptComplete = script.onerror = script.onload = (event) => {
// Cleanups
clearTimeout(timeout)
delete chunksInstalling[chunkId]
// Avoid mem leaks in IE
script.onerror = script.onload = null
// Verify chunk is loaded
if (chunks[chunkId]) {
return resolve(chunks[chunkId])
}
// Something bad happened
const errorType = event && (event.type === 'load' ? 'missing' : event.type)
const realSrc = event && event.target && event.target.src
error.message = 'Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'
error.name = 'ChunkLoadError'
error.type = errorType
error.request = realSrc
failedChunks[chunkId] = error
reject(error)
}
// Timeout
timeout = setTimeout(() => {
onScriptComplete({ type: 'timeout', target: script })
}, 120000)
// Append script
document.head.appendChild(script)
// Return promise
return promise
}
window.__NUXT_JSONP__ = function (chunkId, exports) { chunks[chunkId] = exports }
window.__NUXT_JSONP_CACHE__ = chunks
window.__NUXT_IMPORT__ = importChunk
|
import Good from 'good';
module.exports = [
{
register: Good,
options: {
reporters: [{
reporter: require('good-console'),
events: {
response: '*',
log: '*'
}
}]
}
}
];
|
/*
* 12
*/
(function(global) {
module.exports.setupClient = require("./handlers.js").setupClient
global.setupClient = module.exports.setupClient
module.exports.extentionAvailable = true
global.extentionAvailable = true
console.log("Client can run setup...")
}).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
|
;(function($) {
var popup,
$currentFetchButton,
modalCache = {};
function _toggleButtonState($button, error)
{
var $buttons = $button.find('button');
$.each(['btn-default', 'btn-success', 'btn-danger'], function(idx, className) {
if ($buttons.hasClass(className)) {
$buttons.removeClass(className);
}
});
if (!error) {
$buttons.addClass('btn-success');
$button.data('is_attached', true);
toggleDropdown($button, 'attach');
$buttons[0].blur();
} else {
$buttons.addClass('btn-danger');
toggleDropDown($button, 'detach');
}
}
function fetchCompleted(event)
{
if (!popup || !$currentFetchButton) {
return;
}
var data = popup.$('textarea').text();
popup.close();
popup = null;
var id = '#' + $currentFetchButton.attr('id') + '-data';
$(id).text(data);
$form = $currentFetchButton.parents('form');
$.post($form.attr('action'), $form.serialize(), function (data) {
$(document).trigger('formPost.socialprofiles', [data]);
});
var fetchCompletedEvent = $.Event('fetchCompleted.socialprofiles');
$(document).trigger(fetchCompletedEvent);
if (fetchCompletedEvent.isPropagationStopped()) {
return;
}
_toggleButtonState($currentFetchButton, '' == data);
$currentFetchButton.find('.spb-icon-normal').show();
$currentFetchButton.find('.spb-icon-processing').hide();
$currentFetchButton = null;
return false;
}
function buttonClicked(event)
{
if (popup) {
if ($currentFetchButton && !popup.closed) {
return false;
}
popup.close();
popup = null;
}
var $button = $(event.currentTarget);
if ($button.parent().data('is_attached')) {
$button.blur();
return false;
}
$button.find('.spb-icon-normal').hide();
$button.find('.spb-icon-processing').show();
var url = $button.data('fetch-url');
popup = window.open(url, 'fetch social profile', 'width=480,height=550');
$currentFetchButton = $button.parent();
return false;
}
function actionClicked(event)
{
var $link = $(event.currentTarget);
var action = $link.attr('href').substr(1);
if (action.match(/\|/)) {
var parts = action.split('|');
action = parts[0];
var actionData = parts[1];
}
var $button = $link.parent().parent().parent();
switch (action) {
case 'attach':
$button.find('button:first-child').click();
break;
case 'detach':
toggleDropdown($button, 'detach');
$button.data('is_attached', false);
$('#' + $button.attr('id') + '-data').text('');
var $buttons = $button.find('button');
$.each(['btn-default', 'btn-success', 'btn-danger'], function(idx, className) {
if ($buttons.hasClass(className)) {
$buttons.removeClass(className);
}
});
$buttons.addClass('btn-default');
var $form = $button.parents('form');
$.post($form.attr('action'), $form.serialize(), function (data) {
$(document).trigger('formPost.socialprofiles', [data]);
});
break;
case 'view':
var $modal = $('#' + $button.parent().parent().attr('id') + '-preview-box');
var profileData = $('#' + $button.attr('id') + '-data').text();
if (actionData !== undefined) {
if (!modalCache[actionData]) {
modalCache[actionData] = $.ajax({
url: actionData,
method: 'POST',
data: {data: profileData},
dataType: 'html'
});
}
modalCache[actionData].done(function(html) {
$html = $('<div>' + html + '</div>');
$modal.find('.modal-body')
.replaceWith($html.find('.modal-body'))
.end()
.find('.modal-title')
.html($html.find('.modal-title').html())
.end()
.modal('show');
});
} else {
$modal.find('.modal-body').html('<pre style="max-height: 350px; overflow:auto">' +
JSON.stringify(JSON.parse(profileData), null, " ")
//.replace(/\n/, '<br>').replace(/\s/, ' ')
+ '</pre>'
);
$modal.modal('show');
}
break;
}
$link.parent().parent().dropdown('toggle');
return false;
}
function toggleDropdown($button, action)
{
var $attachActions = $button.find('.spb-action-attach');
var $detachActions = $button.find('.spb-action-detach, .spb-action-preview');
if ('attach' == action) {
$attachActions.addClass('disabled');
$detachActions.removeClass('disabled');
} else {
$attachActions.removeClass('disabled');
$detachActions.addClass('disabled');
}
}
function initFieldset($fieldset)
{
var $buttons = $fieldset.find('.social-profiles-button');
$buttons.find('button:first-child')
.on('click.socialprofiles', buttonClicked);
$buttons.find('.dropdown-menu a')
.on('click.socialprofiles', actionClicked);
$buttons.find('.spb-icon-processing').hide();
$buttons.each(function () {
var $button = $(this);
var $area = $('#' + $button.attr('id') + '-data');
var data = $area.val();
if ('' != data) {
_toggleButtonState($button, false);
toggleDropdown($button, 'attach');
} else {
toggleDropdown($button, 'detach');
}
});
}
$.fn.socialprofiles = function()
{
return this.each(function() {
initFieldset($(this));
});
};
$(function() {
$(document).on('fetch_complete.socialprofiles', fetchCompleted);
$('.social-profiles-fieldset').socialprofiles()
});
})(jQuery); |
var util = require('util');
var events = require('events');
var QuicStream = require('./QuicStream');
var QuicDataStream = module.exports = function QuicDataStream (session, id) {
var self = this;
QuicDataStream.super_.call(this, session, id);
};
util.inherits(QuicDataStream, QuicStream);
|
'use strict';
require('core-js');
var _nodePlop = require('./node-plop');
var _nodePlop2 = _interopRequireDefault(_nodePlop);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Main node-plop module
*
* @param {string} plopfilePath - The absolute path to the plopfile we are interested in working with
* @param {object} plopCfg - A config object to be passed into the plopfile when it's executed
* @returns {object} the node-plop API for the plopfile requested
*/
module.exports = _nodePlop2.default; // es2015 polyfill |
'use strict';
app.factory('Auth', ['$firebaseAuth', function($firebaseAuth) {
return $firebaseAuth();
}]);
|
/**
* Navigation view module controller.
*
* @author imoiseyenko93@gmail.com
*/
define(["angular"], function (angular) {
return ["$scope", "$state", "authService", "lsService", "authService",
function ($scope, $state, authService, lsService, authService) {
var successHandler = function (data) {
lsService.removeToken();
$state.go("login");
};
$scope.model = {
signOut: function () {
authService.signOut(lsService.getToken(), successHandler, successHandler);
}
};
}];
});
|
angular.module('app', [ 'ngRoute', 'ui.select' ])
// Routes
.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/:steamId/trade-offers', {
templateUrl: 'trade-offers.html',
controller: 'TradeOffersController'
})
.when('/:steamId/trade-offer/:tradeOfferId', {
templateUrl: 'trade-offer.html',
controller: 'TradeOfferController'
})
.when('/trade-offer-status', {
templateUrl: 'trade-offer-status.html',
controller: 'TradeOfferStatusController'
})
.otherwise({
redirectTo: '/'
});
})
// Controllers
.controller('HomeController', function($scope, $http) {
$http.get('/accounts').then(function(res) {
$scope.accounts = res.data;
});
})
.controller('TradeOffersController', function($scope, $http, $route) {
$scope.steamId = $route.current.params.steamId;
$http.get($route.current.originalPath.replace(':steamId', $route.current.params.steamId)).then(function(res) {
$scope.data = res.data;
});
})
.controller('TradeOfferController', function($scope, $http, $route) {
$scope.steamId = $route.current.params.steamId;
$scope.tradeOfferId = $route.current.params.tradeOfferId;
$http.get($route.current.originalPath.replace(':steamId', $route.current.params.steamId).replace(':tradeOfferId', $route.current.params.tradeOfferId)).then(function(res) {
$scope.offer = res.data.response.offer;
});
$scope.cancel = function() {
$http.get($route.current.originalPath.replace(':steamId', $route.current.params.steamId).replace(':tradeOfferId', $route.current.params.tradeOfferId) + '/cancel').then(function(res) {
$scope.cancelled = res.completed;
});
};
})
.controller('TradeOfferStatusController', function($scope, $http) {
$http.get('/accounts').then(function(res) {
$scope.accounts = [];
for (var account in res.data) {
$scope.accounts.push(res.data[account]);
}
});
$scope.steam64id = {};
$scope.generateEndpoint = function() {
$scope.endpoint = 'http://api.steampowered.com/IEconService/GetTradeOffer/v1?tradeofferid=' + $scope.tradeofferid + '&key=' + $scope.steam64id.selected.apiKey;
};
});
|
search_result['592']=["topic_000000000000013A.html","CompanyController.GetMasterBadgesItemPerson Method",""]; |
if(!X2JS)throw Error("You're required to include the X2JS library to use the xml module.");
(function(c,e){function d(b){return(b=b.headers("content-type"))?-1<b.search(/\Wxml/i):!1}function f(b,c){return{response:function(a){return a&&d(a)?(a.data=c.xml_str2json(a.data),a):b.when(a)},responseError:function(a){a&&d(a)&&(a.data=c.xml_str2json(a.data));return b.reject(a)}}}function g(b){b.factory("xmlHttpInterceptor",["$q","x2js",f])}function h(){this.config={};this.$get=["X2JS",function(b){return new b(this.config)}]}c&&c.module("xml",[]).config(["$provide",g]).provider("x2js",h).value("X2JS",
e)})(angular,X2JS); |
//date.js - custom extended functions for date object
//TODO: change from extending to wrapper class
Date.prototype.setDateWithSimpleFormat = function (dateString) {
//dateString to be in dd/mm/yyyy
let ary = dateString.split('/');
return new Date(ary[2], ary[1] - 1, ary[0], 0, 0, 0, 0);
};
Date.prototype.setDateWithGoogleRecurEventISO8601Format = function (dateString) {
let year = dateString.slice(0, 4);
let month = dateString.slice(4, 6);
let day = dateString.slice(6, 8);
let time = dateString.split('T')[1];
time = `${time.slice(0, 2)}:${time.slice(2, 4)}:${time.slice(4)}`;
this.setDateWithSimpleFormat(`${day}/${month}/${year}`);
let newDate = new Date(`${year}-${month}-${day}T${time}`);
this.setTime(newDate.getTime());
return this;
};
Date.prototype.addDays = function (d) {
this.setDate(this.getDate() + d);
return this;
};
Date.prototype.addMinutes = function (h) {
this.setMinutes(this.getMinutes() + h);
return this;
};
Date.prototype.rounddownToNearestHalfHour = function () {
let currentMin = this.getMinutes();
if (currentMin === 0) {
return this;
} else if (currentMin < 30) {
this.setMinutes(0);
} else if (currentMin <= 59) {
this.setMinutes(30);
}
return this;
};
Date.prototype.roundupToNearestHalfHour = function () {
let currentMin = this.getMinutes();
if (currentMin === 0) {
return this;
} else if (currentMin <= 30) {
this.setMinutes(30);
} else if (currentMin <= 59) {
this.setMinutes(currentMin + (60 - currentMin));
}
return this;
};
Date.prototype.isDateToday = function () {
let today = new Date().getSimpleDate();
return today === this.getSimpleDate();
};
Date.prototype.getFormattedTime = function () {
let timeFormatOptions = { hour: '2-digit', minute: '2-digit' };
return this.toLocaleTimeString('en-us', timeFormatOptions);
};
Date.prototype.getFormattedDate = function () {
let timeFormatOptions = { year: 'numeric', month: 'long', day: 'numeric' };
return this.toLocaleString('en-us', timeFormatOptions);
};
Date.prototype.getFormattedDateTime = function () {
return this.getFormattedDate() + ', ' + this.getFormattedTime();
};
Date.prototype.getISO8601TimeStamp = function (date) {
let pad = function (amount, width) {
let padding = '';
while (padding.length < width - 1 && amount < Math.pow(10, width - padding.length - 1)) {
padding += '0';
}
return padding + amount.toString();
};
date = date ? date : this;
let offset = date.getTimezoneOffset();
return pad(date.getFullYear(), 4) + '-' +
pad(date.getMonth() + 1, 2) + '-' + pad(date.getDate(), 2) +
'T' + pad(date.getHours(), 2) + ':' + pad(date.getMinutes(), 2) + ':' +
pad(date.getSeconds(), 2) + (offset > 0 ? '-' : '+') +
pad(Math.floor(Math.abs(offset) / 60), 2) + ':' + pad(Math.abs(offset) % 60, 2);
};
Date.prototype.getISO8601DateWithDefinedTime = function (hour, min, sec, ms) {
this.setHours(hour, min, sec, ms);
return this.getISO8601TimeStamp(this);
};
Date.prototype.getISO8601DateWithDefinedTimeString = function (timeStr) {
// e.g 08:30 AM
var tmp = timeStr.split(' ');
var timeAry = tmp[0].split(':');
if (tmp[1] === 'PM' && timeAry[0] < 12) {
timeAry[0] = 12 + parseInt(timeAry[0]);
}
this.setHours(timeAry[0], timeAry[1], 0, 0);
return this.getISO8601TimeStamp(this);
};
Date.prototype.getCurrentMonthNamed = function () {
let timeFormatOptions = { month: 'long' };
return this.toLocaleString('en-us', timeFormatOptions);
};
Date.prototype.getSimpleDate = function () {
return this.getDate() + '/' + (this.getMonth() + 1) + '/' + this.getFullYear();
};
Date.prototype.getCurrentDay = function () {
return this.getDate();
};
Date.prototype.daysInMonth = function () {
let d = new Date(this.getFullYear(), this.getMonth() + 1, 0);
return d.getDate();
};
Date.prototype.getMinuteDiff = function (timeCompared) {
var timeDiff = Math.abs(timeCompared.getTime() - this.getTime());
var minDiff = Math.ceil(timeDiff / 60000);
return minDiff;
};
Date.prototype.getDayNameInWeek = function () {
let weekdayNames = {
0: 'SU',
1: 'MO',
2: 'TU',
3: 'WE',
4: 'TH',
5: 'FR',
6: 'SA'
};
return weekdayNames[this.getDay()];
};
Date.prototype.getNumOfDaysDiffInWeekForDayNames = function () {
let weekdayNames = { SU: 0, MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6 };
let today = new Date(this);
weekdayNames[today.getDayNameInWeek()] = 0;
for (let i = 1; i < Object.keys(weekdayNames).length; i++) {
let date = today.addDays(1);
weekdayNames[date.getDayNameInWeek()] = i;
}
return weekdayNames;
};
|
Let me be :-)
|
var crypto = require('crypto');
var config = require('../../config');
var router = require('express').Router();
var activity = require('../../modules/activity')();
var async = require('async');
var _ = require('lodash-node');
var errorProxy = require(process.cwd() + '/error');
/**
* add activity
*
*/
router
.post('/add', function(req, res) {
var _activity = req.body;
async.waterfall(
[
function(callback) {
var err = null;
if (_activity.user_id == '' || !_.isString(_activity.user_id)) {
err = errorProxy(1000);
} else if (_activity.name == '' || !_.isString(_activity.name)){
err = errorProxy(1200);
} else if ( _activity.name.length >= 200){
err = errorProxy(1208);
} else if (!/^\d+$/.test(_activity.deadline)) {
err = errorProxy(1201);
} else if (!/^\d+$/.test(_activity.toplimit)) {
err = errorProxy(1202);
} else if (!/^\d+(\.\d+)?$/.test(_activity.cost)) {
err = errorProxy(1203);
} else if ( _activity.detail == '' || !_.isString(_activity.detail)) {
err = errorProxy(1205);
} else if (_activity.tags == '' || !_.isString(_activity.tags)) {
err = errorProxy(1206);
} else if (!_.isArray(_activity.bdloc) || !/[\d.]+\,[\d\s.]+$/.test(_activity.bdloc.join())) {
err = errorProxy(1207);
}
callback(err)
},
function(callback){
activity.add(_activity, function(err, result){
if (err) {
callback(errorProxy(2000, err))
} else {
callback(null, result)
}
})
}
],
function(err, data){
// connection: Object
// insertedCount: 1
// insertedId: ObjectID
// ops: Array[1]
// result: Object
// __proto__: Object
var rslt = err || errorProxy();
if (!err) {
rs = rslt.result = {};
rs._id = data.insertedId.toString();
}
res.json(rslt)
})
})
//查询活动列表
.get('/activities', function(req, res) {
var params = req.params;
//qeury
var query = {};
//options
var options = {};
options.skip = params.page_index || 0;
async.waterfall(
[
function(callback) {
activity.list(query, options, function(err, activities){
if (err) {
callback(errorProxy(2000, err));
} else {
callback(null, activities);
}
})
}
],
function(err, activities) {
var rslt = null;
if (err) {
rslt = err;
} else {
rslt = errorProxy();
rslt.result = {};
rslt.result.activities = activities;
rslt.result.page_index = options.skip;
}
res.json(rslt)
})
})
//字符串搜索
.get('/search', function(req, res) {
//qeury
var query = {};
var word = req.query.word;
if (word && word.length > 1) {
word = new RegExp(word, 'i');
query['$or'] = [{tags: word}, {name: word}];
} else {
res.json(errorProxy(2000, '搜索字符串不能少于2个字符'));
return;
}
if (req.query.city) {
query.city = req.query.city;
}
//options
var options = {};
options.skip = req.query.page_index || 0;
async.waterfall(
[
function(callback) {
activity.search(query, options, function(err, activities){
if (err) {
callback(errorProxy(2000, err));
} else {
callback(null, activities);
}
})
}
],
function(err, activities) {
var rslt = null;
if (err) {
rslt = err;
} else {
rslt = errorProxy();
rslt.result = {};
rslt.result.activities = activities;
rslt.result.page_index = options.skip;
}
res.json(rslt)
})
});
module.exports = router; |
// Because PhantomJS can load and manipulate a web page,
// it is perfect to carry out various page automations.
// The following useragent.js example demonstrates
// reading the textContent property of the element whose id is myagent:
var page = require('webpage').create();
console.log('The default user agent is ' + page.settings.userAgent);
page.settings.userAgent = 'SpecialAgent';
page.open('http://www.httpuseragent.org', function(status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
var ua = page.evaluate(function() {
return document.getElementById('myagent').textContent;
});
console.log(ua);
}
phantom.exit();
});
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M4 6.47L5.76 10H20v8H4V6.47M22 4h-4l2 4h-3l-2-4h-2l2 4h-3l-2-4H8l2 4H7L5 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4z" />
, 'MovieOutlined');
|
'use strict';
var React = require('react'),
Main = require('./components/Main'),
DocumentTitle = require('react-document-title'),
{ RouteHandler } = require('react-router'),
{ PropTypes } = React;
var bootstrap = React.createClass({
propTypes: {
params: PropTypes.object.isRequired,
query: PropTypes.object.isRequired
},
render(){
return (
<DocumentTitle title='TinderWeb'>
<div id='wrapper'>
<Main />
<RouteHandler {...this.props} />
</div>
</DocumentTitle>
);
}
});
module.exports = bootstrap;
|
/*global define*/
define([], function () {
"use strict";
bar();
});
|
'use strict';
import koa from 'koa';
import logger from './utils/logger';
import APP_CONF from './configs/app';
import router from './routers';
let app = koa();
app.experimental = true;
app.use(router.account.routes()).use(router.account.allowedMethods());
app.on('error', function () {
console.log('!!');
});
app.listen(APP_CONF.SERVER_PORT);
|
'use strict';
/* all required gulp libs */
var gulp = require('gulp');
var gutil = require('gulp-util');
var clean = require('gulp-clean');
var flatmap = require('gulp-flatmap');
var fs = require('fs');
var path = require('path');
var argv = require('yargs').argv;
var closureCompiler = require('google-closure-compiler').gulp();
var replace = require('gulp-replace');
var exec = require('child_process').exec;
var through2 = require('through2');
var chalk = require('chalk');
/* build config */
// get 'env' argument, 'env=prod' for production, 'env=dev' for development
var __ENV = argv.env ? argv.env : 'prod'; // default is build production
var __DISABLE_DEBUG = argv['disable-debug'] ? true : false;
var __IS_DEV = ('dev' === __ENV);
var __IS_TEST = ('test' === __ENV);
var DEBUG = __IS_DEV || (__IS_TEST && !__DISABLE_DEBUG);
gutil.log('gulp runs with env=' + __ENV + (__IS_TEST ? (' (--disable-debug=' + __DISABLE_DEBUG + ')') : '') + ', DEBUG=' + DEBUG + '\n');
var DIST = 'dist'; // DO NOT add "./" base
var DIST_RAW = DIST + '/1.raw';
var DIST_COMPILED = DIST + '/2.compiled';
var DIST_DEPLOY = DIST + '/3.deploy/' + __ENV;
var outputMyAppVersion = false;
/* === all tasks === */
//
// clean: clean all in dist
// input: src
// output: DIST_RAW
//
gulp.task('clean', function () {
return gulp.src(DIST, {read: false})
.pipe(clean());
});
//
// js replace: replace const
// input: src
// output: DIST_RAW
//
gulp.task('js-replace', ['clean'], function () {
return gulp.src(
[
'./src/app/MyApp.js'
], {base: 'src'})
.pipe(replace('$$DEBUG$$', DEBUG))
.pipe(gulp.dest(DIST_RAW));
});
//
// copy no-need-compiled files to compiled
// input: src
// output: DIST_COMPILED
//
gulp.task('copy-no-need-compiled-files-to-compiled', ['clean'], function () {
return gulp.src(
[
'./src/3rd-party/**/*.js',
'./src/asset/**/*.*',
'./src/app.js'
], {base: 'src'})
.pipe(gulp.dest(DIST_COMPILED));
});
//
// advanced compile separately modules
// input: DIST_RAW
// output: DIST_COMPILED
//
gulp.task('js-compile-advanced', ['js-replace'], function () {
if (__IS_DEV) {
return gulp.src(
[
DIST_RAW + '/app/MyApp.js'
], {base: DIST_RAW})
.pipe(gulp.dest(DIST_COMPILED));
}
var externFiles = getExternFiles();
return gulp.src(
[
DIST_RAW + '/app/MyApp.js'
], {base: './'})
.pipe(flatmap(function (stream, file) {
return stream.pipe(closureCompiler({
compilation_level: 'ADVANCED',
//manage_closure_dependencies: true,
//warning_level: 'QUIET',
language_in: 'ECMASCRIPT6_STRICT',
language_out: 'ECMASCRIPT5_STRICT',
output_wrapper: '(function(){\n%output%\n}).call(this)',
js_output_file: path.join(path.dirname(file.path).replace(DIST_RAW, ''), path.basename(file.path)),
externs: externFiles
}))
}))
.pipe(gulp.dest(DIST_COMPILED));
});
//
// outputMyAppVersion task: get current app version base on git branch/tag name
// e.g: git branch "dev.feature-1" => my-app-dev.feature-1.js
// e.g: git tag "1.0.0" => my-app-1.0.0.js
//
gulp.task('getOutputMyAppVersion', function () {
return gulp.src(['./'])
.pipe(through2.obj(function (chunk, enc, callback) {
// run command 'git symbolic-ref -q --short HEAD || git describe --tags --exact-match'
exec('git symbolic-ref -q --short HEAD || git describe --tags --exact-match', function (err, stdout, stderr) {
if (err || !stdout || stdout.length < 1) {
gutil.log('error can not get current branch or tag name');
outputMyAppVersion = false; // false to tell gulp task 'compile:flash' stop compiling
callback();
return;
}
var isTag = stdout.lastIndexOf('v') == 0;
outputMyAppVersion = isTag ? stdout.substr(1) : stdout;
// remove return carriage characters
outputMyAppVersion = outputMyAppVersion.replace(/(\r\n|\n|\r)/g, '');
gutil.log('got current ' + (isTag ? 'tag: v' : 'branch: ') + outputMyAppVersion);
callback();
});
}))
.pipe(gulp.dest('./'));
});
//
// js compile
//
gulp.task('js-compile', ['copy-no-need-compiled-files-to-compiled', 'js-compile-advanced'], function () {
});
//
// js compile + got myAppVersion
//
gulp.task('js-compile-and-got-my-app-version', ['js-compile', 'getOutputMyAppVersion'], function () {
});
//
// webpack task: call webpack to build
//
gulp.task('webpack', ['js-compile-and-got-my-app-version'], function () {
gutil.log('webpack start...');
if (!outputMyAppVersion) {
gutil.log(chalk.red('webpack start... git branch/tag version invalid. End'));
return;
}
return gulp.src(['./'])
.pipe(through2.obj(function (chunk, enc, callback) {
// run command 'webpack'
exec('webpack ' + ('--env=' + __ENV + ' ') + (__DISABLE_DEBUG ? '--disable-debug ' : ' ') + '--version=' + outputMyAppVersion, function (err, stdout, stderr) {
gutil.log('webpack output: \n' + stdout);
if (err) {
gutil.log('error: ' + err);
outputMyAppVersion = false; // false to tell gulp task 'compile:flash' stop compiling
callback();
return;
}
callback();
});
}))
.pipe(gulp.dest('./'));
});
//
// js deploy: rename and copy to deploy folder
// input: DIST_COMPILED
// output: DIST_DEPLOY
//
gulp.task('js-deploy', ['webpack'], function () {
});
//
// js compile
//
gulp.task('build', ['js-deploy'], function () {
});
//
// default task
//
gulp.task('default', ['build']);
/**
* get Extern Files, depend on 3rd library files that we need keep exported field/functions of them
*
* @return {Array.<T>}
*/
function getExternFiles() {
DEBUG && console.log('getting extern files...');
return [].concat(
getFilesInDirectory('src/externs/3rd-party'),
getFilesInDirectory('src/externs/app/')
);
}
/**
* get all files in a dir
*
* @param dir
* @return {Array}
*/
function getFilesInDirectory(dir) {
var allFileNames = fs.readdirSync(dir);
var allFiles = [];
allFileNames.map(function (file) {
return path.join(dir, file);
}).filter(function (file) {
return fs.statSync(file).isFile();
}).forEach(function (file) {
DEBUG && console.log(" %s", file);
allFiles.push(file);
});
return allFiles;
} |
(function () {
var cookies = {};
function readCookie(name) {
if (cookies[name]) { return cookies[name]; }
var cookie;
var c = document.cookie.split('; ');
cookies = {};
for (var i = c.length - 1; i >= 0; i--) {
cookie = c[i].split('=');
cookies[cookie[0]] = cookie[1];
}
return cookies[name];
}
function deleteCookie(name) {
document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:01 GMT;";
}
function writeCookie(name, value, path) {
deleteCookie(name);
document.cookie = name + "=" + value + path;
cookies[name] = value;
}
function writeSiteCookie(name, value) {
writeCookie(name, value, "; Path=/");
}
function writePageCookie(name, value) {
writeCookie(name, value, "");
}
window.readCookie = readCookie;
window.writeSiteCookie = writeSiteCookie;
window.writePageCookie = writePageCookie;
window.deleteCookie = deleteCookie;
})();
$(function () {
window.deleteCookie("suppressModal");
});
function htmlEscape(str) {
return String(str)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
}
function parseJson(text) {
return (JSON && JSON.parse(text) || $.parseJSON(text));
}
function createSelectList(openingSelectTag, values, data) {
return openingSelectTag
+ Object.keys(values).map(function (name) {
var id = values[name];
return '<option value="' + id + '"' + (id === data ? ' selected' : '') + '>' + name + '</option>';
})
+ '</select>';
}
function writeJson(object) {
return JSON && JSON.stringify ? JSON.stringify(object) : $.toJSON(object);
}
function showErrorAlert(validationError) {
var errorAlert = document.createElement("div");
errorAlert.className = "alert alert-danger alert-dismissable fade in";
errorAlert.textContent = validationError.ErrorMessage;
document.getElementById("errors").appendChild(errorAlert);
}
function showErrorAlerts(validationErrors) {
if (!validationErrors) return;
validationErrors.forEach(showErrorAlert);
}
function setIsLoading(cell, isLoading) {
var image, images;
if (isLoading) {
cell.className += " loading";
image = document.createElement("img");
image.src = "/Content/img/table-cell-loading.gif";
image.style.height = "20px";
cell.appendChild(image);
} else {
images = cell.getElementsByTagName("img");
for (var i = 0; i < images.length; ++i) cell.removeChild(images[i]);
cell.className = cell.className.replace(" loading", "");
}
}
function clearErrorAlerts() {
var errorNode = document.getElementById("errors");
while (errorNode.lastChild) {
errorNode.removeChild(errorNode.lastChild);
}
}
function getOriginalRecord(control, settings) {
var column = { Name: control.name, Label: control.getAttribute("data-label") || control.name },
cell = control.parentNode,
row = cell.parentNode,
rowData = settings.tableData.row($(row)).data(),
recordKey = rowData[settings.keyColumn],
recordName = rowData[settings.nameColumn];
return {
Column: column,
Data: rowData,
Key: recordKey,
Name: recordName
}
}
function showModal(control, settings, callbacks, action) {
var cell = control.parentNode, hide = !settings.doNotHide;
if (window.readCookie("suppressModal")) {
if (hide) setIsLoading(cell, true);
clearErrorAlerts();
action();
return;
}
if (hide) setIsLoading(cell, true);
$("#modalTitle").text(settings.modalTitle);
$("#modalBody").text(settings.modalContent);
$("#modalDialog").modal("show");
$("#modalDialog").off("keydown").on("keydown", function (event) {
var keyCode = event.keyCode;
if (keyCode === 13 || String.fromCharCode(keyCode).toLowerCase() === 'y') {
$("#modalConfirm").trigger("click");
} else if (keyCode === 27 || String.fromCharCode(keyCode).toLowerCase() === 'n') {
$("#modalCancel").trigger("click");
}
});
$("#modalCancel").off("click").on("click", function () {
if ($("#suppressModal").is(":checked")) window.writePageCookie("suppressModal", "1");
settings.tableData.ajax.reload();
});
$("#modalConfirm").off("click").on("click", function () {
if ($("#suppressModal").is(":checked")) window.writePageCookie("suppressModal", "1");
clearErrorAlerts();
$("#modalDialog").modal("hide");
action();
});
}
function showAjaxError(data, message) {
var responseText = data.responseText;
if (responseText) {
var error = parseJson(responseText);
toastr.error(message + "<br /><br />" + error.summary);
} else {
toastr.error(message);
}
}
function deleteWarningMessage(recordName, noun) {
return 'You are about to permanently delete the ' + noun + ' "' + recordName + '". This cannot be undone.';
}
function deleteSuccessMessage(recordName, settings) {
return 'The ' + settings.noun + ' [' + recordName + '] was permanently deleted.';
}
function deleteFailureMessage(recordName, noun) {
return 'The ' + noun + ' [' + recordName + '] could not be deleted.';
}
function deleteWithModalProtection(control, settings) {
var column = { Name: control.name, Label: control.getAttribute("data-label") || control.name },
row = $(control).closest("tr"),
rowData = settings.tableData.row($(row)).data(),
recordKey = rowData[settings.keyColumn],
recordKeyForUrl = null,
recordName = rowData[settings.nameColumn],
noun = settings.noun;
if (!settings.recordKeyForUrl) {
recordKeyForUrl = (settings.getKey || getKey)(recordKey);
} else {
recordKeyForUrl = settings.recordKeyForUrl;
}
settings.modalTitle = "Deleting [" + recordName + "]...";
settings.modalContent = deleteWarningMessage(recordName, settings.noun);
showModal(control, settings, settings, function () {
control.isUpdating = true;
$.ajax({
type: 'DELETE',
contentType: 'application/json',
headers: { Accept: "application/json, application/sharpcloud.v2" },
url: settings.urlRoot + '(' + recordKeyForUrl + ')',
success: function (deletedEntity) {
toastr.success(deleteSuccessMessage(recordName, settings));
control.isUpdating = false;
if (settings.successCallback) settings.successCallback(deletedEntity);
settings.tableData.ajax.reload();
},
error: function (data) {
var responseText = data.responseText,
responseJson = data.responseJSON;
if (responseJson && responseJson.error) {
if (responseJson.error.innererror) {
toastr.error(deleteFailureMessage(recordName, noun) + '<br /><br />' + responseJson.error.innererror.message);
}
} else {
var error = parseJson(responseText);
showErrorAlerts(error.validationErrors);
toastr.error(deleteFailureMessage(recordName, noun) + '<br /><br />' + error.summary);
}
control.isUpdating = false;
settings.tableData.ajax.reload();
}
});
});
}
function createWithModalProtection(control, settings) {
showModal(control, settings, settings, function () {
control.isUpdating = true;
$.ajax({
type: 'POST',
contentType: 'application/json',
headers: { Accept: "application/json" },
url: settings.urlRoot,
data: writeJson(settings.newEntity),
success: function (createdEntity) {
toastr.success(settings.successMessage(createdEntity));
control.isUpdating = false;
if (settings.successCallback) settings.successCallback(createdEntity);
},
error: function (data) {
var responseText = data.responseText;
var error = parseJson(responseText);
showErrorAlerts(error.validationErrors);
toastr.error(settings.failureMessage() + '<br /><br />' + error.summary);
control.isUpdating = false;
}
});
});
}
function getObject(name, value) {
var result = {};
result[name] = value;
return result;
}
function surroundWithEncodedSingleQuotes(text) {
var encodedSingleQuote = encodeURIComponent("'");
return encodedSingleQuote + text + encodedSingleQuote;
}
function getKey(recordKey) {
return (typeof recordKey === 'string' || recordKey instanceof String)
? surroundWithEncodedSingleQuotes(recordKey)
: recordKey;
}
function updateWithModalProtection(control, settings, callbacks, originalRecord) {
originalRecord = originalRecord || getOriginalRecord(control, settings);
var recordName = originalRecord.Name,
recordKey = originalRecord.Key,
column = originalRecord.Column;
settings.modalTitle = "Changing value of [" + recordName + "]...";
settings.modalContent = warningMessage(recordName, column, settings);
showModal(control, settings, callbacks, function () {
var updatedRecord = settings.getRecordUpdate
? settings.getRecordUpdate(recordKey, column.Name, settings.newValue, originalRecord.Data)
: writeJson(getObject(column.Name, settings.newValue)),
recordKeyForUrl = updatedRecord.key || (settings.getKey || getKey)(recordKey),
data = updatedRecord.value || updatedRecord;
control.isUpdating = true;
$.ajax({
type: 'PATCH',
contentType: 'application/json',
headers: { Accept: "application/json" },
url: (updatedRecord.urlRoot || settings.urlRoot) + '(' + recordKeyForUrl + ')',
data: data,
success: function () {
var tr = $(control).closest('tr');
var nextControl = $(control).closest("td").next("td");
var currentControl = $(control);
tr.attr('id', settings.htmlTableId + '-row-' + recordKey);
toastr.success(successMessage(recordName, column, settings));
control.isUpdating = false;
setIsLoading(control.parentNode, false);
if (settings.successCallback) settings.successCallback(settings, parseJson(data), control, recordKey);
if (callbacks && callbacks.success) callbacks.success(settings.newValue, control);
// dataRow.data(jQuery.extend(dataRow.data(), (settings.parseJson || parseJson)(data)));
hookupEvents(settings);
//select next control that needs focus
if (settings.nextControlFunction) {
settings.nextControlFunction(currentControl, tr);
} else {
callCorrectHandleEvent(nextControl);
}
},
error: function (data) {
var responseText = data.responseText,
responseJson = data.responseJSON;
if (responseJson && responseJson.error) {
if (responseJson.error.innererror) {
toastr.error(failureMessage(recordName, column, settings) + '<br /><br />' + responseJson.error.innererror.message);
}
} else if (responseText) {
try {
var error = parseJson(responseText);
if (error.validationErrors) showErrorAlerts(error.validationErrors);
if (error.error && error.error.message) {
showErrorAlert({ ErrorMessage: error.error.message });
error.summary = error.error.message;
}
toastr.error(failureMessage(recordName, column, settings) + '<br /><br />' + error.summary);
} catch (e) {
toastr.error(failureMessage(recordName, column, settings) + '<br /><br />' + responseText);
}
} else {
toastr.error(failureMessage(recordName, column, settings));
}
callbacks.cancelOperation(settings.newValue, control);
control.isUpdating = false;
setIsLoading(control.parentNode, false);
}
});
});
}
function hookupCheckboxes(settings) {
var checkBoxQuery = settings.cellSelector + ' > input[type="checkbox"]';
var checkBoxes = document.querySelectorAll(checkBoxQuery);
[].forEach.call(checkBoxes, function (checkBox) {
checkBox.onchange = function (event) {
checkBox = event.currentTarget;
if (checkBox.isUpdating) return;
checkBox.style.display = "none";
updateWithModalProtection(checkBox, jQuery.extend(settings, {
newValue: checkBox.checked,
newLabel: checkBox.checked ? "TRUE" : "FALSE",
oldValue: !settings.newValue,
oldLabel: checkBox.checked ? "FALSE" : "TRUE"
}), {
cancelOperation: function (newVal, cb) { cb.style.display = ""; cb.checked = !newVal; },
success: function (newVal, cb) { cb.style.display = ""; cb.checked = newVal; }
});
};
});
}
function callCorrectEvent(settings, event, currentTarget) {
if (event.keyCode === 9 && event.shiftKey) { // Tab
if (settings.previousControlFunction != null) {
settings.previousControlFunction($(currentTarget));
} else {
callCorrectHandleEvent($(currentTarget).closest("td").prev("td"));
}
}
else if (event.keyCode === 9) { // Tab
if (settings.nextControlFunction) {
settings.nextControlFunction($(currentTarget));
} else {
callCorrectHandleEvent($(currentTarget).closest("td").next("td"));
}
}
}
function hookupButtons(settings) {
$(settings.cellSelector).on('keydown', 'button', function (event) {
callCorrectEvent(settings, event, event.currentTarget);
});
$(settings.cellSelector).on('keydown', 'span.glyphicon.glyphicon-remove.remove-record', function (event) {
callCorrectEvent(settings, event, event.currentTarget);
});
}
function callCorrectHandleEvent(selectedTd, selectedTr) {
if (selectedTd.length > 0) {
if (selectedTd.find("span[name]")[0]) { // textbox
handleTextBoxClick(selectedTd.find("span[name]")[0]);
} else if (selectedTd.find("button")[0]) {
selectedTd.find("button")[0].focus();
} else if (selectedTd.find("select")[0]) { //selectbox
selectedTd.find("select")[0].focus();
} else if (selectedTd.find('input[type="checkbox"]')[0]) { //checkbox
selectedTd.find('input[type="checkbox"]')[0].focus();
} else if (selectedTd.find("span.glyphicon.glyphicon-remove.remove-record")[0]) { //deletebutton
selectedTd.find("span.glyphicon.glyphicon-remove.remove-record")[0].focus();
}
event.preventDefault();
return false;
}
}
function handleTextBoxClick(span) {
var textBox = span.nextSibling;
if (textBox.isUpdating) return;
span.style.display = "none";
span.previousSibling.style.display = "none";
textBox.style.display = "";
textBox.focus();
}
function hookupTextBoxes(settings) {
var textBoxes = settings.textBoxes || document.querySelectorAll(settings.cellSelector + ' > input[type="text"]');
[].forEach.call(textBoxes, function (textBox) {
var textSpan = textBox.previousSibling;
textSpan.onclick = function (event) { handleTextBoxClick(event.currentTarget); }
var iconSpan = textSpan.previousSibling;
iconSpan.onclick = function (event) { handleTextBoxClick(event.currentTarget.nextSibling); }
textBox.onkeydown = function (event) {
if (event.keyCode === 13) { // Return
event.currentTarget.blur();
} else if (event.keyCode === 27) { // ESC
textBox.value = textBox.previousSibling.textContent;
event.currentTarget.blur();
} else if (event.keyCode === 9 && event.shiftKey) { // Tab
event.currentTarget.blur();
if (settings.previousControlFunction != null) {
settings.previousControlFunction($(this));
} else {
callCorrectHandleEvent($(this).closest("td").prev("td"));
}
}
else if (event.keyCode === 9) { // Tab
event.currentTarget.blur();
if (settings.nextControlFunction) {
settings.nextControlFunction($(this));
} else {
callCorrectHandleEvent($(this).closest("td").next("td"));
}
}
}
textBox.onblur = function (event) {
textBox = event.currentTarget;
if (textBox.isUpdating) return;
var hiddenSpan = textBox.previousSibling;
var newValue = textBox.value;
textBox.style.display = "none";
hiddenSpan.style.display = "";
hiddenSpan.previousSibling.style.display = "";
if (newValue === hiddenSpan.textContent) return;
(settings.update || updateWithModalProtection)(textBox, jQuery.extend(settings, {
newValue: newValue,
newLabel: newValue,
oldValue: hiddenSpan.textContent,
oldLabel: hiddenSpan.textContent
}), {
success: function (newVal, tb) { tb.previousSibling.textContent = newVal; },
cancelOperation: function (newVal, tb) { tb.value = tb.previousSibling.textContent; }
});
};
});
}
function hookupSelectControls(settings) {
var selectQuery = settings.cellSelector + ' > select:not([multiple])';
var selectControls = document.querySelectorAll(selectQuery);
[].forEach.call(selectControls, function (selectControl) {
hookupSelectControl(selectControl, settings);
});
}
function getSelectValue(columnName, settings, data) {
return settings.getSelectValue[columnName].getValue(data);
}
function getSelectLabel(columnName, settings, data) {
return settings.getSelectValue[columnName].getLabel(data);
}
function hookupSelectControl(selectControl, settings) {
selectControl.onchange = function (event) {
var select = event.target,
originalData = getOriginalRecord(select, settings);
settings.newValue = $(select).val();
var oldOption = select.multiple
? getSelectValue(originalData.Column.Name, settings, originalData.Data)
: select.querySelector('option[selected]');
var newOption = select.multiple
? [].map.call(select.selectedOptions, function (option) { return option.label; }).join()
: select.querySelector('option[value="' + select.value + '"]');
var control = select.multiple ? select.nextSibling : select;
control.style.display = 'none';
updateWithModalProtection(select, jQuery.extend(settings, {
oldValue: select.multiple ? originalData.Data : oldOption.value,
oldLabel: select.multiple ? getSelectLabel(originalData.Column.Name, settings, originalData.Data) || "<None>" : oldOption.innerText,
newLabel: select.multiple ? newOption || "<None>" : newOption.innerText
}), {
success: function (newValue, sel) {
control.style.display = '';
if (sel.multiple) return;
oldOption.removeAttribute('selected');
sel.querySelector('option[value="' + newValue + '"]').setAttribute('selected', '');
},
cancelOperation: function (newValue, sel) {
control.style.display = '';
if (sel.multiple) {
var tr = $(sel).closest('tr');
var dataRow = settings.tableData.row(tr);
dataRow.data(jQuery.extend(dataRow.data(), originalData.Data));
dataRow.$("select[multiple]").selectpicker();
hookupEvents(settings);
}
sel.value = oldOption.value;
}
},
originalData);
};
selectControl.onkeydown = function (event) {
if (event.keyCode === 9 && event.shiftKey) { // Tab
event.currentTarget.blur();
if (settings.previousControlFunction != null) {
settings.previousControlFunction($(this), $(this).closest('tr'));
} else {
callCorrectHandleEvent($(this).closest("td").prev("td"));
}
}
else if (event.keyCode === 9) { // Tab
event.currentTarget.blur();
if (settings.nextControlFunction) {
settings.nextControlFunction($(this), $(this).closest('tr'));
} else {
callCorrectHandleEvent($(this).closest("td").next("td"));
}
}
}
}
function hookupDeletionControl(control, settings) {
control.onclick = function () {
control.style.display = 'none';
deleteWithModalProtection(control, settings);
};
control.onkeydown = function(event) {
if (event.keyCode === 9 && event.shiftKey) { // Tab
if (settings.previousControlFunction != null) {
settings.previousControlFunction($(this), $(this).closest('tr'));
} else {
callCorrectHandleEvent($(this).closest("td").prev("td"));
}
} else if (event.keyCode === 9) { // Tab
if (settings.nextControlFunction) {
settings.nextControlFunction($(this), $(this).closest('tr'));
} else {
callCorrectHandleEvent($(this).closest("td").next("td"), $(this).closest('tr'));
}
}
};
}
function hookupDeletions(settings) {
var deletionQuery = settings.cellSelector + ' span.remove-record';
var deletionControls = document.querySelectorAll(deletionQuery);
[].forEach.call(deletionControls, function (deletionControl) {
hookupDeletionControl(deletionControl, settings);
});
}
function additionalColumnSetup(settings) {
$('span[name="' + settings.nameColumn + '"]').addClass("nameColumn");
}
function hookupEvents(settings) {
hookupCheckboxes(settings);
hookupTextBoxes(settings);
hookupSelectControls(settings);
hookupDeletions(settings);
hookupButtons(settings);
}
function getColumnName(meta) {
var column = meta.settings.aoColumns[meta.col];
var data = column.data;
if (typeof data == 'string' || data instanceof String) return data;
return column.columnName;
}
function successMessage(recordName, column, settings) {
var newLabel = settings.newLabel || settings.newValue;
return 'For the ' + settings.noun + ' "' + recordName + '", the value of [' + column.Label + '] has been changed to "' + newLabel + '".';
}
function warningMessage(recordName, column, settings) {
var oldLabel = settings.oldLabel || settings.newValue,
newLabel = settings.newLabel || settings.newValue;
return 'For the ' + settings.noun + ' "' + recordName + '", you are about to change the value of [' + column.Label + '] from "' + oldLabel + '" to "' + newLabel + '".';
}
function failureMessage(recordName, column, settings) {
return 'For the ' + settings.noun + ' ' + recordName + ', the value of [' + column.Label + '] could not be changed.';
}
function renderCheckbox(data, type, full, meta) {
return '<input type="checkbox"' + (data ? ' checked' : '') + ' name="' + getColumnName(meta) + '"/>';
}
function renderMultiSelect(options, data, type, full, meta) {
var columnName = getColumnName(meta),
translate = meta.settings.aoColumns[meta.col].translate,
disabled = options.disabled ? ' disabled="disabled"' : '',
optionTags = Object.keys(options.selectValues)
.map(function (key) {
function optionMatchesElement(element) {
return translate.toOptionValue(element) === key;
}
var selected = data.some(optionMatchesElement) ? ' selected' : '';
return '<option' + disabled + ' value="' + key + '"' + selected + '>' + options.selectValues[key] + '</option>';
});
return '<select multiple class="form-control input-sm' + (options.disabled ? ' disabled' : '') + '" name="' + columnName + '" data-label="' + columnName + '">' + optionTags.join('') + '</select>';
}
function renderDropDown(options) {
if (options.multiSelect) return renderMultiSelect.curry(options);
}
function renderReadonlyText(data) {
return htmlEscape(data) || "";
}
function renderYesOrNo(data) {
return data ? "Yes" : "No";
}
function renderInput(type, name, value, additionalProperties) {
var renderString = '<input type="' + type + '" value="' + (value || '') + '"';
if (name) {
renderString += ' name="' + name + '"';
}
for (var property in additionalProperties) {
if (additionalProperties.hasOwnProperty(property)) {
renderString += additionalProperties[property];
}
}
renderString += ' />';
return renderString;
}
function renderSpan(name, value, additionalProperties) {
var renderString = '<span class="glyphicon glyphicon-pencil" tabindex="0"> </span><span ';
if (name) {
renderString += 'name="' + name + '"';
}
for (var property in additionalProperties) {
if (additionalProperties.hasOwnProperty(property)) {
renderString += additionalProperties[property];
}
}
renderString += '>' + htmlEscape(value) + '</span>';
return renderString;
}
function renderHidden(data, type, full, meta) {
return renderInput('hidden', getColumnName(meta), data);
}
function renderId(data, type, full, meta) {
var columnName = "";
if (meta) {
columnName = getColumnName(meta);
}
return renderInput('hidden', columnName, data, {'class':'class="idField"'});
}
function renderDeleteButton() {
return '<span class="glyphicon glyphicon-remove remove-record" />';
}
function renderNone() { }
function renderTextBox(data, type, full, meta) {
var name = getColumnName(meta);
return renderSpan(name, data || '') + renderInput('text', name, data, {additionalProperties :'style="display: none;" class="form-control input-sm"'});
}
function renderNumber(data, type, full, meta) {
return renderInput("number", getColumnName(meta), data);
}
function renderLocaleDate(data, render) {
var date;
if (data) {
date = new Date(data);
if (date.getFullYear() < 1900) return null;
return render(date);
}
return "";
}
function renderYesOrNo(data) {
return data ? "Yes" : "No";
}
function renderDate(data) {
return renderLocaleDate(data, function (date) { return date.toLocaleString("en-GB"); });
}
function renderDateOnly(data) {
return renderLocaleDate(data, function (date) { return date.toLocaleDateString("en-GB"); });
}
function setUpServerSideTable(settings) {
var expand = settings.expand, urlRoot = settings.urlRoot;
settings.tableId = settings.htmlTableId;
settings.cellSelector = '#' + settings.tableId + ' > tbody > tr > td';
var dt = $('#' + settings.htmlTableId).DataTable({
"autoWidth": false,
"processing": true,
"serverSide": true,
"ajax": function (data, callback, dtSettings) {
function finished(result) {
settings.tableData = dt;
callback(result);
hookupEvents(settings);
$("select[multiple]").multiselect({
buttonClass: 'btn btn-accent',
includeSelectAllOption: true,
onDropdownHide: function (event) {
var $select = $(event.target).closest("td").find("select"),
chosenOptions = $select.val() || [],
select = $select[0],
originalRecord = getOriginalRecord(select, settings),
column = settings.columns.find(function (c) { return c.data === originalRecord.Column.Name; }),
originalChosenOptions = originalRecord.Data[originalRecord.Column.Name].map(function (e) { return column.translate.toOptionValue(e) });
if ($select.hasClass("disabled") || chosenOptions.equals(originalChosenOptions)) return;
var newValue = chosenOptions.map(function (o) { return column.translate.toEntityValue(o, originalRecord.Data); });
select.style.display = 'none';
select.nextSibling.style.display = 'none';
updateWithModalProtection(select, jQuery.extend(settings, {
oldValue: originalRecord,
newValue: newValue,
oldLabel: "[" + (originalChosenOptions.map(function (o) { return $select.find("option[value='" + o + "']").text() }).join(", ") || "<Nothing>") + "]",
newLabel: "[" + (chosenOptions.map(function (o) { return $select.find("option[value='" + o + "']").text() }).join(", ") || "<Nothing>") + "]"
}), {
success: function () {
settings.tableData.ajax.reload();
},
cancelOperation: function () {
settings.tableData.ajax.reload();
}
});
}
});
additionalColumnSetup(settings);
if (settings.ajaxLoaded) settings.ajaxLoaded();
}
if (expand) dtSettings.expand = expand;
serverOData(urlRoot, data, finished, dtSettings);
},
"columns": settings.columns,
"createdRow": settings.createdRow,
"order": settings.order,
"pageLength": settings.length,
"dom": settings.dom || 'lrftip',
"destroy": settings.destroy
});
$(".dataTables_wrapper select").addClass("form-control input-sm");
return dt;
} |
/*
return element: Most of methods return svg canvas object for easy chaining
Initalization:
var container = d3ma.container('#vis').margin({top: 80, left: 80}).box(1400, 600);
var canvas = container.canvas().chart("FinalChart", container.info() );
canvas.draw(data);
Note: container.info() as 2nd parameter is absolutely the core required. It allows each individual layer to know what is the context of the current canvas, passing an object of dataset like container width, height, canvas info including its id, clippath id, width, height, and other info
Syntax:
d3ma.container(selector) // is absolutely required, others are optional.
# container(selector) will take a css selector, which will be the container to append the svg element
Note:
by default, when the svg element initialized, it will create a canvas g element and a defs element contain the clip-path info, random generated cid for clip-path id and id for canvas id attribute.
APIs:
container(selector)
# in general, selector is a single dom element, id in most of the case.
container.margin(_margin)
# Optional, setter/getter margin object, must take an object as value, e.g. {top: 80}, normally come before box()
container.box()
# Optional, by default, it will take the container width and height.
setter/getter retrieve the svg/container width and height, if only one value provide, width and height would be the same
container.canvasW()
# Optional, setter/getter canvas width. Normally, do not need to set explicitly, Use container.box() will auto set the canvas width and height as properly
container.canvasH()
# Optional, setter/getter canvas height. Normally, do not need to set explicitly, Use container.box() will auto set the canvas width and height as properly
container.resize()
# Optional. It should always handle the resize using onResize() or resize() for each instance
Take no args, by default, the graph would not resize when window resize, by calling container.resize() will enable the graph resize when window size changes. It is chainable, could be chained at anywhere after you initialized container object.
container.ratio(_ratio)
#Optional. setter/getter update canvas attribute preserveAspectRatio for resize() purpose. aspectRatio variable in this case.
container.canvas()
# getter. Return the canvas object for easy chaining
container.fluid()
# setter. return the container for easy chaining.
# it will set parentNode 'data-fluid' to 'responsive' on changing the resize calculation
container.info()
# getter. Return all the infomation about this container. expose all the data to the world
include value of marginTop, marginRight, marginBottom, marginLeft, containerW, containerH, canvasW, canvasH, id, cid
*/
// Context is very important here. When dealing with backbone itemview.
// try to limit the current context of the selector, so need to apply the context to limit the selector scope
// context is an optional param, ignore it as needed
d3ma.container = function(selector, context) {
var selection = (context) ? d3.select(context).select(selector) : d3.select(selector);
var margin = { top: 30, right: 10, bottom: 20, left: 40 },
containerW = (context) ? d3ma.$$(context + ' '+ selector).clientWidth : d3ma.$$(selector).clientWidth || selection[0][0].clientWidth || document.body.clientWidth || 960,
containerH = (context) ? d3ma.$$(context + ' '+ selector).clientHeight : d3ma.$$(selector).clientHeight || selection[0][0].clientHeight || window.innerHeight || 540,
canvasW,
canvasH,
container = selection.append('svg'), // Create container, append svg element to the selection
random = Math.floor(Math.random() * 1000),
// Setup the clipPath to hide the content out of the canvas
defs = container.append('defs'),
cid = 'clip-' + random,
clipPath = defs.append('clipPath').attr('id', cid),
rect = clipPath.append('rect'),
// Create a new group element append to svg
// Set the canvas layout with a good amount of offset, has canvas class for easy targeting
id = 'd3ma-' + random,
g = container.append('g').classed('canvas', true).attr({
'class': 'canvas',
'id': id
}),
// http://www.w3.org/TR/SVGTiny12/coords.html#PreserveAspectRatioAttribute
aspectRatio = 'xMidYMid',
scaleRatio = containerW / containerH;
var canvasW = container.canvasW = function(_width, boxCalled) {
if (!arguments.length) { return +(g.attr('width')); }
if(boxCalled) { _width = parseInt(_width) - margin.left - margin.right; }
g.attr('width', _width);
return container;
};
var canvasH = container.canvasH = function(_height, boxCalled) {
if(!arguments.length) { return +(g.attr('height')); }
if(boxCalled) { _height = parseInt(_height) - margin.top - margin.bottom; }
g.attr('height', _height);
return container;
};
container.box = function(_width, _height) {
var m = container.margin();
if(!arguments.length) {
return {
'containerWidth': +canvasW() + (+m.left) + (+m.right),
'containerHeight': +canvasH() + (+m.top) + (+m.bottom)
};
}
// When arguments are more than one, set svg and container width & height
var h = (_height) ? _height : _width;
canvasW(_width, true);
canvasH(h, true);
container.attr({
'width': _width,
'height': h,
'viewBox': '0 0 '+ _width + ' ' + h,
'preserveAspectRatio': aspectRatio
});
scaleRatio = _width / h;
containerW = _width;
containerH = h;
_gTransform(m.left, m.top);
_initClipPath(_width, h, m.left);
return container;
};
container.margin = function(_margin) {
if (!arguments.length) { return margin; }
margin.top = typeof _margin.top !== 'undefined' ? _margin.top : margin.top;
margin.right = typeof _margin.right !== 'undefined' ? _margin.right : margin.right;
margin.bottom = typeof _margin.bottom !== 'undefined' ? _margin.bottom : margin.bottom;
margin.left = typeof _margin.left !== 'undefined' ? _margin.left : margin.left;
// After set the new margin, and maintain svg container width and height, container width and height ratio
container.box(containerW, containerH);
return container;
};
container.ratio = function(_ratio){
if(!arguments.length) { return aspectRatio; }
aspectRatio = _ratio;
container.attr('preserveAspectRatio', _ratio);
return container;
};
// Return the canvas object for easy chaining
container.canvas = function(){
return container.select('g');
};
// Return all the infomation about this container
// expose all the data to the world
container.info = function(){
var margin = container.margin(),
box = container.box();
return {
'marginTop': margin.top,
'marginRight': margin.right,
'marginBottom': margin.bottom,
'marginLeft': margin.left,
'containerW': box.containerWidth,
'containerH': box.containerHeight,
'canvasW': canvasW(),
'canvasH': canvasH(),
'id': '#'+id,
'cid': '#'+cid,
'parentNode': selector
};
};
// Set the canvas element transform attribute, call it when needed
function _gTransform (_marginLeft, _marginTop) {
g.attr('transform', 'translate(' + _marginLeft + ',' + _marginTop + ')');
}
// setup the defs>clip>rect element width and height, x and y attrs
// width and height should equal to the containerW and containerH
// x equal to the -marginLeft, so it starts where the origin of the canvas before the transform
// y equal to the 0 value of the origin, remain static, here use -1 because to show the y-axis tick top
function _initClipPath(_width, _height, _marginLeft) {
rect.attr({
width: _width,
height: _height,
x: -(_marginLeft),
y: -1 // Static, -1 to show the y-axis top tick
});
g.attr('clip-path', 'url(#'+cid+')' );
}
// e.g container.resize().box(1400, 600);
// container.resize() fn could be called from container object, it is chainable
// d3ma.resize() should be used all the time. This resize() is the old implementation
container.resize = function() {
//The Graph will auto scale itself when resize
d3ma.onResize( function() {
var windowWidth = d3ma.windowSize().width;
if ( windowWidth < containerW ) {
container.attr({
'width': windowWidth,
'height': Math.round( windowWidth / scaleRatio )
});
} else {
// reset the graph value to its original width and height
// if it is the same value, do not need to set any more
var _w = +(container.attr('width'));
if( containerW !== _w) {
container.attr({
'width': containerW,
'height': containerH
});
}
}
});
return container;
};
// How to use container.fluid()
// it takes no args. return container for chaining.
// Purpose: to set the current chart as responsive design svg element, like set svg width 100%
//
// How?
// step 1: set svg's parent element ( container ) css box style ex: +box(100%, 360)
// step 2: when/where initialize the container, calling fluid function.
// Ex:
// var clientW = d3ma.$$('#summaryChart').clientWidth,
// clientH = d3ma.$$('#summaryChart').clientHeight;
// container.box( clientW, clientH ).fluid();
// step 3: at the finalChart rendering function, calling the resize function
// Ex: d3ma.resize(key1Line, axis);
//
// It will set parentNode data-fluid attribute on individual chart, then framework will check each chart on this custom value, if it match 'responsive' value, then it will do all the calculation to make a responsive chart. By default, it will expect data-fluid as an empty value, then it will do the fixed layout resizing
container.fluid = function() {
var info = container.info(),
svgEl = d3ma.$$(info.parentNode);
svgEl.setAttribute('data-fluid', 'responsive');
return container;
};
// Set the svg container width and height
// Set the container width and height, and its transform values
container.box(containerW, containerH);
return container;
};
/*
http://www.w3.org/TR/SVGTiny12/coords.html#ViewBoxAttribute
viewBox = "min-x min-y width height" | "none"
separated by white space and/or a comma, which specify a rectangle in viewport space which must be mapped to the bounds of the viewport established by the given element, taking into account the 'preserveAspectRatio' attribute. If specified, an additional transformation is applied to all descendants of the given element to achieve the specified effect.
preserveAspectRatio = ["defer"] <align> [<meet>]
typically when using the 'viewBox' attribute, it is desirable that the graphics stretch to fit non-uniformly to take up the entire viewport. In other cases, it is desirable that uniform scaling be used for the purposes of preserving the aspect ratio of the graphics.
*/
|
_frame.app_main.page['about'] = {}
_frame.app_main.page['about'].journal_parse = function (raw) {
var searchRes
, scrapePtrn = /\[\[([^\:]+)\:([0-9]+)\]\]/gi
, resultHTML = markdown.toHTML(raw)
while ((searchRes = scrapePtrn.exec(raw)) !== null) {
try {
resultHTML = resultHTML.replace(searchRes[0], _tmpl['link_' + searchRes[1].toLowerCase()](searchRes[2], null, true))
} catch (e) { }
}
searchRes = null
scrapePtrn = /\[\[([^\:]+)\:([0-9]+)\:TEXT\]\]/gi
while ((searchRes = scrapePtrn.exec(raw)) !== null) {
try {
resultHTML = resultHTML.replace(searchRes[0], _tmpl['textlink_' + searchRes[1].toLowerCase()](searchRes[2], null, true))
} catch (e) { }
}
return resultHTML
}
_frame.app_main.page['about'].journaltitle = function (d, tagName) {
d = d || {}
tagName = tagName || 'h3'
return '<h3>'
+ (d['hotfix']
? 'HOTFIX - '
: '')
+ (d['type'] == 'app'
? ''
: (d['type'] == 'app-db' ? 'DB' : d['type']).toUpperCase() + ' / ')
+ d['version']
+ '<small>' + (d['date'] ? d['date'] : 'WIP') + '</small>'
+ '</h3>'
}
_frame.app_main.page['about'].init = function (page) {
/*
var latestVersionSection = $('[data-version-app]:first-of-type')
,latestVersion = latestVersionSection.attr('data-version-app').split('.')
,latestVersionSub = latestVersion[0] + '.' + latestVersion[1]
*/
//$('[data-version-app^="'+latestVersionSub+'"]')
let i = 0;
function addUpdateJournal(updateData) {
// let id = 'update_journal_' + (i++)
// , checkbox = $('<input type="checkbox" id="' + (id) + '"/>')
// .prop('checked', (i < 3 ? true : false))
// .appendTo(page)
// , section = $('<section class="update_journal" data-version-' + updateData['type'] + '="' + updateData['version'] + '"/>')
// .append(
// $('<label for="' + id + '"/>')
// .html(_frame.app_main.page['about'].journaltitle(updateData))
// )
// .appendTo(page)
// try {
// $(_frame.app_main.page['about'].journal_parse(updateData['journal'])).appendTo(section)
// } catch (e) {
// _g.error(e)
// checkbox.remove()
// section.remove()
// }
let journal = new Journal(updateData)
journal.genSection((i < 3)).appendTo(page)
i++;
}
var promise_chain = Q.fcall(function () { })
// 开始异步函数链
promise_chain
// 获取全部开发中的更新日志
.then(function () {
var deferred = Q.defer()
_db.updates.find({ 'date': "" }).sort({ 'date': -1, 'version': -1 }).exec(function (err, docs) {
docs.forEach(function (doc) {
addUpdateJournal(doc)
})
deferred.resolve(err)
})
return deferred.promise
})
// 获取全部已更新的更新日志
.then(function () {
var deferred = Q.defer()
_db.updates.find({ $not: { 'date': "" } }).sort({ 'date': -1, 'version': -1 }).exec(function (err, docs) {
docs.forEach(function (doc) {
addUpdateJournal(doc)
})
deferred.resolve(err)
})
return deferred.promise
})
}
class Journal {
constructor(data) {
this.data = data;
// this.content
}
genTitle(tagName = 'h3') {
return $(
`<${tagName}>`
+ (this.data.hotfix
? '[hotfix] '
: ''
)
+ (this.data.type == 'app'
? ''
: (this.data.type == 'app-db' ? 'DB' : this.data.type).toUpperCase()
)
// + (this.data.version.replace(/\./g, '-') == this.data.date
// ? ''
// : this.data.version
// )
+ (this.data.type == 'app'
? this.data.version
: ''
)
+ '<small>' + (this.data.date ? this.data.date : 'WIP') + '</small>'
+ `</${tagName}>`
)
}
genContent() {
let raw = this.data.journal
, searchRes
, scrapePtrn = /\[\[([^\:]+)\:([0-9]+)\]\]/gi
, resultHTML = markdown.toHTML(raw)
while ((searchRes = scrapePtrn.exec(raw)) !== null) {
try {
resultHTML = resultHTML.replace(
searchRes[0],
_tmpl['link_' + searchRes[1].toLowerCase()](searchRes[2], null, true)
)
} catch (e) { }
}
searchRes = null
scrapePtrn = /\[\[([^\:]+)\:([0-9]+)\:TEXT\]\]/gi
while ((searchRes = scrapePtrn.exec(raw)) !== null) {
try {
resultHTML = resultHTML.replace(
searchRes[0],
_tmpl['textlink_' + searchRes[1].toLowerCase()](searchRes[2], null, true)
)
} catch (e) { }
}
this.content = $(resultHTML)
return this.content
}
genSection(defaultShow) {
let id = 'update_journal_' + this.data._id
, checkbox = $('<input type="checkbox" id="' + (id) + '"/>')
.prop('checked', (defaultShow ? true : false))
.on('change', e => {
if (e.target.checked)
this.show()
})
this.section = $('<section class="update_journal" data-version-' + this.data.type + '="' + this.data.version + '"/>')
.append($(`<label for="${id}"/>`).append(this.genTitle()))
if (defaultShow)
this.show()
return this.section.add(
checkbox.insertBefore(this.section)
)
// try {
// let content = this.genContent()
// } catch (e) {
// _g.error(e)
// checkbox.remove()
// section.remove()
// return $()
// }
}
show() {
if (!this.content)
this.genContent().appendTo(this.section)
}
} |
import Vue from 'vue';
import './mdCore';
import mdTable from 'vue-material/dist/components/mdTable';
import 'vue-material/dist/components/mdTable/index.css';
if (!mdTable.installed) {
Vue.use(mdTable);
}
export default mdTable |
import {Task} from '../components/tasks/tasks.service.js';
export class MainController {
constructor ($interval, $log, tasksService, speechService) {
'ngInject';
const vm = this,
currentTime = getPomodoroTime();
Object.assign(vm, {
// timer
timeLeft: formatTime(currentTime),
currentTime,
// tasks
tasks: tasksService.getTasks(),
newTask: Task(),
hasTasks(){ return this.tasks.length > 0; },
filterTerm: '',
// services
$interval,
$log,
tasksService,
speechService
});
// angular and getters don't seem to work
// very well together
vm.activeTask = this.tasks.find(t => t.isActive);
}
addNewTask(){
this.tasks.push(this.newTask);
if (this.tasks.length === 1) this.setTaskAsActive(this.newTask);
this.tasksService.saveTask(this.newTask);
this.newTask = Task();
}
removeTask(task){
const index = this.tasks.indexOf(task);
if (index !== -1){
if (task.isActive) this.setNextTaskAsActive(index);
this.tasks.splice(index,1);
this.tasksService.removeTask(task);
}
}
archiveTask(task){
const index = this.tasks.indexOf(task);
if (index !== -1){
let [taskToArchive] = this.tasks.splice(index,1);
this.tasksService.archiveTask(taskToArchive);
}
}
setNextTaskAsActive(index){
if (this.tasks.length > index + 1) this.setTaskAsActive(this.tasks[index+1]);
else if (index > 0) this.setTaskAsActive(this.tasks[index-1]);
}
setTaskAsActive(task){
const currentActiveTask = this.tasks.find(t => t.isActive);
if (currentActiveTask) currentActiveTask.isActive = false;
task.isActive = true;
this.activeTask = task;
}
startPomodoro(){
if (this.performingTask) throw new Error("Can't start a new pomodoro while one is already running");
this.performingTask = true;
this.setTimerInterval(getPomodoroTime());
this.speechService.say('ring ring ring start pomodoro now! Time to kick some ass!');
}
cancelPomodoro(){
this.stopPomodoro();
this.resetPomodoroTimer();
}
advanceTimer(){
this.$log.debug('advancing timer 1 second');
this.currentTime -= 1;
if (this.currentTime === 0) {
if (this.performingTask) this.completePomodoro();
else this.completeRest();
}
else this.timeLeft = formatTime(this.currentTime);
}
stopPomodoro(){
this.performingTask = false;
this.cleanInterval();
this.speechService.say('Stop! Time to rest and reflect!');
}
completePomodoro(){
this.activeTask.workedPomodoros++;
this.stopPomodoro();
this.startRest();
}
startRest(){
this.resting = true;
this.setupRestTime();
this.setTimerInterval(getRestTime(this.activeTask));
}
setTimerInterval(seconds){
//console.log('create interval');
this.cleanInterval(); // make sure we release all intervals
this.timerInterval = this.$interval(this.advanceTimer.bind(this), 1000, seconds);
}
completeRest(){
this.cleanInterval();
this.resting = false;
this.resetPomodoroTimer();
}
cleanInterval(){
if (this.timerInterval) {
//console.log('stopping interval');
this.$interval.cancel(this.timerInterval);
this.timerInterval = null;
}
}
resetPomodoroTimer(){
this.setTime(getPomodoroTime());
}
setupRestTime(){
this.setTime(getRestTime(this.activeTask));
}
setTime(time){
this.currentTime = time;
this.timeLeft = formatTime(this.currentTime);
}
}
function getPomodoroTime(){
return 25*60;
}
function getRestTime(activeTask){
if (activeTask.workedPomodoros % 4 === 0) return 20*60;
return 5*60;
}
function formatTime(time){
const minutesLeft = Number.parseInt(time/60),
secondsLeft = Math.round((time/60 - minutesLeft) * 60),
formattedMinutesLeft = formatDigits(minutesLeft),
formattedSecondsLeft = formatDigits(secondsLeft);
return `${formattedMinutesLeft}:${formattedSecondsLeft}`
}
function formatDigits(digits){
return digits < 10 ? "0" + digits : digits;
}
|
'use strict';
var env = require('./env.js'),
express = require('express'),
morgan = require('morgan'),
compression = require('compression'),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
session = require('express-session'),
passport = require('passport');
module.exports = function () {
var app = express();
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
} else if (process.env.NODE_ENV === 'development') {
app.use(compression);
}
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(session({
saveUninitialized: true,
resave: true,
secret: env.sessionSecret
}));
app.use(passport.initialize());
app.use(passport.session());
require('../app/route/index.server.route.js')(app);
require('../app/route/user.server.route.js')(app);
require('../app/route/post.server.route.js')(app);
require('../app/route/tag.server.route.js')(app);
require('../app/route/comment.server.route.js')(app);
app.use(express.static('./public'));
return app;
}; |
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
export default Model.extend({
name: attr('string'),
package: attr('raw'),
active: attr('boolean'),
warnings: attr('raw'),
activate() {
let adapter = this.store.adapterFor(this.constructor.modelName);
return adapter.activate(this).then(() => {
// the server only gives us the newly active theme back so we need
// to manually mark other themes as inactive in the store
let activeThemes = this.store.peekAll('theme').filterBy('active', true);
activeThemes.forEach((theme) => {
if (theme !== this) {
// store.push is necessary to avoid dirty records that cause
// problems when we get new data back in subsequent requests
this.store.push({data: {
id: theme.id,
type: 'theme',
attributes: {active: false}
}});
}
});
return this;
});
}
});
|
/*
* @license MIT
* @file
* @copyright KeyW Corporation 2016
*/
(function () {
"use strict";
var _theme;
angular
.module('mdColors',['mdColors'])
.config(['$mdThemingProvider', function($mdThemingProvider){
_theme = $mdThemingProvider.theme();
}])
.directive('mdStyleColor', ['$mdColorPalette',
function ($mdColorPalette) {
return {
restrict: 'A',
scope: { mdStyleColor: '=' },
/**
* Description
* @method link
* @param {} scope
* @param {} element
* @param {} attrs
*/
link: function (scope, element, attrs) {
for (var p in scope.mdStyleColor) {
if (scope.mdStyleColor.hasOwnProperty(p)) {
var themeColors = _theme.colors;
var split = (scope.mdStyleColor[p] || '').split('.');
if (split.length < 2) split.unshift('primary');
var hueR = split[1] || 'hue-1'; // 'hue-1'
var colorR = split[0] || 'primary'; // 'warn'
// Absolute color: 'orange'
var colorA = themeColors[colorR] ?
themeColors[colorR].name : colorR;
// Absolute Hue: '500'
var hueA =
themeColors[colorR] ?
themeColors[colorR].hues[hueR] || hueR :
hueR;
var colorValue = $mdColorPalette[colorA][hueA] ?
$mdColorPalette[colorA][hueA].value :
$mdColorPalette[colorA]['500'].value;
element.css(p, 'rgb('+colorValue.join(',')+')');
}
}
}
}
}]);
}());
|
// For this challenge, take the integer from process.argv[2] and write it as the first
// element in a single element Uint32Array. Then create a Uint16Array from the Array
// Buffer of the Uint32Array and log out to the console the JSON stringified version
// of the Uint16Array.
var ui32 = new Uint32Array(1)
ui32[0] = process.argv[2]
var ui16 = new Uint16Array(ui32.buffer)
console.log(JSON.stringify(ui16))
|
/*
See README.md
*/
var Service, Characteristic, types;
var request = require('request');
// Handle registration with homebridge
module.exports = function(homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
types = homebridge.hapLegacyTypes;
homebridge.registerPlatform("homebridge-wireless-sensor-tag", "wireless-sensor-tag", WirelessTagPlatform);
}
// Platform object for the wireless tags. Represents the wireless tag manager
function WirelessTagPlatform(log,config) {
this.username = config.username;
this.password = config.password;
this.queryFrequency = config.queryFrequency;
this.log = log;
this.tagMap = {};
this.tagList = [];
this.ignoreList = (config.ignoreList == undefined) ? [] : config.ignoreList;
}
WirelessTagPlatform.prototype.shouldIgnore = function(deviceData) {
if(deviceData != undefined && deviceData.name != undefined) {
if(this.ignoreList.indexOf(deviceData.name) > -1) {
return true;
}
}
return false;
}
// Forms a valid request to authenticate against the wireless tag manager. Calls handleResult with a boolean indicating
// success or failure.
WirelessTagPlatform.prototype.sendAuthentication = function(handleResult) {
request({
method: 'POST',
uri: 'http://www.mytaglist.com/ethAccount.asmx/Signin',
json: true,
jar: true,
gzip: true,
body: { email: this.username, password: this.password }
}, function (error, response, body) {
if(error) {
handleResult(true);
} else {
handleResult(response.statusCode!=200);
}
});
}
// Forms a valid request to get the latest tag list. Calls handleResult with a boolean indicating success or failure.
WirelessTagPlatform.prototype.getTagList = function(handleResult) {
request({
method: 'POST',
uri: 'http://www.mytaglist.com/ethClient.asmx/GetTagList2',
json: true,
jar: true,
gzip: true,
body: {}
}, function (error, response, body) {
if(error) {
handleResult(true,body);
} else {
handleResult(response.statusCode!=200,body);
}
});
}
// Does a request to the server to refresh the tag data. Authenticate every time as not sure how often the
// authentication requires refreshing. New tags we see get added to the tag map and the tag list. New tags
// added AFTER startup will be tracked internally but not exposed as a device as frankly I don't know how
// to do that dynamically.
WirelessTagPlatform.prototype.refreshTagData = function(complete) {
var that = this;
// Auth
this.sendAuthentication(function(failed) {
if(!failed) {
// Gets the tag list
that.getTagList(function(innerFailure, body) {
if(!innerFailure) {
for(var index = 0; index < body.d.length; index++) {
var uuid = body.d[index].uuid;
// We haven't seen the tag yet, add it
if(that.tagMap[uuid] == null) {
if(!that.shouldIgnore(body.d[index])) {
var newTag = new WirelessTagAccessory(that.log, body.d[index]);
that.tagMap[uuid] = newTag;
that.tagList.push(newTag);
}
// We have, just update it.
} else {
that.tagMap[uuid].handleUpdate(body.d[index]);
}
}
complete(true);
} else {
that.log("Failed getting tag list");
complete(false);
}
});
} else {
that.log("Failed authenticating to tag list");
complete(false);
}
});
}
// Handles the periodic timer. Reports success or failure and sets the next timer period.
WirelessTagPlatform.prototype.handleTimer = function() {
var that = this;
this.log("Starting update of wireless tags from tag manager");
this.refreshTagData(function(success) {
if(success) {
that.log("Updated wireless tag data");
} else {
that.log("Failed to update wireless tags");
}
// Hack as I was seeing issues with an undefined queryFrequency. Believe I have fixed it but keeping the
// minimum in to keep us from spamming the service. Also prevents values below 5000ms.
if(that.queryFrequency == undefined || that.queryFrequency < 5000) {
that.log("Error ... invalid query frequency, setting to 20000ms default");
that.queryFrequency = 20000;
} else {
setTimeout(that.handleTimer.bind(that), that.queryFrequency);
}
});
}
// Responds to the homebridge platform through calling callback once list of accessories is identified.
WirelessTagPlatform.prototype.accessories = function(callback) {
var that = this;
that.refreshTagData(function(success) {
that.log("Completed getting devices. Result="+success);
if(success) {
that.log("Authenticated and got tag list. Enumerating tags as accessories");
that.handleTimer();
callback(that.tagList);
} else {
that.log("Could not get tags, no accessories exposed");
callback([]);
}
});
}
// Represents a single tag
function WirelessTagAccessory(log,deviceData) {
this.log = log;
this.handleUpdate(deviceData);
}
// Refreshes tag data from the device update data
WirelessTagAccessory.prototype.handleUpdate = function(deviceData) {
this.isOutOfRange = deviceData.OutOfRange;
this.isAlive = deviceData.alive;
this.batteryRemaining = deviceData.batteryRemaining;
this.uuid = deviceData.uuid;
this.tagType = deviceData.tagType;
this.temperature = deviceData.temperature;
this.name = deviceData.name;
if(deviceData.cap != undefined) {
this.humidity = Math.round(deviceData.cap);
} else {
this.humidity = 0.0;
}
this.uuid_base = this.uuid;
// Protections to ensure we don't set the current characteristic value whens services are not yet registered.
if(this.tempService != null && this.tempService != undefined) {
this.tempService
.setCharacteristic(Characteristic.CurrentTemperature, this.temperature);
}
if(this.humidityService != null && this.humidityService != undefined) {
this.humidityService
.setCharacteristic(Characteristic.CurrentRelativeHumidity, this.humidity);
}
}
// Handles getting the temperature in format needed by homebridge. Luckily this is just the raw value in degrees C
WirelessTagAccessory.prototype.getTemperature = function(callback) {
callback(null,this.temperature);
}
// Handles getting the humidity in format needed by homebridge.
WirelessTagAccessory.prototype.getHumidity = function(callback) {
callback(null,this.humidity);
}
// Translates tag state into an occupancy value. If tag is inactive or out of range occupancy is false
WirelessTagAccessory.prototype.getOccupancy = function(callback) {
var isAway = false;
if(this.isOutOfRange == undefined) {
isAway = true;
} else if(this.isOutOfRange) {
isAway = true;
} else if(!this.isAlive) {
isAway = true;
}
callback(null,isAway ? Characteristic.OccupancyDetected.OCCUPANCY_NOT_DETECTED : Characteristic.OccupancyDetected.OCCUPANCY_DETECTED);
}
// Sets up the information, temperature and occupancy services.
WirelessTagAccessory.prototype.getServices = function() {
this.informationService = new Service.AccessoryInformation();
this.informationService
.setCharacteristic(Characteristic.Manufacturer, "SmartHome")
.setCharacteristic(Characteristic.Model, "Wireless Sensor Tag Type="+this.tagType)
.setCharacteristic(Characteristic.SerialNumber, this.uuid);
this.tempService = new Service.TemperatureSensor();
this.tempService
.getCharacteristic(Characteristic.CurrentTemperature)
.on('get', this.getTemperature.bind(this));
this.humidityService = new Service.HumiditySensor();
this.humidityService
.getCharacteristic(Characteristic.CurrentRelativeHumidity)
.on('get', this.getHumidity.bind(this));
this.occupancyService = new Service.OccupancySensor();
this.occupancyService
.getCharacteristic(Characteristic.OccupancyDetected)
.on('get', this.getOccupancy.bind(this));
return [this.informationService, this.tempService, this.occupancyService, this.humidityService];
}
module.exports.platform = WirelessTagPlatform;
module.exports.accessory = WirelessTagAccessory;
|
// FacetCollection class
var FacetCollection = function(collection) {
// give FacetCollection instances ability to handle Backbone Events
_.extend(this, Backbone.Events);
// init local variables
var _self = this,
_facets = {}, // facets list
_cidModelMap = {}, // an hash containing cid/model pairs used for fast model lookup
_activeModels = {}, // cids of the active models for each facet (a facetName -> [cid] map)
_vent = _.extend({}, Backbone.Events), // a local event handler used for local events
_filters = {}, // an hashmap of custom filters
_sortDir = 'asc', // default sort direction
_sortAttr,
_facetsOrder,
_ownReset = false,
// inits the models map
_initModelsMap = function() {
// clear content of _cidModelMap if any
for(var cid in _cidModelMap) {
if(_cidModelMap.hasOwnProperty(cid)) {
delete _cidModelMap[cid];
}
}
// generate a clone for each model and add it to the map with the cid as key
collection.each(function(model) {
var clone = model.clone();
clone.cid = model.cid;
_cidModelMap[model.cid] = clone;
});
},
// deletes the entry for the facet with the given name from the facets hash
_removeFacet = function(facetName, silent) {
delete _facets[facetName];
delete _activeModels[facetName];
_resetCollection();
if(silent !== true) {
_self.trigger('removeFacet', facetName);
}
},
// fetch (or create if not existing) a facetData object from the facets hash
_begetFacet = function(facetName, operator) {
var facetData = _facets[facetName];
if(facetData && facetData.operator === operator) {
return facetData;
} else {
var facet = new Facet(facetName, _cidModelMap, _vent, operator);
// create an entry for the new facet in the facet to active models map
_activeModels[facetName] = [];
// add operator property to the object along the actual facet reference
return {
facet: facet,
operator : operator
};
}
},
_filter = function(facetName, cids) {
// set active cids for current facet
_activeModels[facetName] = cids;
// refresh collection according to new facet filters
_resetCollection();
},
_filterBy = function(facetName, facetValue, cids, silent) {
_filter(facetName, cids);
if(silent !== true){
// expose filter event
_self.trigger('filter', facetName, facetValue);
}
},
_unfilterBy = function(facetName, facetValue, cids, silent) {
_filter(facetName, cids);
if(silent !== true){
// expose unfilter event
_self.trigger('unfilter', facetName, facetValue);
}
},
_resetCollection = function() {
var modelsCids = [], models = [], cid, key, filterName, filterFn;
// if no values are selected, return all models
for(cid in _cidModelMap) {
if(_cidModelMap.hasOwnProperty(cid)) {
modelsCids.push(cid);
}
}
// otherwise merge the active models of each facet
for(key in _activeModels) {
if (_activeModels.hasOwnProperty(key)) {
if(_facets[key].facet.toJSON().data.selected) {
if(_facets[key].operator === 'or') {
modelsCids = _.union(modelsCids, _activeModels[key]);
} else {
modelsCids = _.intersection(modelsCids, _activeModels[key]);
}
}
}
}
filterFn = function(cid) {
return filter(_cidModelMap[cid]);
};
// filter using the added filter functions
for(filterName in _filters) {
if(_filters.hasOwnProperty(filterName)) {
var filter = _filters[filterName];
if(filter instanceof Function) {
modelsCids = _.filter(modelsCids, filterFn);
}
}
}
// sort the models by cid
modelsCids.sort();
// create active models array retrieving clones from the cid to model hash
for(var i = 0, len = modelsCids.length; i < len; i += 1) {
models.push(_cidModelMap[modelsCids[i]]);
}
// notify facets to recompute active facet values count
_vent.trigger('resetCollection', modelsCids);
_ownReset = true;
// reset the collecton with the active models
collection.reset(models);
_ownReset = false;
},
// triggered whenever the Backbone collection is reset
_resetOrigCollection = function() {
if(_ownReset) {
return;
}
_initModelsMap();
// notify facets to recompute
_vent.trigger('resetOrigCollection', _cidModelMap);
},
// triggered whenever a new Model is added to the Backbone collection
_addModel = function(model) {
// create a clone of the model and add it to the cid to model map
var clone = model.clone();
clone.cid = model.cid;
_cidModelMap[model.cid] = clone;
// notify facets about the added model
_vent.trigger('addModel', model);
},
// // triggered whenever a Model instance is removed from the Backbone collection
_removeModel = function(model) {
// delete model clone from the cid to model map
delete _cidModelMap[model.cid];
// notify facets about the removed model
_vent.trigger('removeModel', model);
var anyActive = _.any(_facets, function(facetData) {
return facetData.facet.toJSON().data.selected;
});
if(!anyActive) {
_resetCollection();
}
},
// triggered whenever a model is changed
_modifyModel = function(model) {
// delete old clone from models cache
delete _cidModelMap[model.cid];
// store new model clone with the changes in models cache
var clone = model.clone();
clone.cid = model.cid;
_cidModelMap[model.cid] = clone;
// notify facets about the changed model
_vent.trigger('changeModel', model);
var anyActive = _.any(_facets, function(facetData) {
return facetData.facet.toJSON().data.selected;
});
if(!anyActive) {
_resetCollection();
}
},
_sort = function(silent) {
collection.comparator = function(m1,m2) {
var v1 = _getValue(m1, _sortAttr),
v2 = _getValue(m2, _sortAttr),
val1,
val2;
// check if value is a number
if(isNaN(v1) || isNaN(v2)) {
val1 = Date.parse(v1); // check if value is a date
val2 = Date.parse(v2);
if(isNaN(val1) || isNaN(val2)){
val1 = v1; // otherwise is a string
val2 = v2;
}
} else {
val1 = parseFloat(v1, 10);
val2 = parseFloat(v2, 10);
}
if(_sortDir === "asc") {
if(val1 && val2) {
return (val1 > val2) - (val1 < val2);
} else {
if(val1) {
return 1;
}
if(val2) {
return -1;
}
}
} else {
if(val1 && val2) {
return (val1 < val2) - (val1 > val2);
} else {
if(val1) {
return -1;
}
if(val2) {
return 1;
}
}
}
};
collection.sort();
if(silent !== true) {
_self.trigger('sort', _sortAttr, _sortDir);
}
};
// creates a Facet or fetches it from the facets map if it was already created before
// use the given operator if any is given and it is a valid value, use default ('and') otherwise
this.facet = function(facetName, operator, silent) {
var op = (operator && (operator === 'and' || operator === 'or')) ? operator : 'and';
_facets[facetName] = _begetFacet(facetName, op);
_resetCollection();
if(silent !== true){
this.trigger('facet', facetName);
}
return _facets[facetName].facet;
};
// returns a JSON array containing facet JSON objects for each facet added to the collection
this.toJSON = function() {
var key, facetData, facetJSON, facetPos, facets = [], sortedFacets = [];
for (key in _facets) {
if (_facets.hasOwnProperty(key)) {
facetData = _facets[key];
facetJSON = facetData.facet.toJSON();
// add information about the type of facet ('or' or 'and' Facet)
facetJSON.data.operator = facetData.operator;
if(_facetsOrder && _facetsOrder instanceof Array) {
facetPos = _.indexOf(_facetsOrder, facetJSON.data.name);
if(facetPos !== -1) {
sortedFacets[facetPos] = facetJSON;
} else {
facets.push(facetJSON);
}
} else {
facets.push(facetJSON);
}
}
}
return sortedFacets.concat(facets);
};
// removes all the facets assigned to this collection
this.clear = function(silent) {
var key;
for (key in _facets) {
if (_facets.hasOwnProperty(key)) {
_facets[key].facet.remove();
delete _facets[key];
}
}
// resets original values in the collection
var models = [];
for (key in _cidModelMap) {
if (_cidModelMap.hasOwnProperty(key)) {
models.push(_cidModelMap[key]);
}
}
collection.reset(models);
// reset active models
_activeModels = {};
if(silent !== true) {
this.trigger('clear');
}
return this;
};
// deselect all the values from all the facets
this.clearValues = function(silent) {
var key;
for (key in _facets) {
if (_facets.hasOwnProperty(key)) {
_facets[key].facet.clear();
}
}
// resets original values in the collection
var models = [];
for (key in _cidModelMap) {
if (_cidModelMap.hasOwnProperty(key)) {
models.push(_cidModelMap[key]);
}
}
collection.reset(models);
// reset active models
_activeModels = {};
if(silent !== true) {
this.trigger('clearValues');
}
return this;
};
// removes the collection from the _collections cache and
// removes the facetrid property from the collection
this.remove = function() {
var facetrid = collection.facetrid;
this.clear(true);
// detach event listeners from collection instance
collection.off('reset', _resetOrigCollection);
collection.off('add', _addModel);
collection.off('remove', _removeModel);
collection.off('change', _modifyModel);
delete collection.facetrid;
delete _collections[facetrid];
};
// reorders facets in the JSON output according to the array of facet names given
this.facetsOrder = function(facetNames, silent) {
_facetsOrder = facetNames;
if(silent !== true){
this.trigger('facetsOrderChange', facetNames);
}
return this;
};
// sorts the collection by the given attribute
this.sortBy = function(attrName, silent) {
_sortAttr = attrName;
_sort(silent);
return this;
};
// sorts the collection by ascendent sort direction
this.asc = function(silent) {
_sortDir = 'asc';
_sort(silent);
return this;
};
// sorts the collection by descendent sort direction
this.desc = function(silent) {
_sortDir = 'desc';
_sort(silent);
return this;
};
// adds a filter
this.addFilter = function(filterName, filter, silent) {
if(filter && filterName) {
_filters[filterName] = filter;
_resetCollection(silent);
}
return this;
};
// removes a filter
this.removeFilter = function(filterName, silent) {
if(filterName) {
delete _filters[filterName];
_resetCollection(silent);
}
return this;
};
// removes all the filters
this.clearFilters = function(silent) {
for(var filterName in _filters) {
if(_filters.hasOwnProperty(filterName)) {
delete _filters[filterName];
}
}
_resetCollection(silent);
return this;
};
// returns a reference to the Backbone.Collection instance
this.collection = function(){
return collection;
};
// returns the original collection length
this.origLength = function() {
return _.size(_cidModelMap);
};
// returns the facet list, which can be used for iteration
this.facets = function(){
return _.pluck(_facets, 'facet');
};
this.initFromSettingsJSON = function(json) {
var facetCollection, facetr, facets, sort, facetData, attr,
lab, eop, iop, fsort, cust, values, facet, i, j, k, len, len2;
facetr = Backbone.Facetr;
facetCollection = facetr(collection);
facets = json.facets;
sort = json.sort;
if(facets != null) {
for(i = 0, len = facets.length; i < len; i += 1) {
facetData = facets[i];
attr = facetData.attr;
lab = facetData.lab;
eop = facetData.eop;
iop = facetData.iop;
fsort = facetData.sort;
cust = facetData.cust;
values = facetData.vals;
facet = facetCollection.facet(attr, eop);
if(lab) {
facet.label(lab);
}
switch(fsort.by){
case 'count' : {
facet.sortByCount();
} break;
case 'activeCount' : {
facet.sortByActiveCount();
} break;
default:{
facet.sortByValue();
}
}
facet[fsort.direction]();
if(cust){
for(k in cust){
if(cust.hasOwnProperty(k)){
facet.customData(k, cust[k]);
}
}
}
for(j = 0, len2 = values.length; j < len2; j += 1) {
facet.value(values[j], iop);
}
}
}
if(sort != null) {
var sattr = sort.by,
sdir = sort.dir;
if(sattr) {
facetr(collection).sortBy(sattr);
}
if(sdir) {
facetr(collection)[sdir]();
}
}
this.trigger('initFromSettingsJSON');
return this;
};
this.settingsJSON = function() {
var json, facet, facetJSON, values, activeValues;
json = {};
if(_sortAttr && _sortDir) {
json.sort = {
'by' : _sortAttr,
'dir' : _sortDir
};
}
if(_.size(_facets) !== 0) {
json.facets = [];
for(facet in _facets) {
if(_facets.hasOwnProperty(facet)) {
facetJSON = _facets[facet].facet.toJSON();
values = _.pluck(facetJSON.values, 'active');
activeValues = [];
for(var i = 0, len = values.length; i < len; i += 1) {
if(values[i]) {
activeValues.push(facetJSON.values[i].value);
}
}
json.facets.push({
'attr' : facetJSON.data.name,
'lab' : facetJSON.data.label,
'eop' : facetJSON.data.extOperator,
'iop' : facetJSON.data.intOperator,
'sort' : facetJSON.data.sort,
'cust' : facetJSON.data.customData,
'vals' : activeValues
});
}
}
}
return json;
};
// init models map
_initModelsMap();
// remove the facet from the facets hash whenever facet.remove() is invoked
_vent.on('removeFacet', _removeFacet, this);
// filter collection whenever facet.value(value) and facet.removeValue(value) are invoked
_vent.on('value', _filterBy, this);
_vent.on('removeValue clear', _unfilterBy, this);
// bind Backbone Collection event listeners to FacetCollection respective actions
collection.on('reset', _resetOrigCollection);
collection.on('add', _addModel);
collection.on('remove', _removeModel);
collection.on('change', _modifyModel);
}; |
/* */
"format cjs";
(function(process) {
!function(a) {
"use strict";
var b = null,
c = null;
!function(c) {
function a(d) {
if (b[d])
return b[d].exports;
var e = b[d] = {
exports: {},
id: d,
loaded: !1
};
return c[d].call(e.exports, e, e.exports, a), e.loaded = !0, e.exports;
}
var b = {};
return a.m = c, a.c = b, a.p = "", a(0);
}([function(b, c, a) {
a(50), a(2), a(3), a(4), a(5), a(6), a(7), a(8), a(9), a(10), a(11), a(12), a(13), a(14), a(15), a(16), a(17), a(18), a(19), a(20), a(21), a(22), a(23), a(24), a(25), a(26), a(27), a(28), a(29), a(30), a(31), a(32), a(33), a(34), a(35), a(36), a(37), a(38), a(39), a(40), a(41), a(42), a(43), a(44), a(45), a(46), a(47), a(48), a(49), a(1), a(51), a(52), a(53), a(54), a(55), a(56), a(57), a(58), a(59), a(60), a(61);
}, function(v, u, b) {
function e(b, f) {
return this instanceof e ? (this[c] = i(b), this[d] = !!f, a) : new e(b, f);
}
function m(b) {
function a(a, b, e) {
this[c] = i(a), this[d] = a[d], this[j] = s(b, e, a[d] ? 2 : 1);
}
return o(a, "Chain", b, h), n(a.prototype, r.that), a;
}
var r = b(63),
s = b(84),
k = b(65).safe,
g = b(67),
f = b(81),
p = b(89),
d = k("entries"),
j = k("fn"),
c = k("iter"),
l = b(85),
i = f.get,
n = f.set,
o = f.create;
o(e, "Wrapper", function() {
return this[c].next();
});
var h = e.prototype;
n(h, function() {
return this[c];
});
var t = m(function() {
var a = this[c].next();
return a.done ? a : f.step(0, l(this[c], this[j], a.value, this[d]));
}),
q = m(function() {
for (; ; ) {
var a = this[c].next();
if (a.done || l(this[c], this[j], a.value, this[d]))
return a;
}
});
b(91)(h, {
of: function(a, b) {
p(this, this[d], a, b);
},
array: function(c, d) {
var b = [];
return p(c != a ? this.map(c, d) : this, !1, b.push, b), b;
},
filter: function(a, b) {
return new q(this, a, b);
},
map: function(a, b) {
return new t(this, a, b);
}
}), e.isIterable = f.is, e.getIterator = i, g(g.G + g.F, {$for: e});
}, function(N, M, e) {
function F(a) {
var e = i[a] = b.set(k(g.prototype), C, a);
return B && m && q(j, a, {
configurable: !0,
set: function(b) {
d(this, c) && d(this[c], a) && (this[c][a] = !1), q(this, a, p(1, b));
}
}), e;
}
function r(a, b, e) {
return e && d(i, b) ? (e.enumerable ? (d(a, c) && a[c][b] && (a[c][b] = !1), e = k(e, {enumerable: p(0, !1)})) : (d(a, c) || f(a, c, p(1, {})), a[c][b] = !0), q(a, b, e)) : f(a, b, e);
}
function u(a, b) {
H(a);
for (var c,
d = K(b = l(b)),
e = 0,
f = d.length; f > e; )
r(a, c = d[e++], b[c]);
return a;
}
function E(b, c) {
return c === a ? k(b) : u(k(b), c);
}
function L(a) {
var b = I.call(this, a);
return b || !d(this, a) || !d(i, a) || d(this, c) && this[c][a] ? b : !0;
}
function D(a, b) {
var e = w(a = l(a), b);
return !e || !d(i, b) || d(a, c) && a[c][b] || (e.enumerable = !0), e;
}
function v(g) {
for (var a,
b = y(l(g)),
e = [],
f = 0; b.length > f; )
d(i, a = b[f++]) || a == c || e.push(a);
return e;
}
function A(f) {
for (var a,
b = y(l(f)),
c = [],
e = 0; b.length > e; )
d(i, a = b[e++]) && c.push(i[a]);
return c;
}
var b = e(63),
s = e(64).set,
t = e(65),
z = e(66),
h = e(67),
x = e(62),
J = e(68),
K = e(69),
H = e(70).obj,
j = Object.prototype,
B = b.DESC,
d = b.has,
k = b.create,
w = b.getDesc,
f = b.setDesc,
p = b.desc,
y = b.getNames,
l = b.toObject,
g = b.g.Symbol,
m = !1,
C = t("tag"),
c = t("hidden"),
I = {}.propertyIsEnumerable,
n = z("symbol-registry"),
i = z("symbols"),
o = b.isFunction(g),
q = B ? function() {
try {
return k(f({}, c, {get: function() {
return f(this, c, {value: !1})[c];
}}))[c] || f;
} catch (a) {
return function(c, a, d) {
var b = w(j, a);
b && delete j[a], f(c, a, d), b && c !== j && f(j, a, b);
};
}
}() : f;
o || (g = function() {
if (this instanceof g)
throw TypeError("Symbol is not a constructor");
return F(t(arguments[0]));
}, x(g.prototype, "toString", function() {
return this[C];
}), b.create = E, b.setDesc = r, b.getDesc = D, b.setDescs = u, b.getNames = v, b.getSymbols = A, b.DESC && b.FW && x(Object.prototype, "propertyIsEnumerable", L, !0));
var G = {
"for": function(a) {
return d(n, a += "") ? n[a] : n[a] = g(a);
},
keyFor: function(a) {
return J(n, a);
},
useSetter: function() {
m = !0;
},
useSimple: function() {
m = !1;
}
};
b.each.call("hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","), function(a) {
var b = e(71)(a);
G[a] = o ? b : F(b);
}), m = !0, h(h.G + h.W, {Symbol: g}), h(h.S, "Symbol", G), h(h.S + h.F * !o, "Object", {
create: E,
defineProperty: r,
defineProperties: u,
getOwnPropertyDescriptor: D,
getOwnPropertyNames: v,
getOwnPropertySymbols: A
}), s(g, "Symbol"), s(Math, "Math", !0), s(b.g.JSON, "JSON", !0);
}, function(c, d, a) {
var b = a(67);
b(b.S, "Object", {assign: a(78)});
}, function(c, d, b) {
var a = b(67);
a(a.S, "Object", {is: function(a, b) {
return a === b ? 0 !== a || 1 / a === 1 / b : a != a && b != b;
}});
}, function(c, d, a) {
var b = a(67);
b(b.S, "Object", {setPrototypeOf: a(79).set});
}, function(d, e, a) {
var b = a(64),
c = {};
c[a(71)("toStringTag")] = "z", a(63).FW && "z" != b(c) && a(62)(Object.prototype, "toString", function() {
return "[object " + b.classof(this) + "]";
}, !0);
}, function(f, g, e) {
var b = e(63),
c = e(67),
a = b.isObject,
d = b.toObject;
b.each.call("freeze,seal,preventExtensions,isFrozen,isSealed,isExtensible,getOwnPropertyDescriptor,getPrototypeOf,keys,getOwnPropertyNames".split(","), function(g, f) {
var e = (b.core.Object || {})[g] || Object[g],
h = 0,
i = {};
i[g] = 0 == f ? function(b) {
return a(b) ? e(b) : b;
} : 1 == f ? function(b) {
return a(b) ? e(b) : b;
} : 2 == f ? function(b) {
return a(b) ? e(b) : b;
} : 3 == f ? function(b) {
return a(b) ? e(b) : !0;
} : 4 == f ? function(b) {
return a(b) ? e(b) : !0;
} : 5 == f ? function(b) {
return a(b) ? e(b) : !1;
} : 6 == f ? function(a, b) {
return e(d(a), b);
} : 7 == f ? function(a) {
return e(Object(b.assertDefined(a)));
} : 8 == f ? function(a) {
return e(d(a));
} : function(a) {
return e(d(a));
};
try {
e("z");
} catch (j) {
h = 1;
}
c(c.S + c.F * h, "Object", i);
});
}, function(f, g, e) {
var a = e(63),
b = "name",
c = a.setDesc,
d = Function.prototype;
b in d || a.FW && a.DESC && c(d, b, {
configurable: !0,
get: function() {
var d = (this + "").match(/^\s*function ([^ (]*)/),
e = d ? d[1] : "";
return a.has(this, b) || c(this, b, a.desc(5, e)), e;
},
set: function(d) {
a.has(this, b) || c(this, b, a.desc(0, d));
}
});
}, function(e, f, b) {
var a = b(63),
c = b(71)("hasInstance"),
d = Function.prototype;
c in d || a.setDesc(d, c, {value: function(b) {
if (!a.isFunction(this) || !a.isObject(b))
return !1;
if (!a.isObject(this.prototype))
return b instanceof this;
for (; b = a.getProto(b); )
if (this.prototype === b)
return !0;
return !1;
}});
}, function(l, k, f) {
function j(a) {
var b,
c;
if (h(b = a.valueOf) && !d(c = b.call(a)))
return c;
if (h(b = a.toString) && !d(c = b.call(a)))
return c;
throw TypeError("Can't convert object to number");
}
function e(a) {
if (d(a) && (a = j(a)), "string" == typeof a && a.length > 2 && 48 == a.charCodeAt(0)) {
var b = !1;
switch (a.charCodeAt(1)) {
case 66:
case 98:
b = !0;
case 79:
case 111:
return parseInt(a.slice(2), b ? 2 : 8);
}
}
return +a;
}
var a = f(63),
d = a.isObject,
h = a.isFunction,
i = "Number",
b = a.g[i],
c = b,
g = b.prototype;
!a.FW || b("0o1") && b("0b1") || (b = function(a) {
return this instanceof b ? new c(e(a)) : e(a);
}, a.each.call(a.DESC ? a.getNames(c) : "MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger".split(","), function(d) {
a.has(c, d) && !a.has(b, d) && a.setDesc(b, d, a.getDesc(c, d));
}), b.prototype = g, g.constructor = b, f(62)(a.g, i, b));
}, function(i, j, b) {
function c(a) {
return !d.isObject(a) && f(a) && h(a) === a;
}
var d = b(63),
e = b(67),
g = Math.abs,
h = Math.floor,
f = d.g.isFinite,
a = 9007199254740991;
e(e.S, "Number", {
EPSILON: Math.pow(2, -52),
isFinite: function(a) {
return "number" == typeof a && f(a);
},
isInteger: c,
isNaN: function(a) {
return a != a;
},
isSafeInteger: function(b) {
return c(b) && g(b) <= a;
},
MAX_SAFE_INTEGER: a,
MIN_SAFE_INTEGER: -a,
parseFloat: parseFloat,
parseInt: parseInt
});
}, function(u, t, r) {
function q(a) {
return a + 1 / k - 1 / k;
}
function l(a) {
return 0 == (a = +a) || a != a ? a : 0 > a ? -1 : 1;
}
function n(b) {
return isFinite(b = +b) && 0 != b ? 0 > b ? -n(-b) : a(b + g(b * b + 1)) : b;
}
function d(a) {
return 0 == (a = +a) ? a : a > -1e-6 && 1e-6 > a ? a + a * a / 2 : b(a) - 1;
}
var e = 1 / 0,
m = r(67),
j = Math.E,
c = Math.pow,
h = Math.abs,
b = Math.exp,
a = Math.log,
g = Math.sqrt,
p = Math.ceil,
o = Math.floor,
k = c(2, -52),
f = c(2, -23),
s = c(2, 127) * (2 - f),
i = c(2, -126);
m(m.S, "Math", {
acosh: function(b) {
return (b = +b) < 1 ? NaN : isFinite(b) ? a(b / j + g(b + 1) * g(b - 1) / j) + 1 : b;
},
asinh: n,
atanh: function(b) {
return 0 == (b = +b) ? b : a((1 + b) / (1 - b)) / 2;
},
cbrt: function(a) {
return l(a = +a) * c(h(a), 1 / 3);
},
clz32: function(b) {
return (b >>>= 0) ? 31 - o(a(b + .5) * Math.LOG2E) : 32;
},
cosh: function(a) {
return (b(a = +a) + b(-a)) / 2;
},
expm1: d,
fround: function(g) {
var c,
a,
b = h(g),
d = l(g);
return i > b ? d * q(b / i / f) * i * f : (c = (1 + f / k) * b, a = c - (c - b), a > s || a != a ? d * e : d * a);
},
hypot: function() {
for (var b,
i = 0,
f = 0,
d = arguments.length,
j = Array(d),
a = 0; d > f; ) {
if (b = j[f] = h(arguments[f++]), b == e)
return e;
b > a && (a = b);
}
for (a = a || 1; d--; )
i += c(j[d] / a, 2);
return a * g(i);
},
imul: function(f, g) {
var a = 65535,
b = +f,
c = +g,
d = a & b,
e = a & c;
return 0 | d * e + ((a & b >>> 16) * e + d * (a & c >>> 16) << 16 >>> 0);
},
log1p: function(b) {
return (b = +b) > -1e-8 && 1e-8 > b ? b - b * b / 2 : a(1 + b);
},
log10: function(b) {
return a(b) / Math.LN10;
},
log2: function(b) {
return a(b) / Math.LN2;
},
sign: l,
sinh: function(a) {
return h(a = +a) < 1 ? (d(a) - d(-a)) / 2 : (b(a - 1) - b(-a - 1)) * (j / 2);
},
tanh: function(a) {
var c = d(a = +a),
f = d(-a);
return c == e ? 1 : f == e ? -1 : (c - f) / (b(a) + b(-a));
},
trunc: function(a) {
return (a > 0 ? o : p)(a);
}
});
}, function(f, g, b) {
var a = b(67),
e = b(63).toIndex,
c = String.fromCharCode,
d = String.fromCodePoint;
a(a.S + a.F * (!!d && 1 != d.length), "String", {fromCodePoint: function() {
for (var a,
b = [],
f = arguments.length,
d = 0; f > d; ) {
if (a = +arguments[d++], e(a, 1114111) !== a)
throw RangeError(a + " is not a valid code point");
b.push(65536 > a ? c(a) : c(((a -= 65536) >> 10) + 55296, a % 1024 + 56320));
}
return b.join("");
}});
}, function(d, e, a) {
var b = a(63),
c = a(67);
c(c.S, "String", {raw: function(e) {
for (var d = b.toObject(e.raw),
f = b.toLength(d.length),
g = arguments.length,
c = [],
a = 0; f > a; )
c.push(d[a++] + ""), g > a && c.push(arguments[a] + "");
return c.join("");
}});
}, function(g, h, a) {
var d = a(63).set,
e = a(80)(!0),
b = a(65).safe("iter"),
f = a(81),
c = f.step;
a(82)(String, "String", function(a) {
d(this, b, {
o: a + "",
i: 0
});
}, function() {
var a,
d = this[b],
f = d.o,
g = d.i;
return g >= f.length ? c(1) : (a = e(f, g), d.i += a.length, c(0, a));
});
}, function(d, e, a) {
var b = a(67),
c = a(80)(!1);
b(b.P, "String", {codePointAt: function(a) {
return c(this, a);
}});
}, function(g, h, b) {
var d = b(63),
f = b(64),
c = b(67),
e = d.toLength;
c(c.P + c.F * !b(77)(function() {
"q".endsWith(/./);
}), "String", {endsWith: function(b) {
if ("RegExp" == f(b))
throw TypeError();
var c = d.assertDefined(this) + "",
g = arguments[1],
h = e(c.length),
i = g === a ? h : Math.min(e(g), h);
return b += "", c.slice(i - b.length, i) === b;
}});
}, function(e, f, a) {
var c = a(63),
d = a(64),
b = a(67);
b(b.P, "String", {includes: function(a) {
if ("RegExp" == d(a))
throw TypeError();
return !!~(c.assertDefined(this) + "").indexOf(a, arguments[1]);
}});
}, function(c, d, a) {
var b = a(67);
b(b.P, "String", {repeat: a(83)});
}, function(e, f, a) {
var c = a(63),
d = a(64),
b = a(67);
b(b.P + b.F * !a(77)(function() {
"q".startsWith(/./);
}), "String", {startsWith: function(a) {
if ("RegExp" == d(a))
throw TypeError();
var b = c.assertDefined(this) + "",
e = c.toLength(Math.min(arguments[1], b.length));
return a += "", b.slice(e, e + a.length) === a;
}});
}, function(h, i, b) {
var d = b(63),
f = b(84),
c = b(67),
e = b(81),
g = b(85);
c(c.S + c.F * !b(86)(function(a) {
Array.from(a);
}), "Array", {from: function(o) {
var l,
c,
i,
j,
h = Object(d.assertDefined(o)),
m = arguments[1],
k = m !== a,
n = k ? f(m, arguments[2], 2) : a,
b = 0;
if (e.is(h))
for (j = e.get(h), c = new ("function" == typeof this ? this : Array); !(i = j.next()).done; b++)
c[b] = k ? g(j, n, [i.value, b], !0) : i.value;
else
for (c = new ("function" == typeof this ? this : Array)(l = d.toLength(h.length)); l > b; b++)
c[b] = k ? n(h[b], b) : h[b];
return c.length = b, c;
}});
}, function(c, d, b) {
var a = b(67);
a(a.S, "Array", {of: function() {
for (var a = 0,
b = arguments.length,
c = new ("function" == typeof this ? this : Array)(b); b > a; )
c[a] = arguments[a++];
return c.length = b, c;
}});
}, function(i, j, b) {
var e = b(63),
d = b(87),
f = b(65).safe("iter"),
g = b(81),
c = g.step,
h = g.Iterators;
b(82)(Array, "Array", function(a, b) {
e.set(this, f, {
o: e.toObject(a),
i: 0,
k: b
});
}, function() {
var d = this[f],
e = d.o,
g = d.k,
b = d.i++;
return !e || b >= e.length ? (d.o = a, c(1)) : "keys" == g ? c(0, b) : "values" == g ? c(0, e[b]) : c(0, [b, e[b]]);
}, "values"), h.Arguments = h.Array, d("keys"), d("values"), d("entries");
}, function(b, c, a) {
a(88)(Array);
}, function(f, g, b) {
var c = b(63),
e = b(67),
d = c.toIndex;
e(e.P, "Array", {copyWithin: function(k, l) {
var f = Object(c.assertDefined(this)),
g = c.toLength(f.length),
b = d(k, g),
e = d(l, g),
j = arguments[2],
m = j === a ? g : d(j, g),
h = Math.min(m - e, g - b),
i = 1;
for (b > e && e + h > b && (i = -1, e = e + h - 1, b = b + h - 1); h-- > 0; )
e in f ? f[b] = f[e] : delete f[b], b += i, e += i;
return f;
}}), b(87)("copyWithin");
}, function(f, g, b) {
var c = b(63),
d = b(67),
e = c.toIndex;
d(d.P, "Array", {fill: function(h) {
for (var b = Object(c.assertDefined(this)),
d = c.toLength(b.length),
f = e(arguments[1], d),
g = arguments[2],
i = g === a ? d : e(g, d); i > f; )
b[f++] = h;
return b;
}}), b(87)("fill");
}, function(f, g, a) {
var b = "find",
c = a(67),
d = !0,
e = a(74)(5);
b in [] && Array(1)[b](function() {
d = !1;
}), c(c.P + c.F * d, "Array", {find: function(a) {
return e(this, a, arguments[1]);
}}), a(87)(b);
}, function(f, g, a) {
var b = "findIndex",
c = a(67),
d = !0,
e = a(74)(6);
b in [] && Array(1)[b](function() {
d = !1;
}), c(c.P + c.F * d, "Array", {findIndex: function(a) {
return e(this, a, arguments[1]);
}}), a(87)(b);
}, function(l, k, d) {
var c = d(63),
j = d(64),
b = c.g.RegExp,
e = b,
f = b.prototype,
g = /a/g,
h = new b(g) !== g,
i = function() {
try {
return "/a/i" == b(g, "i");
} catch (a) {}
}();
c.FW && c.DESC && (h && i || (b = function(c, f) {
var d = "RegExp" == j(c),
g = f === a;
return this instanceof b || !d || !g ? h ? new e(d && !g ? c.source : c, f) : new e(d ? c.source : c, d && g ? c.flags : f) : c;
}, c.each.call(c.getNames(e), function(a) {
a in b || c.setDesc(b, a, {
configurable: !0,
get: function() {
return e[a];
},
set: function(b) {
e[a] = b;
}
});
}), f.constructor = b, b.prototype = f, d(62)(c.g, "RegExp", b)), "g" != /./g.flags && c.setDesc(f, "flags", {
configurable: !0,
get: d(76)(/^.*\/(\w*)$/, "$1")
})), d(88)(b);
}, function(D, C, c) {
function h(b) {
var c = o(b)[s];
return c != a ? c : b;
}
function v(b) {
var a;
return A(b) && (a = b.then), g(a) ? a : !1;
}
function p(a) {
var b = a.c;
b.length && x(function() {
function f(b) {
var e,
g,
f = d ? b.ok : b.fail;
try {
f ? (d || (a.h = !0), e = f === !0 ? c : f(c), e === b.P ? b.rej(TypeError("Promise-chain cycle")) : (g = v(e)) ? g.call(e, b.res, b.rej) : b.res(e)) : b.rej(c);
} catch (h) {
b.rej(h);
}
}
for (var c = a.v,
d = 1 == a.s,
e = 0; b.length > e; )
f(b[e++]);
b.length = 0;
});
}
function t(e) {
var a,
b = e[i],
c = b.a || b.c,
d = 0;
if (b.h)
return !1;
for (; c.length > d; )
if (a = c[d++], a.fail || !t(a.P))
return !1;
return !0;
}
function l(c) {
var d,
b = this;
b.d || (b.d = !0, b = b.r || b, b.v = c, b.s = 2, b.a = b.c.slice(), setTimeout(function() {
x(function() {
t(d = b.p) && ("process" == u(k) ? k.emit("unhandledRejection", c, d) : n.console && g(console.error) && console.error("Unhandled promise rejection", c)), b.a = a;
});
}, 1), p(b));
}
function w(c) {
var d,
b,
a = this;
if (!a.d) {
a.d = !0, a = a.r || a;
try {
(d = v(c)) ? (b = {
r: a,
d: !1
}, d.call(c, j(w, b, 1), j(l, b, 1))) : (a.v = c, a.s = 1, p(a));
} catch (e) {
l.call(b || {
r: a,
d: !1
}, e);
}
}
}
var e = c(63),
j = c(84),
u = c(64),
d = c(67),
r = c(70),
y = c(89),
z = c(79).set,
B = c(88),
s = c(71)("species"),
i = c(65).safe("record"),
f = "Promise",
n = e.g,
k = n.process,
x = k && k.nextTick || c(90).set,
b = n[f],
g = e.isFunction,
A = e.isObject,
q = r.fn,
o = r.obj,
m = function() {
function a(d) {
var c = new b(d);
return z(c, a.prototype), c;
}
var d,
c = !1;
try {
c = g(b) && g(b.resolve) && b.resolve(d = new b(function() {})) == d, z(a, b), a.prototype = e.create(b.prototype, {constructor: {value: a}}), a.resolve(5).then(function() {}) instanceof a || (c = !1);
} catch (f) {
c = !1;
}
return c;
}();
m || (b = function(d) {
q(d);
var c = {
p: r.inst(this, b, f),
c: [],
a: a,
s: 0,
d: !1,
v: a,
h: !1
};
e.hide(this, i, c);
try {
d(j(w, c, 1), j(l, c, 1));
} catch (g) {
l.call(c, g);
}
}, c(91)(b.prototype, {
then: function(e, f) {
var h = o(o(this).constructor)[s],
c = {
ok: g(e) ? e : !0,
fail: g(f) ? f : !1
},
j = c.P = new (h != a ? h : b)(function(a, b) {
c.res = q(a), c.rej = q(b);
}),
d = this[i];
return d.c.push(c), d.a && d.a.push(c), d.s && p(d), j;
},
"catch": function(b) {
return this.then(a, b);
}
})), d(d.G + d.W + d.F * !m, {Promise: b}), u.set(b, f), B(b), B(e.core[f]), d(d.S + d.F * !m, f, {
reject: function(a) {
return new (h(this))(function(c, b) {
b(a);
});
},
resolve: function(a) {
return A(a) && i in a && e.getProto(a) === this.prototype ? a : new (h(this))(function(b) {
b(a);
});
}
}), d(d.S + d.F * !(m && c(86)(function(a) {
b.all(a)["catch"](function() {});
})), f, {
all: function(c) {
var b = h(this),
a = [];
return new b(function(g, h) {
y(c, !1, a.push, a);
var d = a.length,
f = Array(d);
d ? e.each.call(a, function(a, c) {
b.resolve(a).then(function(a) {
f[c] = a, --d || g(f);
}, h);
}) : g(f);
});
},
race: function(b) {
var a = h(this);
return new a(function(c, d) {
y(b, !1, function(b) {
a.resolve(b).then(c, d);
});
});
}
});
}, function(c, d, b) {
var a = b(92);
b(93)("Map", {
get: function(c) {
var b = a.getEntry(this, c);
return b && b.v;
},
set: function(b, c) {
return a.def(this, 0 === b ? 0 : b, c);
}
}, a, !0);
}, function(c, d, a) {
var b = a(92);
a(93)("Set", {add: function(a) {
return b.def(this, a = 0 === a ? 0 : a, a);
}}, b);
}, function(m, l, b) {
var c = b(63),
a = b(94),
f = a.leakStore,
j = a.ID,
h = a.WEAK,
k = c.has,
d = c.isObject,
i = Object.isExtensible || d,
g = {},
e = b(93)("WeakMap", {
get: function(a) {
if (d(a)) {
if (!i(a))
return f(this).get(a);
if (k(a, h))
return a[h][this[j]];
}
},
set: function(b, c) {
return a.def(this, b, c);
}
}, a, !0, !0);
c.FW && 7 != (new e).set((Object.freeze || Object)(g), 7).get(g) && c.each.call(["delete", "has", "get", "set"], function(a) {
var c = e.prototype,
g = c[a];
b(62)(c, a, function(b, c) {
if (d(b) && !i(b)) {
var e = f(this)[a](b, c);
return "set" == a ? this : e;
}
return g.call(this, b, c);
});
});
}, function(c, d, a) {
var b = a(94);
a(93)("WeakSet", {add: function(a) {
return b.def(this, a, !0);
}}, b, !1, !0);
}, function(v, u, d) {
function l(c) {
b.set(this, k, {
o: c,
k: a,
i: 0
});
}
var b = d(63),
e = d(67),
g = d(79),
o = d(81),
s = d(71)("iterator"),
k = d(65).safe("iter"),
j = o.step,
m = d(70),
f = b.isObject,
h = b.getProto,
i = b.g.Reflect,
q = Function.apply,
c = m.obj,
r = Object.isExtensible || f,
p = Object.preventExtensions,
t = !(i && i.enumerate && s in i.enumerate({}));
o.create(l, "Object", function() {
var d,
b = this[k],
c = b.k;
if (c == a) {
b.k = c = [];
for (d in b.o)
c.push(d);
}
do
if (b.i >= c.length)
return j(1);
while (!((d = c[b.i++]) in b.o));
return j(0, d);
});
var n = {
apply: function(a, b, c) {
return q.call(a, b, c);
},
construct: function(a, g) {
var c = m.fn(arguments.length < 3 ? a : arguments[2]).prototype,
d = b.create(f(c) ? c : Object.prototype),
e = q.call(a, d, g);
return f(e) ? e : d;
},
defineProperty: function(a, d, e) {
c(a);
try {
return b.setDesc(a, d, e), !0;
} catch (f) {
return !1;
}
},
deleteProperty: function(a, d) {
var e = b.getDesc(c(a), d);
return e && !e.configurable ? !1 : delete a[d];
},
get: function w(e, g) {
var i,
j = arguments.length < 3 ? e : arguments[2],
d = b.getDesc(c(e), g);
return d ? b.has(d, "value") ? d.value : d.get === a ? a : d.get.call(j) : f(i = h(e)) ? w(i, g, j) : a;
},
getOwnPropertyDescriptor: function(a, d) {
return b.getDesc(c(a), d);
},
getPrototypeOf: function(a) {
return h(c(a));
},
has: function(a, b) {
return b in a;
},
isExtensible: function(a) {
return r(c(a));
},
ownKeys: d(95),
preventExtensions: function(a) {
c(a);
try {
return p && p(a), !0;
} catch (b) {
return !1;
}
},
set: function x(i, g, j) {
var k,
l,
e = arguments.length < 4 ? i : arguments[3],
d = b.getDesc(c(i), g);
if (!d) {
if (f(l = h(i)))
return x(l, g, j, e);
d = b.desc(0);
}
return b.has(d, "value") ? d.writable !== !1 && f(e) ? (k = b.getDesc(e, g) || b.desc(0), k.value = j, b.setDesc(e, g, k), !0) : !1 : d.set === a ? !1 : (d.set.call(e, j), !0);
}
};
g && (n.setPrototypeOf = function(a, b) {
g.check(a, b);
try {
return g.set(a, b), !0;
} catch (c) {
return !1;
}
}), e(e.G, {Reflect: {}}), e(e.S + e.F * t, "Reflect", {enumerate: function(a) {
return new l(c(a));
}}), e(e.S, "Reflect", n);
}, function(d, e, a) {
var b = a(67),
c = a(75)(!0);
b(b.P, "Array", {includes: function(a) {
return c(this, a, arguments[1]);
}}), a(87)("includes");
}, function(d, e, a) {
var b = a(67),
c = a(80)(!0);
b(b.P, "String", {at: function(a) {
return c(this, a);
}});
}, function(d, e, a) {
var b = a(67),
c = a(96);
b(b.P, "String", {lpad: function(a) {
return c(this, a, arguments[1], !0);
}});
}, function(d, e, a) {
var b = a(67),
c = a(96);
b(b.P, "String", {rpad: function(a) {
return c(this, a, arguments[1], !1);
}});
}, function(c, d, a) {
var b = a(67);
b(b.S, "RegExp", {escape: a(76)(/([\\\-[\]{}()*+?.,^$|])/g, "\\$1", !0)});
}, function(e, f, b) {
var a = b(63),
c = b(67),
d = b(95);
c(c.S, "Object", {getOwnPropertyDescriptors: function(e) {
var b = a.toObject(e),
c = {};
return a.each.call(d(b), function(d) {
a.setDesc(c, d, a.desc(0, a.getDesc(b, d)));
}), c;
}});
}, function(e, f, a) {
function b(a) {
return function(i) {
var h,
d = c.toObject(i),
e = c.getKeys(d),
f = e.length,
b = 0,
g = Array(f);
if (a)
for (; f > b; )
g[b] = [h = e[b++], d[h]];
else
for (; f > b; )
g[b] = d[e[b++]];
return g;
};
}
var c = a(63),
d = a(67);
d(d.S, "Object", {
values: b(!1),
entries: b(!0)
});
}, function(b, c, a) {
a(97)("Map");
}, function(b, c, a) {
a(97)("Set");
}, function(d, e, b) {
var a = b(67),
c = b(90);
a(a.G + a.B, {
setImmediate: c.set,
clearImmediate: c.clear
});
}, function(k, j, c) {
c(23);
var a = c(63),
d = c(81).Iterators,
b = c(71)("iterator"),
e = d.Array,
f = a.g.NodeList,
g = a.g.HTMLCollection,
h = f && f.prototype,
i = g && g.prototype;
a.FW && (!f || b in h || a.hide(h, b, e), !g || b in i || a.hide(i, b, e)), d.NodeList = d.HTMLCollection = e;
}, function(i, j, a) {
function d(a) {
return f ? function(c, d) {
return a(g(h, [].slice.call(arguments, 2), b.isFunction(c) ? c : Function(c)), d);
} : a;
}
var b = a(63),
c = a(67),
g = a(73),
h = a(98),
e = b.g.navigator,
f = !!e && /MSIE .\./.test(e.userAgent);
c(c.G + c.B + c.F * f, {
setTimeout: d(b.g.setTimeout),
setInterval: d(b.g.setInterval)
});
}, function(x, w, b) {
function f(b) {
var c = d.create(null);
return b != a && (k.is(b) ? t(b, !0, function(a, b) {
c[a] = b;
}) : u(c, b)), c;
}
function m(a, b) {
d.set(this, p, {
o: j(a),
a: n(a),
i: 0,
k: b
});
}
function i(a) {
return function(b) {
return new m(b, a);
};
}
function l(a, b) {
return "function" == typeof a ? a : b;
}
function c(b) {
var d = 1 == b,
c = 4 == b;
return function(n, o, p) {
var e,
i,
h,
q = v(o, p, 3),
m = j(n),
k = d || 7 == b || 2 == b ? new (l(this, f)) : a;
for (e in m)
if (g(m, e) && (i = m[e], h = q(i, e, n), b))
if (d)
k[e] = h;
else if (h)
switch (b) {
case 2:
k[e] = i;
break;
case 3:
return !0;
case 5:
return i;
case 6:
return e;
case 7:
k[h[0]] = h[1];
}
else if (c)
return !1;
return 3 == b || c ? c : k;
};
}
function r(b) {
return function(o, p, e) {
q.fn(p);
var c,
h,
i,
d = j(o),
k = n(d),
r = k.length,
m = 0;
for (b ? c = e == a ? new (l(this, f)) : Object(e) : arguments.length < 3 ? (q(r, "Reduce of empty object with no initial value"), c = d[k[m++]]) : c = Object(e); r > m; )
if (g(d, h = k[m++]))
if (i = p(c, d[h], h, o), b) {
if (i === !1)
break;
} else
c = i;
return c;
};
}
var d = b(63),
v = b(84),
e = b(67),
u = b(78),
o = b(68),
p = b(65).safe("iter"),
q = b(70),
k = b(81),
t = b(89),
h = k.step,
n = d.getKeys,
j = d.toObject,
g = d.has;
f.prototype = null, k.create(m, "Dict", function() {
var c,
b = this[p],
d = b.o,
e = b.a,
f = b.k;
do
if (b.i >= e.length)
return b.o = a, h(1);
while (!g(d, c = e[b.i++]));
return "keys" == f ? h(0, c) : "values" == f ? h(0, d[c]) : h(0, [c, d[c]]);
});
var s = c(6);
e(e.G + e.F, {Dict: f}), e(e.S, "Dict", {
keys: i("keys"),
values: i("values"),
entries: i("entries"),
forEach: c(0),
map: c(1),
filter: c(2),
some: c(3),
every: c(4),
find: c(5),
findKey: s,
mapPairs: c(7),
reduce: r(!1),
turn: r(!0),
keyOf: o,
includes: function(c, b) {
return (b == b ? o(c, b) : s(c, function(a) {
return a != a;
})) !== a;
},
has: g,
get: function(b, c) {
return g(b, c) ? b[c] : a;
},
set: d.def,
isDict: function(a) {
return d.isObject(a) && d.getProto(a) === f.prototype;
}
});
}, function(d, e, a) {
var b = a(63).core,
c = a(81);
b.isIterable = c.is, b.getIterator = c.get;
}, function(U, T, d) {
function F(a, b) {
return function(g) {
var c,
e = t(g),
f = 0,
d = [];
for (c in e)
c != m && l(e, c) && d.push(c);
for (; b > f; )
l(e, c = a[f++]) && (~D(d, c) || d.push(c));
return d;
};
}
function s() {}
function C(a) {
return function(h, d) {
i.fn(h);
var c = t(this),
e = f(c.length),
b = a ? e - 1 : 0,
g = a ? -1 : 1;
if (arguments.length < 2)
for (; ; ) {
if (b in c) {
d = c[b], b += g;
break;
}
b += g, i(a ? b >= 0 : e > b, "Reduce of empty array with no initial value");
}
for (; a ? b >= 0 : e > b; b += g)
b in c && (d = h(d, c[b], b, this));
return d;
};
}
function e(a) {
return a > 9 ? a : "0" + a;
}
var b = d(63),
A = d(72),
g = d(64),
c = d(67),
O = d(73),
h = d(74),
m = d(65).safe("__proto__"),
i = d(70),
p = i.obj,
y = Object.prototype,
q = b.html,
v = [],
j = v.slice,
P = v.join,
z = g.classof,
l = b.has,
I = b.setDesc,
Q = b.getDesc,
u = b.setDescs,
x = b.isFunction,
o = b.isObject,
t = b.toObject,
f = b.toLength,
B = b.toIndex,
r = !1,
D = d(75)(!1),
R = h(0),
J = h(1),
K = h(2),
L = h(3),
M = h(4);
if (!b.DESC) {
try {
r = 8 == I(A("div"), "x", {get: function() {
return 8;
}}).x;
} catch (S) {}
b.setDesc = function(b, c, a) {
if (r)
try {
return I(b, c, a);
} catch (d) {}
if ("get" in a || "set" in a)
throw TypeError("Accessors not supported!");
return "value" in a && (p(b)[c] = a.value), b;
}, b.getDesc = function(c, d) {
if (r)
try {
return Q(c, d);
} catch (e) {}
return l(c, d) ? b.desc(!y.propertyIsEnumerable.call(c, d), c[d]) : a;
}, b.setDescs = u = function(a, c) {
p(a);
for (var d,
e = b.getKeys(c),
g = e.length,
f = 0; g > f; )
b.setDesc(a, d = e[f++], c[d]);
return a;
};
}
c(c.S + c.F * !b.DESC, "Object", {
getOwnPropertyDescriptor: b.getDesc,
defineProperty: b.setDesc,
defineProperties: u
});
var n = "constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),
G = n.concat("length", "prototype"),
H = n.length,
k = function() {
var a,
b = A("iframe"),
c = H,
d = ">";
for (b.style.display = "none", q.appendChild(b), b.src = "javascript:", a = b.contentWindow.document, a.open(), a.write("<script>document.F=Object</script" + d), a.close(), k = a.F; c--; )
delete k.prototype[n[c]];
return k();
};
c(c.S, "Object", {
getPrototypeOf: b.getProto = b.getProto || function(a) {
return a = Object(i.def(a)), l(a, m) ? a[m] : x(a.constructor) && a instanceof a.constructor ? a.constructor.prototype : a instanceof Object ? y : null;
},
getOwnPropertyNames: b.getNames = b.getNames || F(G, G.length, !0),
create: b.create = b.create || function(c, d) {
var b;
return null !== c ? (s.prototype = p(c), b = new s, s.prototype = null, b[m] = c) : b = k(), d === a ? b : u(b, d);
},
keys: b.getKeys = b.getKeys || F(n, H, !1),
seal: function(a) {
return a;
},
freeze: function(a) {
return a;
},
preventExtensions: function(a) {
return a;
},
isSealed: function(a) {
return !o(a);
},
isFrozen: function(a) {
return !o(a);
},
isExtensible: function(a) {
return o(a);
}
}), c(c.P, "Function", {bind: function(d) {
function c() {
var h = e.concat(j.call(arguments)),
f = this instanceof c,
g = f ? b.create(a.prototype) : d,
i = O(a, h, g);
return f ? g : i;
}
var a = i.fn(this),
e = j.call(arguments, 1);
return a.prototype && (c.prototype = a.prototype), c;
}}), 0 in Object("z") && "z" == "z"[0] || (b.ES5Object = function(a) {
return "String" == g(a) ? a.split("") : Object(a);
});
var E = !0;
try {
q && j.call(q), E = !1;
} catch (S) {}
c(c.P + c.F * E, "Array", {slice: function(h, b) {
var d = f(this.length),
i = g(this);
if (b = b === a ? d : b, "Array" == i)
return j.call(this, h, b);
for (var e = B(h, d),
m = B(b, d),
k = f(m - e),
l = Array(k),
c = 0; k > c; c++)
l[c] = "String" == i ? this.charAt(e + c) : this[e + c];
return l;
}}), c(c.P + c.F * (b.ES5Object != Object), "Array", {join: function() {
return P.apply(b.ES5Object(this), arguments);
}}), c(c.S, "Array", {isArray: function(a) {
return "Array" == g(a);
}}), c(c.P, "Array", {
forEach: b.each = b.each || function(a) {
return R(this, a, arguments[1]);
},
map: function(a) {
return J(this, a, arguments[1]);
},
filter: function(a) {
return K(this, a, arguments[1]);
},
some: function(a) {
return L(this, a, arguments[1]);
},
every: function(a) {
return M(this, a, arguments[1]);
},
reduce: C(!1),
reduceRight: C(!0),
indexOf: function(a) {
return D(this, a, arguments[1]);
},
lastIndexOf: function(e, g) {
var c = t(this),
d = f(c.length),
a = d - 1;
for (arguments.length > 1 && (a = Math.min(a, b.toInteger(g))), 0 > a && (a = f(d + a)); a >= 0; a--)
if (a in c && c[a] === e)
return a;
return -1;
}
}), c(c.P, "String", {trim: d(76)(/^\s*([\s\S]*\S)?\s*$/, "$1")}), c(c.S, "Date", {now: function() {
return +new Date;
}});
var w = new Date(-5e13 - 1),
N = !(w.toISOString && "0385-07-25T07:06:39.999Z" == w.toISOString() && d(77)(function() {
new Date(NaN).toISOString();
}));
c(c.P + c.F * N, "Date", {toISOString: function() {
if (!isFinite(this))
throw RangeError("Invalid time value");
var a = this,
b = a.getUTCFullYear(),
c = a.getUTCMilliseconds(),
d = 0 > b ? "-" : b > 9999 ? "+" : "";
return d + ("00000" + Math.abs(b)).slice(d ? -6 : -4) + "-" + e(a.getUTCMonth() + 1) + "-" + e(a.getUTCDate()) + "T" + e(a.getUTCHours()) + ":" + e(a.getUTCMinutes()) + ":" + e(a.getUTCSeconds()) + "." + (c > 99 ? c : "0" + e(c)) + "Z";
}}), "Object" == z(function() {
return arguments;
}()) && (g.classof = function(a) {
var b = z(a);
return "Object" == b && x(a.callee) ? "Arguments" : b;
});
}, function(e, f, a) {
var c = a(63),
b = a(67),
d = a(98);
b(b.G + b.F, {delay: function(a) {
return new (c.core.Promise || c.g.Promise)(function(b) {
setTimeout(d.call(b, !0), a);
});
}});
}, function(d, e, a) {
var b = a(63),
c = a(67);
b.core._ = b.path._ = b.path._ || {}, c(c.P + c.F, "Function", {part: a(98)});
}, function(f, g, b) {
function d(b, c) {
for (var d,
f = e(a.toObject(c)),
h = f.length,
g = 0; h > g; )
a.setDesc(b, d = f[g++], a.getDesc(c, d));
return b;
}
var a = b(63),
c = b(67),
e = b(95);
c(c.S + c.F, "Object", {
isObject: a.isObject,
classof: b(64).classof,
define: d,
make: function(b, c) {
return d(a.create(b), c);
}
});
}, function(f, g, b) {
var d = b(63),
c = b(67),
e = b(70).fn;
c(c.P + c.F, "Array", {turn: function(c, f) {
e(c);
for (var g = f == a ? [] : Object(f),
h = d.ES5Object(this),
i = d.toLength(h.length),
b = 0; i > b && c(g, h[b], b++, this) !== !1; )
;
return g;
}}), b(87)("turn");
}, function(e, f, b) {
var c = b(63),
d = b(65).safe("iter");
b(82)(Number, "Number", function(a) {
c.set(this, d, {
l: c.toLength(a),
i: 0
});
}, function() {
var b = this[d],
c = b.i++,
e = c >= b.l;
return {
done: e,
value: e ? a : c
};
});
}, function(g, h, b) {
var e = b(63),
c = b(67),
f = b(73),
d = {};
d.random = function(b) {
var c = +this,
d = b == a ? 0 : +b,
e = Math.min(c, d);
return Math.random() * (Math.max(c, d) - e) + e;
}, e.FW && e.each.call("round,floor,ceil,abs,sin,asin,cos,acos,tan,atan,exp,sqrt,max,min,pow,atan2,acosh,asinh,atanh,cbrt,clz32,cosh,expm1,hypot,imul,log1p,log10,log2,sign,sinh,tanh,trunc".split(","), function(a) {
var b = Math[a];
b && (d[a] = function() {
for (var a = [+this],
c = 0; arguments.length > c; )
a.push(arguments[c++]);
return f(b, a);
});
}), c(c.P + c.F, "Number", d);
}, function(g, h, d) {
var a,
b = d(67),
e = d(76),
c = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'"
},
f = {};
for (a in c)
f[c[a]] = a;
b(b.P + b.F, "String", {
escapeHTML: e(/[&<>"']/g, c),
unescapeHTML: e(/&(?:amp|lt|gt|quot|apos);/g, f)
});
}, function(s, r, j) {
function a(a) {
return a > 9 ? a : "0" + a;
}
function k(f) {
return function(k, j) {
function g(a) {
return q[f + a]();
}
var q = this,
h = d[c.has(d, j) ? j : b];
return (k + "").replace(p, function(b) {
switch (b) {
case "s":
return g(l);
case "ss":
return a(g(l));
case "m":
return g(m);
case "mm":
return a(g(m));
case "h":
return g(n);
case "hh":
return a(g(n));
case "D":
return g(i);
case "DD":
return a(g(i));
case "W":
return h[0][g("Day")];
case "N":
return g(e) + 1;
case "NN":
return a(g(e) + 1);
case "M":
return h[2][g(e)];
case "MM":
return h[1][g(e)];
case "Y":
return g(o);
case "YY":
return a(g(o) % 100);
}
return b;
});
};
}
function h(e, a) {
function b(d) {
var b = [];
return c.each.call(a.months.split(","), function(a) {
b.push(a.replace(q, "$" + d));
}), b;
}
return d[e] = [a.weekdays.split(","), b(1), b(2)], f;
}
var c = j(63),
g = j(67),
f = c.core,
p = /\b\w\w?\b/g,
q = /:(.*)\|(.*)$/,
d = {},
b = "en",
l = "Seconds",
m = "Minutes",
n = "Hours",
i = "Date",
e = "Month",
o = "FullYear";
g(g.P + g.F, i, {
format: k("get"),
formatUTC: k("getUTC")
}), h(b, {
weekdays: "Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday",
months: "January,February,March,April,May,June,July,August,September,October,November,December"
}), h("ru", {
weekdays: "Воскресенье,Понедельник,Вторник,Среда,Четверг,Пятница,Суббота",
months: "Январ:я|ь,Феврал:я|ь,Март:а|,Апрел:я|ь,Ма:я|й,Июн:я|ь,Июл:я|ь,Август:а|,Сентябр:я|ь,Октябр:я|ь,Ноябр:я|ь,Декабр:я|ь"
}), f.locale = function(a) {
return c.has(d, a) ? b = a : b;
}, f.addLocale = h;
}, function(c, d, b) {
var a = b(67);
a(a.G + a.F, {global: b(63).g});
}, function(g, h, b) {
var c = b(63),
d = b(67),
e = {},
f = !0;
c.each.call("assert,clear,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,isIndependentlyComposed,log,markTimeline,profile,profileEnd,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn".split(","), function(b) {
e[b] = function() {
return f && c.g.console && c.isFunction(console[b]) ? Function.apply.call(console[b], console, arguments) : a;
};
}), d(d.G + d.F, {log: b(78)(e.log, e, {
enable: function() {
f = !0;
},
disable: function() {
f = !1;
}
})});
}, function(h, i, b) {
function c(f, c) {
e.each.call(f.split(","), function(e) {
c == a && e in g ? d[e] = g[e] : e in [] && (d[e] = b(84)(Function.call, [][e], c));
});
}
var e = b(63),
f = b(67),
g = e.core.Array || Array,
d = {};
c("pop,reverse,shift,keys,values,entries", 1), c("indexOf,every,some,forEach,map,filter,find,findIndex,includes", 3), c("join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill,turn"), f(f.S, "Array", d);
}, function(f, h, c) {
function d(c, d, e, h) {
if (a.isFunction(e)) {
var f = c[d];
a.hide(e, b, f ? f + "" : g.replace(/hasOwnProperty/, d + ""));
}
c === a.g ? c[d] = e : (h || delete c[d], a.hide(c, d, e));
}
var a = c(63),
g = {}.hasOwnProperty + "",
b = c(65).safe("src"),
e = Function.toString;
d(Function.prototype, "toString", function() {
return a.has(this, b) ? this[b] : e.call(this);
}), a.core.inspectSource = function(a) {
return e.call(a);
}, f.exports = d;
}, function(w, x, v) {
function e(a) {
return isNaN(a = +a) ? 0 : (a > 0 ? r : q)(a);
}
function h(a, b) {
return {
enumerable: !(1 & a),
configurable: !(2 & a),
writable: !(4 & a),
value: b
};
}
function i(a, b, c) {
return a[b] = c, a;
}
function j(a) {
return k ? function(b, c, d) {
return g.setDesc(b, c, h(a, d));
} : i;
}
function u(a) {
return null !== a && ("object" == typeof a || "function" == typeof a);
}
function t(a) {
return "function" == typeof a;
}
function m(b) {
if (b == a)
throw TypeError("Can't call method on " + b);
return b;
}
var d = "undefined" != typeof self ? self : Function("return this")(),
o = {},
n = Object.defineProperty,
p = {}.hasOwnProperty,
q = Math.ceil,
r = Math.floor,
s = Math.max,
l = Math.min,
k = !!function() {
try {
return 2 == n({}, "a", {get: function() {
return 2;
}}).a;
} catch (a) {}
}(),
f = j(1),
g = w.exports = v(99)({
g: d,
core: o,
html: d.document && document.documentElement,
isObject: u,
isFunction: t,
that: function() {
return this;
},
toInteger: e,
toLength: function(a) {
return a > 0 ? l(e(a), 9007199254740991) : 0;
},
toIndex: function(a, b) {
return a = e(a), 0 > a ? s(a + b, 0) : l(a, b);
},
has: function(a, b) {
return p.call(a, b);
},
create: Object.create,
getProto: Object.getPrototypeOf,
DESC: k,
desc: h,
getDesc: Object.getOwnPropertyDescriptor,
setDesc: n,
setDescs: Object.defineProperties,
getKeys: Object.keys,
getNames: Object.getOwnPropertyNames,
getSymbols: Object.getOwnPropertySymbols,
assertDefined: m,
ES5Object: Object,
toObject: function(a) {
return g.ES5Object(m(a));
},
hide: f,
def: j(0),
set: d.Symbol ? i : f,
each: [].forEach
});
a !== b && (b = o), a !== c && (c = d);
}, function(f, h, d) {
function b(a) {
return g.call(a).slice(8, -1);
}
var e = d(63),
c = d(71)("toStringTag"),
g = {}.toString;
b.classof = function(d) {
var e,
f;
return d == a ? d === a ? "Undefined" : "Null" : "string" == typeof(f = (e = Object(d))[c]) ? f : b(e);
}, b.set = function(a, b, d) {
a && !e.has(a = d ? a : a.prototype, c) && e.hide(a, c, b);
}, f.exports = b;
}, function(c, f, d) {
function b(b) {
return "Symbol(".concat(b === a ? "" : b, ")_", (++e + Math.random()).toString(36));
}
var e = 0;
b.safe = d(63).g.Symbol || b, c.exports = b;
}, function(d, f, e) {
var a = e(63),
b = "__core-js_shared__",
c = a.g[b] || a.hide(a.g, b, {})[b];
d.exports = function(a) {
return c[a] || (c[a] = {});
};
}, function(g, j, e) {
function f(a, b) {
return function() {
return a.apply(b, arguments);
};
}
function a(k, l, p) {
var g,
m,
e,
q,
o = k & a.G,
r = k & a.P,
j = o ? b : k & a.S ? b[l] : (b[l] || {}).prototype,
n = o ? d : d[l] || (d[l] = {});
o && (p = l);
for (g in p)
m = !(k & a.F) && j && g in j, e = (m ? j : p)[g], q = k & a.B && m ? f(e, b) : r && h(e) ? f(Function.call, e) : e, j && !m && i(j, g, e), n[g] != e && c.hide(n, g, q), r && ((n.prototype || (n.prototype = {}))[g] = e);
}
var c = e(63),
b = c.g,
d = c.core,
h = c.isFunction,
i = e(62);
b.core = d, a.F = 1, a.G = 2, a.S = 4, a.P = 8, a.B = 16, a.W = 32, g.exports = a;
}, function(b, d, c) {
var a = c(63);
b.exports = function(f, g) {
for (var b,
c = a.toObject(f),
d = a.getKeys(c),
h = d.length,
e = 0; h > e; )
if (c[b = d[e++]] === g)
return b;
};
}, function(b, d, c) {
var a = c(63);
b.exports = function(b) {
var c = a.getKeys(b),
e = a.getDesc,
d = a.getSymbols;
return d && a.each.call(d(b), function(a) {
e(b, a).enumerable && c.push(a);
}), c;
};
}, function(c, e, d) {
function a(c, a, b) {
if (!c)
throw TypeError(b ? a + b : a);
}
var b = d(63);
a.def = b.assertDefined, a.fn = function(a) {
if (!b.isFunction(a))
throw TypeError(a + " is not a function!");
return a;
}, a.obj = function(a) {
if (!b.isObject(a))
throw TypeError(a + " is not an object!");
return a;
}, a.inst = function(a, b, c) {
if (!(a instanceof b))
throw TypeError(c + ": use the 'new' operator!");
return a;
}, c.exports = a;
}, function(d, e, a) {
var b = a(63).g,
c = a(66)("wks");
d.exports = function(d) {
return c[d] || (c[d] = b.Symbol && b.Symbol[d] || a(65).safe("Symbol." + d));
};
}, function(d, g, e) {
var b = e(63),
a = b.g.document,
c = b.isObject,
f = c(a) && c(a.createElement);
d.exports = function(b) {
return f ? a.createElement(b) : {};
};
}, function(b) {
b.exports = function(c, b, d) {
var e = d === a;
switch (b.length) {
case 0:
return e ? c() : c.call(d);
case 1:
return e ? c(b[0]) : c.call(d, b[0]);
case 2:
return e ? c(b[0], b[1]) : c.call(d, b[0], b[1]);
case 3:
return e ? c(b[0], b[1], b[2]) : c.call(d, b[0], b[1], b[2]);
case 4:
return e ? c(b[0], b[1], b[2], b[3]) : c.call(d, b[0], b[1], b[2], b[3]);
case 5:
return e ? c(b[0], b[1], b[2], b[3], b[4]) : c.call(d, b[0], b[1], b[2], b[3], b[4]);
}
return c.apply(d, b);
};
}, function(d, f, c) {
var b = c(63),
e = c(84);
d.exports = function(c) {
var f = 1 == c,
h = 2 == c,
i = 3 == c,
d = 4 == c,
g = 6 == c,
j = 5 == c || g;
return function(u, s, t) {
for (var l,
n,
q = Object(b.assertDefined(u)),
o = b.ES5Object(q),
r = e(s, t, 3),
p = b.toLength(o.length),
k = 0,
m = f ? Array(p) : h ? [] : a; p > k; k++)
if ((j || k in o) && (l = o[k], n = r(l, k, q), c))
if (f)
m[k] = n;
else if (n)
switch (c) {
case 3:
return !0;
case 5:
return l;
case 6:
return k;
case 2:
m.push(l);
}
else if (d)
return !1;
return g ? -1 : i || d ? d : m;
};
};
}, function(b, d, c) {
var a = c(63);
b.exports = function(b) {
return function(h, e, i) {
var f,
d = a.toObject(h),
g = a.toLength(d.length),
c = a.toIndex(i, g);
if (b && e != e) {
for (; g > c; )
if (f = d[c++], f != f)
return !0;
} else
for (; g > c; c++)
if ((b || c in d) && d[c] === e)
return b || c;
return !b && -1;
};
};
}, function(a) {
a.exports = function(b, a, c) {
var d = a === Object(a) ? function(b) {
return a[b];
} : a;
return function(a) {
return ((c ? a : this) + "").replace(b, d);
};
};
}, function(a) {
a.exports = function(a) {
try {
return a(), !1;
} catch (b) {
return !0;
}
};
}, function(c, e, a) {
var b = a(63),
d = a(69);
c.exports = Object.assign || function(i) {
for (var a = Object(b.assertDefined(i)),
j = arguments.length,
c = 1; j > c; )
for (var e,
f = b.ES5Object(arguments[c++]),
g = d(f),
k = g.length,
h = 0; k > h; )
a[e = g[h++]] = f[e];
return a;
};
}, function(f, g, b) {
function c(b, a) {
e.obj(b), e(null === a || d.isObject(a), a, ": can't set as prototype!");
}
var d = b(63),
e = b(70);
f.exports = {
set: Object.setPrototypeOf || ("__proto__" in {} ? function(e, a) {
try {
a = b(84)(Function.call, d.getDesc(Object.prototype, "__proto__").set, 2), a({}, []);
} catch (f) {
e = !0;
}
return function(b, d) {
return c(b, d), e ? b.__proto__ = d : a(b, d), b;
};
}() : a),
check: c
};
}, function(c, e, d) {
var b = d(63);
c.exports = function(c) {
return function(i, j) {
var e,
g,
f = b.assertDefined(i) + "",
d = b.toInteger(j),
h = f.length;
return 0 > d || d >= h ? c ? "" : a : (e = f.charCodeAt(d), 55296 > e || e > 56319 || d + 1 === h || (g = f.charCodeAt(d + 1)) < 56320 || g > 57343 ? c ? f.charAt(d) : e : c ? f.slice(d, d + 2) : (e - 55296 << 10) + (g - 56320) + 65536);
};
};
}, function(j, k, b) {
function h(b, d) {
a.hide(b, f, d), c in [] && a.hide(b, c, d);
}
var a = b(63),
d = b(64),
i = b(70).obj,
f = b(71)("iterator"),
c = "@@iterator",
e = b(66)("iterators"),
g = {};
h(g, a.that), j.exports = {
BUGGY: "keys" in [] && !("next" in [].keys()),
Iterators: e,
step: function(a, b) {
return {
value: b,
done: !!a
};
},
is: function(h) {
var b = Object(h),
g = a.g.Symbol,
i = g && g.iterator || c;
return i in b || f in b || a.has(e, d.classof(b));
},
get: function(b) {
var g = a.g.Symbol,
h = b[g && g.iterator || c],
j = h || b[f] || e[d.classof(b)];
return i(j.call(b));
},
set: h,
create: function(b, c, e, f) {
b.prototype = a.create(f || g, {next: a.desc(1, e)}), d.set(b, c + " Iterator");
}
};
}, function(k, m, a) {
var e = a(67),
j = a(62),
b = a(63),
l = a(64),
c = a(81),
i = a(71)("iterator"),
g = "@@iterator",
h = "keys",
d = "values",
f = c.Iterators;
k.exports = function(t, o, r, y, m, x, w) {
function n(b) {
function a(a) {
return new r(a, b);
}
switch (b) {
case h:
return function() {
return a(this);
};
case d:
return function() {
return a(this);
};
}
return function() {
return a(this);
};
}
c.create(r, o, y);
var p,
q,
u = o + " Iterator",
a = t.prototype,
s = a[i] || a[g] || m && a[m],
k = s || n(m);
if (s) {
var v = b.getProto(k.call(new t));
l.set(v, u, !0), b.FW && b.has(a, g) && c.set(v, b.that);
}
if (b.FW && c.set(a, k), f[o] = k, f[u] = b.that, m)
if (p = {
keys: x ? k : n(h),
values: m == d ? k : n(d),
entries: m != d ? k : n("entries")
}, w)
for (q in p)
q in a || j(a, q, p[q]);
else
e(e.P + e.F * c.BUGGY, o, p);
};
}, function(b, d, c) {
var a = c(63);
b.exports = function(e) {
var c = a.assertDefined(this) + "",
d = "",
b = a.toInteger(e);
if (0 > b || b == 1 / 0)
throw RangeError("Count can't be negative");
for (; b > 0; (b >>>= 1) && (c += c))
1 & b && (d += c);
return d;
};
}, function(b, e, c) {
var d = c(70).fn;
b.exports = function(b, c, e) {
if (d(b), ~e && c === a)
return b;
switch (e) {
case 1:
return function(a) {
return b.call(c, a);
};
case 2:
return function(a, d) {
return b.call(c, a, d);
};
case 3:
return function(a, d, e) {
return b.call(c, a, d, e);
};
}
return function() {
return b.apply(c, arguments);
};
};
}, function(e, g, f) {
function b(b) {
var c = b["return"];
c !== a && d(c.call(b));
}
function c(e, c, a, f) {
try {
return f ? c(d(a)[0], a[1]) : c(a);
} catch (g) {
throw b(e), g;
}
}
var d = f(70).obj;
c.close = b, e.exports = c;
}, function(d, f, e) {
var a = e(71)("iterator"),
b = !1;
try {
var c = [7][a]();
c["return"] = function() {
b = !0;
}, Array.from(c, function() {
throw 2;
});
} catch (g) {}
d.exports = function(f) {
if (!b)
return !1;
var d = !1;
try {
var c = [7],
e = c[a]();
e.next = function() {
d = !0;
}, c[a] = function() {
return e;
}, f(c);
} catch (g) {}
return d;
};
}, function(d, e, c) {
var a = c(63),
b = c(71)("unscopables");
!a.FW || b in [] || a.hide(Array.prototype, b, {}), d.exports = function(c) {
a.FW && ([][b][c] = !0);
};
}, function(d, e, b) {
var a = b(63),
c = b(71)("species");
d.exports = function(b) {
!a.DESC || c in b || a.setDesc(b, c, {
configurable: !0,
get: a.that
});
};
}, function(c, f, a) {
var d = a(84),
e = a(81).get,
b = a(85);
c.exports = function(g, c, h, i) {
for (var f,
a = e(g),
j = d(h, i, c ? 2 : 1); !(f = a.next()).done; )
if (b(a, j, f.value, c) === !1)
return b.close(a);
};
}, function(x, y, c) {
function f() {
var a = +this;
if (g.has(d, a)) {
var b = d[a];
delete d[a], b();
}
}
function s(a) {
f.call(a.data);
}
var b,
l,
i,
g = c(63),
h = c(84),
w = c(64),
v = c(73),
n = c(72),
a = g.g,
e = g.isFunction,
p = g.html,
q = a.process,
m = a.setImmediate,
k = a.clearImmediate,
t = a.postMessage,
u = a.addEventListener,
r = a.MessageChannel,
j = 0,
d = {},
o = "onreadystatechange";
e(m) && e(k) || (m = function(a) {
for (var c = [],
f = 1; arguments.length > f; )
c.push(arguments[f++]);
return d[++j] = function() {
v(e(a) ? a : Function(a), c);
}, b(j), j;
}, k = function(a) {
delete d[a];
}, "process" == w(q) ? b = function(a) {
q.nextTick(h(f, a, 1));
} : u && e(t) && !a.importScripts ? (b = function(a) {
t(a, "*");
}, u("message", s, !1)) : e(r) ? (l = new r, i = l.port2, l.port1.onmessage = s, b = h(i.postMessage, i, 1)) : b = o in n("script") ? function(a) {
p.appendChild(n("script"))[o] = function() {
p.removeChild(this), f.call(a);
};
} : function(a) {
setTimeout(h(f, a, 1), 0);
}), x.exports = {
set: m,
clear: k
};
}, function(a, d, b) {
var c = b(62);
a.exports = function(a, b) {
for (var d in b)
c(a, d, b[d]);
return a;
};
}, function(t, x, c) {
function m(a, b) {
if (!p(a))
return "symbol" == typeof a ? a : ("string" == typeof a ? "S" : "P") + a;
if (!q(a, l)) {
if (!v(a))
return "F";
if (!b)
return "E";
u(a, l, ++w);
}
return "O" + a[l];
}
function k(c, d) {
var a,
e = m(d);
if ("F" !== e)
return c[h][e];
for (a = c[b]; a; a = a.n)
if (a.k == d)
return a;
}
var d = c(63),
r = c(84),
e = c(65).safe,
o = c(70),
s = c(89),
j = c(81).step,
q = d.has,
g = d.set,
p = d.isObject,
u = d.hide,
v = Object.isExtensible || p,
l = e("id"),
h = e("O1"),
f = e("last"),
b = e("first"),
n = e("iter"),
i = d.DESC ? e("size") : "size",
w = 0;
t.exports = {
getConstructor: function(j, l, m) {
function e() {
var c = o.inst(this, e, j),
k = arguments[0];
g(c, h, d.create(null)), g(c, i, 0), g(c, f, a), g(c, b, a), k != a && s(k, l, c[m], c);
}
return c(91)(e.prototype, {
clear: function() {
for (var d = this,
e = d[h],
c = d[b]; c; c = c.n)
c.r = !0, c.p && (c.p = c.p.n = a), delete e[c.i];
d[b] = d[f] = a, d[i] = 0;
},
"delete": function(g) {
var c = this,
a = k(c, g);
if (a) {
var d = a.n,
e = a.p;
delete c[h][a.i], a.r = !0, e && (e.n = d), d && (d.p = e), c[b] == a && (c[b] = d), c[f] == a && (c[f] = e), c[i]--;
}
return !!a;
},
forEach: function(c) {
for (var a,
d = r(c, arguments[1], 3); a = a ? a.n : this[b]; )
for (d(a.v, a.k, this); a && a.r; )
a = a.p;
},
has: function(a) {
return !!k(this, a);
}
}), d.DESC && d.setDesc(e.prototype, "size", {get: function() {
return o.def(this[i]);
}}), e;
},
def: function(c, e, l) {
var g,
j,
d = k(c, e);
return d ? d.v = l : (c[f] = d = {
i: j = m(e, !0),
k: e,
v: l,
p: g = c[f],
n: a,
r: !1
}, c[b] || (c[b] = d), g && (g.n = d), c[i]++, "F" !== j && (c[h][j] = d)), c;
},
getEntry: k,
setIter: function(e, f, d) {
c(82)(e, f, function(a, b) {
g(this, n, {
o: a,
k: b
});
}, function() {
for (var d = this[n],
e = d.k,
c = d.l; c && c.r; )
c = c.p;
return d.o && (d.l = c = c ? c.n : d.o[b]) ? "keys" == e ? j(0, c.k) : "values" == e ? j(0, c.v) : j(0, [c.k, c.v]) : (d.o = a, j(1));
}, d ? "entries" : "values", !d, !0);
}
};
}, function(f, j, b) {
var c = b(63),
d = b(67),
g = b(81).BUGGY,
h = b(89),
e = b(88),
i = b(70).inst;
f.exports = function(j, u, t, l, n) {
function o(a, d) {
if (c.FW) {
var e = k[a];
b(62)(k, a, function(a, b) {
var c = e.call(this, 0 === a ? 0 : a, b);
return d ? this : c;
});
}
}
var p = c.g[j],
f = p,
m = l ? "set" : "add",
k = f && f.prototype,
s = {};
if (c.isFunction(f) && (n || !g && k.forEach && k.entries)) {
var r,
q = new f,
v = q[m](n ? {} : -0, 1);
b(86)(function(a) {
new f(a);
}) || (f = function() {
i(this, f, j);
var b = new p,
c = arguments[0];
return c != a && h(c, l, b[m], b), b;
}, f.prototype = k, c.FW && (k.constructor = f)), n || q.forEach(function(b, a) {
r = 1 / a === -(1 / 0);
}), r && (o("delete"), o("has"), l && o("get")), (r || v !== q) && o(m, !0);
} else
f = t.getConstructor(j, l, m), b(91)(f.prototype, u);
return b(64).set(f, j), s[j] = f, d(d.G + d.W + d.F * (f != p), s), e(f), e(c.core[j]), n || t.setIter(f, j, l), f;
};
}, function(r, u, c) {
function j(a, b) {
return p(a.array, function(a) {
return a[0] === b;
});
}
function f(b) {
return b[h] || m(b, h, {
array: [],
get: function(c) {
var b = j(this, c);
return b ? b[1] : a;
},
has: function(a) {
return !!j(this, a);
},
set: function(a, b) {
var c = j(this, a);
c ? c[1] = b : this.array.push([a, b]);
},
"delete": function(b) {
var a = t(this.array, function(a) {
return a[0] === b;
});
return ~a && this.array.splice(a, 1), !!~a;
}
})[h];
}
var g = c(63),
l = c(65).safe,
n = c(70),
q = c(89),
e = g.has,
i = g.isObject,
m = g.hide,
k = Object.isExtensible || i,
s = 0,
d = l("id"),
b = l("weak"),
h = l("leak"),
o = c(74),
p = o(5),
t = o(6);
r.exports = {
getConstructor: function(j, l, m) {
function h() {
g.set(n.inst(this, h, j), d, s++);
var b = arguments[0];
b != a && q(b, l, this[m], this);
}
return c(91)(h.prototype, {
"delete": function(a) {
return i(a) ? k(a) ? e(a, b) && e(a[b], this[d]) && delete a[b][this[d]] : f(this)["delete"](a) : !1;
},
has: function(a) {
return i(a) ? k(a) ? e(a, b) && e(a[b], this[d]) : f(this).has(a) : !1;
}
}), h;
},
def: function(c, a, g) {
return k(n.obj(a)) ? (e(a, b) || m(a, b, {}), a[b][c[d]] = g) : f(c).set(a, g), c;
},
leakStore: f,
WEAK: b,
ID: d
};
}, function(c, e, a) {
var b = a(63),
d = a(70).obj;
c.exports = function(a) {
d(a);
var c = b.getNames(a),
e = b.getSymbols;
return e ? c.concat(e(a)) : c;
};
}, function(d, f, b) {
var c = b(63),
e = b(83);
d.exports = function(k, g, h, i) {
var f = c.assertDefined(k) + "";
if (g === a)
return f;
var l = c.toInteger(g),
d = l - f.length;
if (0 > d || d === 1 / 0)
throw new RangeError("Cannot satisfy string length " + g + " for string: " + f);
var j = h === a ? " " : h + "",
b = e.call(j, Math.ceil(d / j.length));
return b.length > d && (b = i ? b.slice(b.length - d) : b.slice(0, d)), i ? b.concat(f) : f.concat(b);
};
}, function(c, e, a) {
var b = a(67),
d = a(89);
c.exports = function(a) {
b(b.P, a, {toJSON: function() {
var a = [];
return d(this, !1, a.push, a), a;
}});
};
}, function(c, f, a) {
var d = a(63),
b = a(73),
e = a(70).fn;
c.exports = function() {
for (var h = e(this),
a = arguments.length,
c = Array(a),
f = 0,
i = d.path._,
g = !1; a > f; )
(c[f] = arguments[f++]) === i && (g = !0);
return function() {
var d,
j = this,
k = arguments.length,
e = 0,
f = 0;
if (!g && !k)
return b(h, c, j);
if (d = c.slice(), g)
for (; a > e; e++)
d[e] === i && (d[e] = arguments[f++]);
for (; k > f; )
d.push(arguments[f++]);
return b(h, d, j);
};
};
}, function(a) {
a.exports = function(a) {
return a.FW = !0, a.path = a.g, a;
};
}]), "undefined" != typeof module && module.exports ? module.exports = b : "function" == typeof define && define.amd ? define(function() {
return b;
}) : c.core = b;
}();
})(require('process'));
|
$(document).ready(function(){
$(".toooltip_like").unbind("mouseover").bind("mouseover",function(){
var id = $(this).attr("id");
var i,post_id="";
for(i=9;i<id.length;i++)
post_id+=id[i];
$.ajax({
url:"see_who_liked.php",
method:"post",
data:{post_id:post_id},
beforesend:function()
{
$("#tooltip_text_"+post_id).html("Loading....");
},
success:function(data)
{
$("#tooltip_text_"+post_id).html(data);
}
})
})
}) |
(function (document, window) {
"use strict";
var TextLimit = {
// Settings
defaultLimit: 150,
defaultType: "character", // "character" or "word"
defaultStyle: "normal", // "normal" or "micro"
// Selectors
limiterSelector: "data-limiter",
microSelector: "data-limiter-micro",
wordSelector: "data-limiter-word",
// Attach a limiter to a field
createLimiter: function($field, limit, type, style) {
limit = limit || TextLimit.defaultLimit;
type = type || TextLimit.defaultType;
style = style || TextLimit.defaultStyle;
if($field.classList.contains("init")) {
return;
}
var $headingCounter = document.createElement("span");
$headingCounter.classList.add('form--field-with-count--counter');
var $heading = document.createElement("div");
$heading.classList.add('form--field-with-count--heading');
var $fieldWrapper = document.createElement("div");
$fieldWrapper.classList.add('form--field-with-count');
if(style === "micro") {
$fieldWrapper.classList.add("form--field-with-count__micro");
} else {
$heading.innerText = limit + " " + type + " limit";
}
// Add a class to differentiate textarea limiters
if($field.nodeName.toLowerCase() === "textarea") {
$fieldWrapper.classList.add("form--field-with-count__textarea");
}
$heading.appendChild($headingCounter);
// Apply form width styling
var formClass = $field.className;
if(formClass && formClass.split("form--")[1]) {
formClass = formClass.split("form--")[1].split(" ")[0];
$fieldWrapper.classList.add("form--" + formClass);
}
$field.parentElement.insertBefore($fieldWrapper, $field);
$fieldWrapper.appendChild($heading);
$fieldWrapper.appendChild($field);
TextLimit.limit($field, limit, $headingCounter, type, style);
$field.classList.add("init");
},
// Vanilla conversion of the jQuery limit plugin
// http://www.scriptiny.com/2012/09/jquery-input-textarea-limiter/
limit: function($field, limit, $counter, type, style){
style = style || "normal";
limit = parseInt(limit);
function setCount() {
var value = $field.value;
// Word count matcher
if(type === "word") {
value = value.trim();
var remaining = value.split(/\s/).filter(function(word) {
return word.length > 0;
}).length;
if(remaining > limit) {
var strippedValue = $field.value.replace(/\n/, '[new_line]').split(' ').slice(0,limit).join(' ').replace('[new_line]', '\n');
$field.value = strippedValue + " ";
remaining = limit;
}
// Character count matcher
} else {
var remaining = $field.value.length;
if(remaining > limit) {
$field.value = $field.value.substr(0, limit);
remaining = limit;
}
}
if(style === "micro") {
$counter.innerText = remaining + "/" + limit;
} else {
$counter.innerText = limit - remaining + " left";
}
}
setCount();
Ornament.U.bindOnce($field, "keyup focus", function(){
setCount();
});
},
// Init
init: function(){
document.querySelectorAll("[" + TextLimit.limiterSelector + "]").forEach(function($field) {
var limit = $field.getAttribute(TextLimit.limiterSelector);
var style = $field.hasAttribute(TextLimit.microSelector) ? "micro" : "normal";
var type = $field.hasAttribute(TextLimit.wordSelector) ? "word" : "character";
TextLimit.createLimiter($field, limit, type, style);
});
}
}
Ornament.registerComponent("FormLimiter", TextLimit);
}(document, window)); |
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Variant Schema
*/
var VariantSchema = new Schema({
Patient: {type: String},
Chr: {type: String},
Start: {type: Number},
End: {type: Number},
Ref: {type: String},
Alt: {type: String},
Func_knownGene: {type: String},
Gene_knownGene: {type: String},
ExonicFunc_knownGene: {type: String},
AAChange_knownGene: {type: String},
Func_ensGene: {type: String},
Gene_ensGene: {type: String},
ExonicFunc_ensGene: {type: String},
AAChange_ensGene: {type: String},
Func_refGene: {type: String},
Gene_refGene: {type: String},
ExonicFunc_refGene: {type: String},
AAChange_refGene: {type: String},
phastConsElements46way: {type: String},
genomicSuperDups: {type: String},
esp6500si_all: {type: String},
maf_1000g2012apr_all: {type: Number},
cg69: {type: Number},
snp137: {type: String},
LJB2_SIFT: {type: Number},
LJB2_PolyPhen2_HDIV: {type: Number},
LJB2_PP2_HDIV_Pred: {type: String},
LJB2_PolyPhen2_HVAR: {type: Number},
LJB2_PolyPhen2_HVAR_Pred: {type: String},
LJB2_LRT: {type: Number},
LJB2_LRT_Pred: {type: String},
LJB2_MutationTaster: {type: Number},
LJB2_MutationTaster_Pred: {type: String},
LJB_MutationAssessor: {type: String},
LJB_MutationAssessor_Pred: {type: String},
LJB2_FATHMM: {type: Number},
LJB2_GERP: {type: Number},
LJB2_PhyloP: {type: Number},
LJB2_SiPhy: {type: Number},
VCF_Chr: {type: String},
VCF_Pos: {type: Number},
VCF_Ref: {type: String},
VCF_Alt: {type: String},
VCF_Qual: {type: Number},
VCF_Info: {type: String},
VCF_Format: {type: String},
VCF_Sample_PFC_0028: {type: String},
IA_Zygosity: {type: String},
IA_GeneName: {type: String},
IA_Local_MAF: {type: Number},
IA_MAF_GATK: {type: String},
IA_OMIMAnno_Go: {type: String},
IA_OMIMAnno_Wiki: {type: String},
IA_OMIMAnno_MIM: {type: String},
IA_OMIMAnno_oMIM: {type: String},
IA_GenecardsLink: {type: String},
IA_OMIMLink: {type: String},
IA_UniprotLink: {type: String},
EF_Count: {type: Number}
});
mongoose.model('Variant', VariantSchema); |
/*
* This file has been generated to support Visual Studio IntelliSense.
* You should not use this file at runtime inside the browser--it is only
* intended to be used only for design-time IntelliSense. Please use the
* standard jQuery library for all runtime use.
*
* Comment version: 1.11.1
*/
/*!
* jQuery JavaScript Library v1.11.1
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
*/
(function (window, undefined) {
var jQuery = function (selector, context) {
/// <summary>
/// 1: Accepts a string containing a CSS selector which is then used to match a set of elements.
/// 1.1 - $(selector, context)
/// 1.2 - $(element)
/// 1.3 - $(elementArray)
/// 1.4 - $(object)
/// 1.5 - $(jQuery object)
/// 1.6 - $()
/// 2: Creates DOM elements on the fly from the provided string of raw HTML.
/// 2.1 - $(html, ownerDocument)
/// 2.2 - $(html, attributes)
/// 3: Binds a function to be executed when the DOM has finished loading.
/// 3.1 - $(callback)
/// </summary>
/// <param name="selector" type="String">
/// A string containing a selector expression
/// </param>
/// <param name="context" type="jQuery">
/// A DOM Element, Document, or jQuery to use as context
/// </param>
/// <returns type="jQuery" />
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init(selector, context, rootjQuery);
};
jQuery.Animation = function Animation(elem, properties, options) {
var result,
stopped,
index = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always(function () {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function () {
if (stopped) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max(0, animation.startTime + animation.duration - currentTime),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for (; index < length ; index++) {
animation.tweens[index].run(percent);
}
deferred.notifyWith(elem, [animation, percent, remaining]);
if (percent < 1 && length) {
return remaining;
} else {
deferred.resolveWith(elem, [animation]);
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend({}, properties),
opts: jQuery.extend(true, { specialEasing: {} }, options),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function (prop, end) {
var tween = jQuery.Tween(elem, animation.opts, prop, end,
animation.opts.specialEasing[prop] || animation.opts.easing);
animation.tweens.push(tween);
return tween;
},
stop: function (gotoEnd) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if (stopped) {
return this;
}
stopped = true;
for (; index < length ; index++) {
animation.tweens[index].run(1);
}
// resolve when we played the last frame
// otherwise, reject
if (gotoEnd) {
deferred.resolveWith(elem, [animation, gotoEnd]);
} else {
deferred.rejectWith(elem, [animation, gotoEnd]);
}
return this;
}
}),
props = animation.props;
propFilter(props, animation.opts.specialEasing);
for (; index < length ; index++) {
result = animationPrefilters[index].call(animation, elem, props, animation.opts);
if (result) {
return result;
}
}
createTweens(animation, props);
if (jQuery.isFunction(animation.opts.start)) {
animation.opts.start.call(elem, animation);
}
jQuery.fx.timer(
jQuery.extend(tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress(animation.opts.progress)
.done(animation.opts.done, animation.opts.complete)
.fail(animation.opts.fail)
.always(animation.opts.always);
};
jQuery.Callbacks = function (options) {
/// <summary>
/// A multi-purpose callbacks list object that provides a powerful way to manage callback lists.
/// </summary>
/// <param name="options" type="String">
/// An optional list of space-separated flags that change how the callback list behaves.
/// </param>
/// <returns type="Callbacks" />
// 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 // Flag to know if list is currently firing
firing,
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// First callback to fire (used internally by add and fireWith)
firingStart,
// 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;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function (fn) {
return fn ? jQuery.inArray(fn, list) > -1 : !!(list && list.length);
},
// 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.Deferred = function (func) {
/// <summary>
/// A constructor function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.
/// </summary>
/// <param name="func" type="Function">
/// A function that is called just before the constructor returns.
/// </param>
/// <returns type="Deferred" />
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 = jQuery.isFunction(fns[i]) && fns[i];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[tuple[1]](function () {
var returned = fn && 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 === promise ? newDefer.promise() : this, fn ? [returned] : arguments);
}
});
});
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 ]
deferred[tuple[0]] = function () {
deferred[tuple[0] + "With"](this === deferred ? promise : this, arguments);
return this;
};
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;
};
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;
};
jQuery.Tween = function Tween(elem, options, prop, end, easing) {
return new Tween.prototype.init(elem, options, prop, end, easing);
};
jQuery._data = function (elem, name, data) {
return internalData(elem, name, data, true);
};
jQuery._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");
jQuery._removeData(elem, key);
})
});
};
jQuery._removeData = function (elem, name) {
return internalRemoveData(elem, name, true);
};
jQuery.acceptData = function (elem) {
// Do not set data on non-element because it will not be cleared (#8335).
if (elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9) {
return false;
}
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.access = function (elems, fn, key, value, chainable, emptyGet, raw) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if (jQuery.type(key) === "object") {
chainable = true;
for (i in key) {
jQuery.access(elems, fn, i, key[i], true, emptyGet, raw);
}
// Sets one value
} else if (value !== undefined) {
chainable = true;
if (!jQuery.isFunction(value)) {
raw = true;
}
if (bulk) {
// Bulk operations run against the entire set
if (raw) {
fn.call(elems, value);
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function (elem, key, value) {
return bulk.call(jQuery(elem), value);
};
}
}
if (fn) {
for (; i < length; i++) {
fn(elems[i], key, raw ? value : value.call(elems[i], i, fn(elems[i], key)));
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call(elems) :
length ? fn(elems[0], key) : emptyGet;
};
jQuery.active = 0;
jQuery.ajax = function (url, options) {
/// <summary>
/// Perform an asynchronous HTTP (Ajax) request.
/// 1 - jQuery.ajax(url, settings)
/// 2 - jQuery.ajax(settings)
/// </summary>
/// <param name="url" type="String">
/// A string containing the URL to which the request is sent.
/// </param>
/// <param name="options" type="PlainObject">
/// A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) below for a complete list of all settings.
/// </param>
// If url is an object, simulate pre-1.5 signature
if (typeof url === "object") {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Cross-domain detection vars
parts,
// Loop variable
i,
// URL without anti-cache param
cacheURL,
// Response headers as string
responseHeadersString,
// timeout handle
timeoutTimer,
// To know if global events are to be dispatched
fireGlobals,
transport,
// Response headers
responseHeaders,
// Create the final options object
s = jQuery.ajaxSetup({}, options),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && (callbackContext.nodeType || callbackContext.jquery) ?
jQuery(callbackContext) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks("once memory"),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function (key) {
var match;
if (state === 2) {
if (!responseHeaders) {
responseHeaders = {};
while ((match = rheaders.exec(responseHeadersString))) {
responseHeaders[match[1].toLowerCase()] = match[2];
}
}
match = responseHeaders[key.toLowerCase()];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function () {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function (name, value) {
var lname = name.toLowerCase();
if (!state) {
name = requestHeadersNames[lname] = requestHeadersNames[lname] || name;
requestHeaders[name] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function (type) {
if (!state) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function (map) {
var code;
if (map) {
if (state < 2) {
for (code in map) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[code] = [statusCode[code], map[code]];
}
} else {
// Execute the appropriate callbacks
jqXHR.always(map[jqXHR.status]);
}
}
return this;
},
// Cancel the request
abort: function (statusText) {
var finalText = statusText || strAbort;
if (transport) {
transport.abort(finalText);
}
done(0, finalText);
return this;
}
};
// Attach deferreds
deferred.promise(jqXHR).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ((url || s.url || ajaxLocation) + "").replace(rhash, "").replace(rprotocol, ajaxLocParts[1] + "//");
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim(s.dataType || "*").toLowerCase().match(core_rnotwhite) || [""];
// A cross-domain request is in order when we have a protocol:host:port mismatch
if (s.crossDomain == null) {
parts = rurl.exec(s.url.toLowerCase());
s.crossDomain = !!(parts &&
(parts[1] !== ajaxLocParts[1] || parts[2] !== ajaxLocParts[2] ||
(parts[3] || (parts[1] === "http:" ? 80 : 443)) !=
(ajaxLocParts[3] || (ajaxLocParts[1] === "http:" ? 80 : 443)))
);
}
// Convert data if not already a string
if (s.data && s.processData && typeof s.data !== "string") {
s.data = jQuery.param(s.data, s.traditional);
}
// Apply prefilters
inspectPrefiltersOrTransports(prefilters, s, options, jqXHR);
// If request was aborted inside a prefilter, stop there
if (state === 2) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Watch for a new set of requests
if (fireGlobals && jQuery.active++ === 0) {
jQuery.event.trigger("ajaxStart");
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test(s.type);
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
cacheURL = s.url;
// More options handling for requests with no content
if (!s.hasContent) {
// If data is available, append data to url
if (s.data) {
cacheURL = (s.url += (ajax_rquery.test(cacheURL) ? "&" : "?") + s.data);
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if (s.cache === false) {
s.url = rts.test(cacheURL) ?
// If there is already a '_' parameter, set its value
cacheURL.replace(rts, "$1_=" + ajax_nonce++) :
// Otherwise add one to the end
cacheURL + (ajax_rquery.test(cacheURL) ? "&" : "?") + "_=" + ajax_nonce++;
}
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if (s.ifModified) {
if (jQuery.lastModified[cacheURL]) {
jqXHR.setRequestHeader("If-Modified-Since", jQuery.lastModified[cacheURL]);
}
if (jQuery.etag[cacheURL]) {
jqXHR.setRequestHeader("If-None-Match", jQuery.etag[cacheURL]);
}
}
// Set the correct header, if data is being sent
if (s.data && s.hasContent && s.contentType !== false || options.contentType) {
jqXHR.setRequestHeader("Content-Type", s.contentType);
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[0] && s.accepts[s.dataTypes[0]] ?
s.accepts[s.dataTypes[0]] + (s.dataTypes[0] !== "*" ? ", " + allTypes + "; q=0.01" : "") :
s.accepts["*"]
);
// Check for headers option
for (i in s.headers) {
jqXHR.setRequestHeader(i, s.headers[i]);
}
// Allow custom headers/mimetypes and early abort
if (s.beforeSend && (s.beforeSend.call(callbackContext, jqXHR, s) === false || state === 2)) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for (i in { success: 1, error: 1, complete: 1 }) {
jqXHR[i](s[i]);
}
// Get transport
transport = inspectPrefiltersOrTransports(transports, s, options, jqXHR);
// If no transport, we auto-abort
if (!transport) {
done(-1, "No Transport");
} else {
jqXHR.readyState = 1;
// Send global event
if (fireGlobals) {
globalEventContext.trigger("ajaxSend", [jqXHR, s]);
}
// Timeout
if (s.async && s.timeout > 0) {
timeoutTimer = setTimeout(function () {
jqXHR.abort("timeout");
}, s.timeout);
}
try {
state = 1;
transport.send(requestHeaders, done);
} catch (e) {
// Propagate exception as error if not done
if (state < 2) {
done(-1, e);
// Simply rethrow otherwise
} else {
throw e;
}
}
}
// Callback for when everything is done
function done(status, nativeStatusText, responses, headers) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if (state === 2) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if (timeoutTimer) {
clearTimeout(timeoutTimer);
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Get response data
if (responses) {
response = ajaxHandleResponses(s, jqXHR, responses);
}
// If successful, handle type chaining
if (status >= 200 && status < 300 || status === 304) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if (s.ifModified) {
modified = jqXHR.getResponseHeader("Last-Modified");
if (modified) {
jQuery.lastModified[cacheURL] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if (modified) {
jQuery.etag[cacheURL] = modified;
}
}
// if no content
if (status === 204) {
isSuccess = true;
statusText = "nocontent";
// if not modified
} else if (status === 304) {
isSuccess = true;
statusText = "notmodified";
// If we have data, let's convert it
} else {
isSuccess = ajaxConvert(s, response);
statusText = isSuccess.state;
success = isSuccess.data;
error = isSuccess.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if (status || !statusText) {
statusText = "error";
if (status < 0) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = (nativeStatusText || statusText) + "";
// Success/Error
if (isSuccess) {
deferred.resolveWith(callbackContext, [success, statusText, jqXHR]);
} else {
deferred.rejectWith(callbackContext, [jqXHR, statusText, error]);
}
// Status-dependent callbacks
jqXHR.statusCode(statusCode);
statusCode = undefined;
if (fireGlobals) {
globalEventContext.trigger(isSuccess ? "ajaxSuccess" : "ajaxError",
[jqXHR, s, isSuccess ? success : error]);
}
// Complete
completeDeferred.fireWith(callbackContext, [jqXHR, statusText]);
if (fireGlobals) {
globalEventContext.trigger("ajaxComplete", [jqXHR, s]);
// Handle the global AJAX counter
if (!(--jQuery.active)) {
jQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR;
};
jQuery.ajaxPrefilter = function (dataTypeExpression, func) {
/// <summary>
/// Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax().
/// </summary>
/// <param name="dataTypeExpression" type="String">
/// An optional string containing one or more space-separated dataTypes
/// </param>
/// <param name="func" type="Function">
/// A handler to set default values for future Ajax requests.
/// </param>
/// <returns type="undefined" />
if (typeof dataTypeExpression !== "string") {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match(core_rnotwhite) || [];
if (jQuery.isFunction(func)) {
// For each dataType in the dataTypeExpression
while ((dataType = dataTypes[i++])) {
// Prepend if requested
if (dataType[0] === "+") {
dataType = dataType.slice(1) || "*";
(structure[dataType] = structure[dataType] || []).unshift(func);
// Otherwise append
} else {
(structure[dataType] = structure[dataType] || []).push(func);
}
}
}
};
jQuery.ajaxSettings = {
"url": 'http://localhost:25812/',
"type": 'GET',
"isLocal": false,
"global": true,
"processData": true,
"async": true,
"contentType": 'application/x-www-form-urlencoded; charset=UTF-8',
"accepts": {},
"contents": {},
"responseFields": {},
"converters": {},
"flatOptions": {},
"jsonp": 'callback'
};
jQuery.ajaxSetup = function (target, settings) {
/// <summary>
/// Set default values for future Ajax requests.
/// </summary>
/// <param name="target" type="PlainObject">
/// A set of key/value pairs that configure the default Ajax request. All options are optional.
/// </param>
return settings ?
// Building a settings object
ajaxExtend(ajaxExtend(target, jQuery.ajaxSettings), settings) :
// Extending ajaxSettings
ajaxExtend(jQuery.ajaxSettings, target);
};
jQuery.ajaxTransport = function (dataTypeExpression, func) {
/// <summary>
/// Creates an object that handles the actual transmission of Ajax data.
/// </summary>
/// <param name="dataTypeExpression" type="String">
/// A string identifying the data type to use
/// </param>
/// <param name="func" type="Function">
/// A handler to return the new transport object to use with the data type provided in the first argument.
/// </param>
/// <returns type="undefined" />
if (typeof dataTypeExpression !== "string") {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match(core_rnotwhite) || [];
if (jQuery.isFunction(func)) {
// For each dataType in the dataTypeExpression
while ((dataType = dataTypes[i++])) {
// Prepend if requested
if (dataType[0] === "+") {
dataType = dataType.slice(1) || "*";
(structure[dataType] = structure[dataType] || []).unshift(func);
// Otherwise append
} else {
(structure[dataType] = structure[dataType] || []).push(func);
}
}
}
};
jQuery.attr = function (elem, name, value) {
var hooks, notxml, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if (!elem || nType === 3 || nType === 8 || nType === 2) {
return;
}
// Fallback to prop when attributes are not supported
if (typeof elem.getAttribute === core_strundefined) {
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);
} else if (hooks && notxml && "set" in hooks && (ret = hooks.set(elem, value, name)) !== undefined) {
return ret;
} else {
elem.setAttribute(name, value + "");
return value;
}
} else if (hooks && notxml && "get" in hooks && (ret = hooks.get(elem, name)) !== null) {
return ret;
} else {
// In IE9+, Flash objects don't have .getAttribute (#12945)
// Support: IE9+
if (typeof elem.getAttribute !== core_strundefined) {
ret = elem.getAttribute(name);
}
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
};
jQuery.attrHooks = { "type": {} };
jQuery.buildFragment = function (elems, context, scripts, selection) {
var j, elem, contains,
tmp, tag, tbody, wrap,
l = elems.length,
// Ensure a safe fragment
safe = createSafeFragment(context),
nodes = [],
i = 0;
for (; i < l; i++) {
elem = elems[i];
if (elem || elem === 0) {
// Add nodes directly
if (jQuery.type(elem) === "object") {
jQuery.merge(nodes, elem.nodeType ? [elem] : elem);
// Convert non-html into a text node
} else if (!rhtml.test(elem)) {
nodes.push(context.createTextNode(elem));
// Convert html into DOM nodes
} else {
tmp = tmp || safe.appendChild(context.createElement("div"));
// Deserialize a standard representation
tag = (rtagName.exec(elem) || ["", ""])[1].toLowerCase();
wrap = wrapMap[tag] || wrapMap._default;
tmp.innerHTML = wrap[1] + elem.replace(rxhtmlTag, "<$1></$2>") + wrap[2];
// Descend through wrappers to the right content
j = wrap[0];
while (j--) {
tmp = tmp.lastChild;
}
// Manually add leading whitespace removed by IE
if (!jQuery.support.leadingWhitespace && rleadingWhitespace.test(elem)) {
nodes.push(context.createTextNode(rleadingWhitespace.exec(elem)[0]));
}
// Remove IE's autoinserted <tbody> from table fragments
if (!jQuery.support.tbody) {
// String was a <table>, *may* have spurious <tbody>
elem = tag === "table" && !rtbody.test(elem) ?
tmp.firstChild :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !rtbody.test(elem) ?
tmp :
0;
j = elem && elem.childNodes.length;
while (j--) {
if (jQuery.nodeName((tbody = elem.childNodes[j]), "tbody") && !tbody.childNodes.length) {
elem.removeChild(tbody);
}
}
}
jQuery.merge(nodes, tmp.childNodes);
// Fix #12392 for WebKit and IE > 9
tmp.textContent = "";
// Fix #12392 for oldIE
while (tmp.firstChild) {
tmp.removeChild(tmp.firstChild);
}
// Remember the top-level container for proper cleanup
tmp = safe.lastChild;
}
}
}
// Fix #11356: Clear elements from fragment
if (tmp) {
safe.removeChild(tmp);
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if (!jQuery.support.appendChecked) {
jQuery.grep(getAll(nodes, "input"), fixDefaultChecked);
}
i = 0;
while ((elem = nodes[i++])) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if (selection && jQuery.inArray(elem, selection) !== -1) {
continue;
}
contains = jQuery.contains(elem.ownerDocument, elem);
// Append to fragment
tmp = getAll(safe.appendChild(elem), "script");
// Preserve script evaluation history
if (contains) {
setGlobalEval(tmp);
}
// Capture executables
if (scripts) {
j = 0;
while ((elem = tmp[j++])) {
if (rscriptType.test(elem.type || "")) {
scripts.push(elem);
}
}
}
}
tmp = null;
return safe;
};
jQuery.cache = {};
jQuery.camelCase = function (string) {
return string.replace(rmsPrefix, "ms-").replace(rdashAlpha, fcamelCase);
};
jQuery.cleanData = function (elems, /* internal */ acceptData) {
var elem, type, id, data,
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 (typeof elem.removeAttribute !== core_strundefined) {
elem.removeAttribute(internalKey);
} else {
elem[internalKey] = null;
}
core_deletedIds.push(id);
}
}
}
}
};
jQuery.clone = function (elem, dataAndEvents, deepDataAndEvents) {
var destElements, node, clone, i, srcElements,
inPage = jQuery.contains(elem.ownerDocument, elem);
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)) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll(clone);
srcElements = getAll(elem);
// Fix all IE cloning issues
for (i = 0; (node = srcElements[i]) != null; ++i) {
// Ensure that the destination node is not null; Fixes #9587
if (destElements[i]) {
fixCloneNodeIssues(node, destElements[i]);
}
}
}
// Copy the events from the original to the clone
if (dataAndEvents) {
if (deepDataAndEvents) {
srcElements = srcElements || getAll(elem);
destElements = destElements || getAll(clone);
for (i = 0; (node = srcElements[i]) != null; i++) {
cloneCopyEvent(node, destElements[i]);
}
} else {
cloneCopyEvent(elem, clone);
}
}
// Preserve script evaluation history
destElements = getAll(clone, "script");
if (destElements.length > 0) {
setGlobalEval(destElements, !inPage && getAll(elem, "script"));
}
destElements = srcElements = node = null;
// Return the cloned set
return clone;
};
jQuery.contains = function (context, elem) {
/// <summary>
/// Check to see if a DOM element is a descendant of another DOM element.
/// </summary>
/// <param name="context" domElement="true">
/// The DOM element that may contain the other element.
/// </param>
/// <param name="elem" domElement="true">
/// The DOM element that may be contained by (a descendant of) the other element.
/// </param>
/// <returns type="Boolean" />
// Set document vars if needed
if ((context.ownerDocument || context) !== document) {
setDocument(context);
}
return contains(context, elem);
};
jQuery.css = function (elem, name, extra, styles) {
var num, val, 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, styles);
}
//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 (extra === "" || extra) {
num = parseFloat(val);
return extra === true || jQuery.isNumeric(num) ? num || 0 : val;
}
return val;
};
jQuery.cssHooks = {
"opacity": {},
"height": {},
"width": {},
"margin": {},
"padding": {},
"borderWidth": {}
};
jQuery.cssNumber = {
"columnCount": true,
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
};
jQuery.cssProps = {
"float": 'cssFloat',
"display": 'display',
"visibility": 'visibility'
};
jQuery.data = function (elem, name, data) {
/// <summary>
/// 1: Store arbitrary data associated with the specified element. Returns the value that was set.
/// 1.1 - jQuery.data(element, key, value)
/// 2: Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element.
/// 2.1 - jQuery.data(element, key)
/// 2.2 - jQuery.data(element)
/// </summary>
/// <param name="elem" domElement="true">
/// The DOM element to associate with the data.
/// </param>
/// <param name="name" type="String">
/// A string naming the piece of data to set.
/// </param>
/// <param name="data" type="Object">
/// The new data value.
/// </param>
/// <returns type="Object" />
return internalData(elem, name, data);
};
jQuery.dequeue = function (elem, type) {
/// <summary>
/// Execute the next function on the queue for the matched element.
/// </summary>
/// <param name="elem" domElement="true">
/// A DOM element from which to remove and execute a queued function.
/// </param>
/// <param name="type" type="String">
/// A string containing the name of the queue. Defaults to fx, the standard effects queue.
/// </param>
/// <returns type="undefined" />
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--;
}
hooks.cur = fn;
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();
}
};
jQuery.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;
};
jQuery.each = function (obj, callback, args) {
/// <summary>
/// A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.
/// </summary>
/// <param name="obj" type="Object">
/// The object or array to iterate over.
/// </param>
/// <param name="callback" type="Function">
/// The function that will be executed on every object.
/// </param>
/// <returns type="Object" />
var value,
i = 0,
length = obj.length,
isArray = isArraylike(obj);
if (args) {
if (isArray) {
for (; i < length; i++) {
value = callback.apply(obj[i], args);
if (value === false) {
break;
}
}
} else {
for (i in obj) {
value = callback.apply(obj[i], args);
if (value === false) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if (isArray) {
for (; i < length; i++) {
value = callback.call(obj[i], i, obj[i]);
if (value === false) {
break;
}
}
} else {
for (i in obj) {
value = callback.call(obj[i], i, obj[i]);
if (value === false) {
break;
}
}
}
}
return obj;
};
jQuery.easing = {};
jQuery.error = function (msg) {
/// <summary>
/// Takes a string and throws an exception containing it.
/// </summary>
/// <param name="msg" type="String">
/// The message to send out.
/// </param>
throw new Error(msg);
};
jQuery.etag = {};
jQuery.event = {
"global": {},
"props": ['altKey', 'bubbles', 'cancelable', 'ctrlKey', 'currentTarget', 'eventPhase', 'metaKey', 'relatedTarget', 'shiftKey', 'target', 'timeStamp', 'view', 'which'],
"fixHooks": {},
"keyHooks": {},
"mouseHooks": {},
"special": {},
"triggered": {}
};
jQuery.expr = {
"cacheLength": 50,
"match": {},
"find": {},
"relative": {},
"preFilter": {},
"filter": {},
"pseudos": {},
"filters": {},
"setFilters": {},
"attrHandle": {},
":": {}
};
jQuery.extend = function () {
/// <summary>
/// Merge the contents of two or more objects together into the first object.
/// 1 - jQuery.extend(target, object1, objectN)
/// 2 - jQuery.extend(deep, target, object1, objectN)
/// </summary>
/// <param name="" type="Boolean">
/// If true, the merge becomes recursive (aka. deep copy).
/// </param>
/// <param name="" type="Object">
/// The object to extend. It will receive the new properties.
/// </param>
/// <param name="" type="Object">
/// An object containing additional properties to merge in.
/// </param>
/// <param name="" type="Object">
/// Additional objects containing properties to merge in.
/// </param>
/// <returns type="Object" />
var src, copyIsArray, copy, name, options, 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.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);
};
jQuery.find = 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);
};
jQuery.fn = {
"jquery": '1.11.1',
"selector": '',
"length": 0
};
jQuery.fx = function (elem, options, prop, end, easing, unit) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || (jQuery.cssNumber[prop] ? "" : "px");
};
jQuery.get = function (url, data, callback, type) {
/// <summary>
/// Load data from the server using a HTTP GET request.
/// </summary>
/// <param name="url" type="String">
/// A string containing the URL to which the request is sent.
/// </param>
/// <param name="data" type="String">
/// A plain object or string that is sent to the server with the request.
/// </param>
/// <param name="callback" type="Function">
/// A callback function that is executed if the request succeeds.
/// </param>
/// <param name="type" type="String">
/// The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).
/// </param>
// shift arguments if data argument was omitted
if (jQuery.isFunction(data)) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
jQuery.getJSON = function (url, data, callback) {
/// <summary>
/// Load JSON-encoded data from the server using a GET HTTP request.
/// </summary>
/// <param name="url" type="String">
/// A string containing the URL to which the request is sent.
/// </param>
/// <param name="data" type="PlainObject">
/// A plain object or string that is sent to the server with the request.
/// </param>
/// <param name="callback" type="Function">
/// A callback function that is executed if the request succeeds.
/// </param>
return jQuery.get(url, data, callback, "json");
};
jQuery.getScript = function (url, callback) {
/// <summary>
/// Load a JavaScript file from the server using a GET HTTP request, then execute it.
/// </summary>
/// <param name="url" type="String">
/// A string containing the URL to which the request is sent.
/// </param>
/// <param name="callback" type="Function">
/// A callback function that is executed if the request succeeds.
/// </param>
return jQuery.get(url, undefined, callback, "script");
};
jQuery.globalEval = function (data) {
/// <summary>
/// Execute some JavaScript code globally.
/// </summary>
/// <param name="data" type="String">
/// The JavaScript code to execute.
/// </param>
if (data && jQuery.trim(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);
}
};
jQuery.grep = function (elems, callback, inv) {
/// <summary>
/// Finds the elements of an array which satisfy a filter function. The original array is not affected.
/// </summary>
/// <param name="elems" type="Array">
/// The array to search through.
/// </param>
/// <param name="callback" type="Function">
/// The function to process each item against. The first argument to the function is the item, and the second argument is the index. The function should return a Boolean value. this will be the global window object.
/// </param>
/// <param name="inv" type="Boolean">
/// If "invert" is false, or not provided, then the function returns an array consisting of all elements for which "callback" returns true. If "invert" is true, then the function returns an array consisting of all elements for which "callback" returns false.
/// </param>
/// <returns type="Array" />
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;
};
jQuery.guid = 1;
jQuery.hasData = function (elem) {
/// <summary>
/// Determine whether an element has any jQuery data associated with it.
/// </summary>
/// <param name="elem" domElement="true">
/// A DOM element to be checked for data.
/// </param>
/// <returns type="Boolean" />
elem = elem.nodeType ? jQuery.cache[elem[jQuery.expando]] : elem[jQuery.expando];
return !!elem && !isEmptyDataObject(elem);
};
jQuery.holdReady = function (hold) {
/// <summary>
/// Holds or releases the execution of jQuery's ready event.
/// </summary>
/// <param name="hold" type="Boolean">
/// Indicates whether the ready hold is being requested or released
/// </param>
/// <returns type="undefined" />
if (hold) {
jQuery.readyWait++;
} else {
jQuery.ready(true);
}
};
jQuery.inArray = function (elem, arr, i) {
/// <summary>
/// Search for a specified value within an array and return its index (or -1 if not found).
/// </summary>
/// <param name="elem" type="Anything">
/// The value to search for.
/// </param>
/// <param name="arr" type="Array">
/// An array through which to search.
/// </param>
/// <param name="i" type="Number">
/// The index of the array at which to begin the search. The default is 0, which will search the whole array.
/// </param>
/// <returns type="Number" />
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;
};
jQuery.isEmptyObject = function (obj) {
/// <summary>
/// Check to see if an object is empty (contains no enumerable properties).
/// </summary>
/// <param name="obj" type="Object">
/// The object that will be checked to see if it's empty.
/// </param>
/// <returns type="Boolean" />
var name;
for (name in obj) {
return false;
}
return true;
};
jQuery.isFunction = function (obj) {
/// <summary>
/// Determine if the argument passed is a Javascript function object.
/// </summary>
/// <param name="obj" type="PlainObject">
/// Object to test whether or not it is a function.
/// </param>
/// <returns type="boolean" />
return jQuery.type(obj) === "function";
};
jQuery.isNumeric = function (obj) {
/// <summary>
/// Determines whether its argument is a number.
/// </summary>
/// <param name="obj" type="PlainObject">
/// The value to be tested.
/// </param>
/// <returns type="Boolean" />
return !isNaN(parseFloat(obj)) && isFinite(obj);
};
jQuery.isPlainObject = function (obj) {
/// <summary>
/// Check to see if an object is a plain object (created using "{}" or "new Object").
/// </summary>
/// <param name="obj" type="PlainObject">
/// The object that will be checked to see if it's a plain object.
/// </param>
/// <returns type="Boolean" />
// 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);
};
jQuery.isReady = true;
jQuery.isWindow = function (obj) {
/// <summary>
/// Determine whether the argument is a window.
/// </summary>
/// <param name="obj" type="PlainObject">
/// Object to test whether or not it is a window.
/// </param>
/// <returns type="boolean" />
return obj != null && obj == obj.window;
};
jQuery.isXMLDoc = function (elem) {
/// <summary>
/// Check to see if a DOM node is within an XML document (or is an XML document).
/// </summary>
/// <param name="elem" domElement="true">
/// The DOM node that will be checked to see if it's in an XML document.
/// </param>
/// <returns type="Boolean" />
// 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;
};
jQuery.lastModified = {};
jQuery.makeArray = function (arr, results) {
/// <summary>
/// Convert an array-like object into a true JavaScript array.
/// </summary>
/// <param name="arr" type="PlainObject">
/// Any object to turn into a native Array.
/// </param>
/// <returns type="Array" />
var ret = results || [];
if (arr != null) {
if (isArraylike(Object(arr))) {
jQuery.merge(ret,
typeof arr === "string" ?
[arr] : arr
);
} else {
core_push.call(ret, arr);
}
}
return ret;
};
jQuery.map = function (elems, callback, arg) {
/// <summary>
/// Translate all items in an array or object to new array of items.
/// 1 - jQuery.map(array, callback(elementOfArray, indexInArray))
/// 2 - jQuery.map(arrayOrObject, callback( value, indexOrKey ))
/// </summary>
/// <param name="elems" type="Array">
/// The Array to translate.
/// </param>
/// <param name="callback" type="Function">
/// The function to process each item against. The first argument to the function is the array item, the second argument is the index in array The function can return any value. Within the function, this refers to the global (window) object.
/// </param>
/// <returns type="Array" />
var value,
i = 0,
length = elems.length,
isArray = isArraylike(elems),
ret = [];
// 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 (i in elems) {
value = callback(elems[i], i, arg);
if (value != null) {
ret[ret.length] = value;
}
}
}
// Flatten any nested arrays
return core_concat.apply([], ret);
};
jQuery.merge = function (first, second) {
/// <summary>
/// Merge the contents of two arrays together into the first array.
/// </summary>
/// <param name="first" type="Array">
/// The first array to merge, the elements of second added.
/// </param>
/// <param name="second" type="Array">
/// The second array to merge into the first, unaltered.
/// </param>
/// <returns type="Array" />
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;
};
jQuery.noConflict = function (deep) {
/// <summary>
/// Relinquish jQuery's control of the $ variable.
/// </summary>
/// <param name="deep" type="Boolean">
/// A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself).
/// </param>
/// <returns type="Object" />
if (window.$ === jQuery) {
window.$ = _$;
}
if (deep && window.jQuery === jQuery) {
window.jQuery = _jQuery;
}
return jQuery;
};
jQuery.noData = {
"embed": true,
"object": 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000',
"applet": true
};
jQuery.nodeName = function (elem, name) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
};
jQuery.noop = function () {
/// <summary>
/// An empty function.
/// </summary>
/// <returns type="undefined" />
};
jQuery.now = function () {
/// <summary>
/// Return a number representing the current time.
/// </summary>
/// <returns type="Number" />
return (new Date()).getTime();
};
jQuery.offset = {};
jQuery.param = function (a, traditional) {
/// <summary>
/// Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.
/// 1 - jQuery.param(obj)
/// 2 - jQuery.param(obj, traditional)
/// </summary>
/// <param name="a" type="Object">
/// An array or object to serialize.
/// </param>
/// <param name="traditional" type="Boolean">
/// A Boolean indicating whether to perform a traditional "shallow" serialization.
/// </param>
/// <returns type="String" />
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, "+");
};
jQuery.parseHTML = function (data, context, keepScripts) {
/// <summary>
/// Parses a string into an array of DOM nodes.
/// </summary>
/// <param name="data" type="String">
/// HTML string to be parsed
/// </param>
/// <param name="context" domElement="true">
/// DOM element to serve as the context in which the HTML fragment will be created
/// </param>
/// <param name="keepScripts" type="Boolean">
/// A Boolean indicating whether to include scripts passed in the HTML string
/// </param>
/// <returns type="Array" />
if (!data || typeof data !== "string") {
return null;
}
if (typeof context === "boolean") {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec(data),
scripts = !keepScripts && [];
// Single tag
if (parsed) {
return [context.createElement(parsed[1])];
}
parsed = jQuery.buildFragment([data], context, scripts);
if (scripts) {
jQuery(scripts).remove();
}
return jQuery.merge([], parsed.childNodes);
};
jQuery.parseJSON = function (data) {
/// <summary>
/// Takes a well-formed JSON string and returns the resulting JavaScript object.
/// </summary>
/// <param name="data" type="String">
/// The JSON string to parse.
/// </param>
/// <returns type="Object" />
// Attempt to parse using the native JSON parser first
if (window.JSON && window.JSON.parse) {
return window.JSON.parse(data);
}
if (data === null) {
return data;
}
if (typeof data === "string") {
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim(data);
if (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);
};
jQuery.parseXML = function (data) {
/// <summary>
/// Parses a string into an XML document.
/// </summary>
/// <param name="data" type="String">
/// a well-formed XML string to be parsed
/// </param>
/// <returns type="XMLDocument" />
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;
};
jQuery.post = function (url, data, callback, type) {
/// <summary>
/// Load data from the server using a HTTP POST request.
/// </summary>
/// <param name="url" type="String">
/// A string containing the URL to which the request is sent.
/// </param>
/// <param name="data" type="String">
/// A plain object or string that is sent to the server with the request.
/// </param>
/// <param name="callback" type="Function">
/// A callback function that is executed if the request succeeds.
/// </param>
/// <param name="type" type="String">
/// The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).
/// </param>
// shift arguments if data argument was omitted
if (jQuery.isFunction(data)) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
jQuery.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];
}
}
};
jQuery.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'
};
jQuery.propHooks = {
"tabIndex": {},
"selected": {}
};
jQuery.proxy = function (fn, context) {
/// <summary>
/// Takes a function and returns a new one that will always have a particular context.
/// 1 - jQuery.proxy(function, context)
/// 2 - jQuery.proxy(context, name)
/// 3 - jQuery.proxy(function, context, additionalArguments)
/// 4 - jQuery.proxy(context, name, additionalArguments)
/// </summary>
/// <param name="fn" type="Function">
/// The function whose context will be changed.
/// </param>
/// <param name="context" type="PlainObject">
/// The object to which the context (this) of the function should be set.
/// </param>
/// <param name="" type="Anything">
/// Any number of arguments to be passed to the function referenced in the function argument.
/// </param>
/// <returns type="Function" />
var args, proxy, tmp;
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 || this, 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;
};
jQuery.queue = function (elem, type, data) {
/// <summary>
/// 1: Show the queue of functions to be executed on the matched element.
/// 1.1 - jQuery.queue(element, queueName)
/// 2: Manipulate the queue of functions to be executed on the matched element.
/// 2.1 - jQuery.queue(element, queueName, newQueue)
/// 2.2 - jQuery.queue(element, queueName, callback())
/// </summary>
/// <param name="elem" domElement="true">
/// A DOM element where the array of queued functions is attached.
/// </param>
/// <param name="type" type="String">
/// A string containing the name of the queue. Defaults to fx, the standard effects queue.
/// </param>
/// <param name="data" type="Array">
/// An array of functions to replace the current queue contents.
/// </param>
/// <returns type="jQuery" />
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 || [];
}
};
jQuery.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);
}
// 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");
}
};
jQuery.readyWait = 0;
jQuery.removeAttr = function (elem, value) {
var name, propName,
i = 0,
attrNames = value && value.match(core_rnotwhite);
if (attrNames && elem.nodeType === 1) {
while ((name = attrNames[i++])) {
propName = jQuery.propFix[name] || name;
// Boolean attributes get special treatment (#10870)
if (rboolean.test(name)) {
// Set corresponding property to false for boolean attributes
// Also clear defaultChecked/defaultSelected (if appropriate) for IE<8
if (!getSetAttribute && ruseDefault.test(name)) {
elem[jQuery.camelCase("default-" + name)] =
elem[propName] = false;
} else {
elem[propName] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
jQuery.attr(elem, name, "");
}
elem.removeAttribute(getSetAttribute ? name : propName);
}
}
};
jQuery.removeData = function (elem, name) {
/// <summary>
/// Remove a previously-stored piece of data.
/// </summary>
/// <param name="elem" domElement="true">
/// A DOM element from which to remove data.
/// </param>
/// <param name="name" type="String">
/// A string naming the piece of data to remove.
/// </param>
/// <returns type="jQuery" />
return internalRemoveData(elem, name);
};
jQuery.removeEvent = function (elem, type, handle) {
if (elem.removeEventListener) {
elem.removeEventListener(type, handle, false);
}
};
jQuery.sibling = function (n, elem) {
var r = [];
for (; n; n = n.nextSibling) {
if (n.nodeType === 1 && n !== elem) {
r.push(n);
}
}
return r;
};
jQuery.speed = function (speed, easing, fn) {
var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : {
complete: fn || !fn && easing ||
jQuery.isFunction(speed) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if (opt.queue == null || opt.queue === true) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function () {
if (jQuery.isFunction(opt.old)) {
opt.old.call(this);
}
if (opt.queue) {
jQuery.dequeue(this, opt.queue);
}
};
return opt;
};
jQuery.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";
}
// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if (!jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0) {
style[name] = "inherit";
}
// 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];
}
};
jQuery.support = {
"getSetAttribute": true,
"leadingWhitespace": true,
"tbody": true,
"htmlSerialize": true,
"style": true,
"hrefNormalized": true,
"opacity": true,
"cssFloat": true,
"checkOn": true,
"optSelected": false,
"enctype": true,
"html5Clone": true,
"boxModel": true,
"deleteExpando": true,
"noCloneEvent": true,
"inlineBlockNeedsLayout": false,
"shrinkWrapBlocks": false,
"reliableMarginRight": true,
"boxSizingReliable": false,
"pixelPosition": true,
"noCloneChecked": false,
"optDisabled": true,
"input": true,
"radioValue": false,
"appendChecked": true,
"checkClone": true,
"submitBubbles": true,
"changeBubbles": true,
"focusinBubbles": true,
"clearCloneStyle": false,
"cors": true,
"ajax": true,
"reliableHiddenOffsets": true,
"boxSizing": true,
"doesNotIncludeMarginInBodyOffset": true
};
jQuery.swap = function (elem, options, callback, args) {
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.apply(elem, args || []);
// Revert the old values
for (name in options) {
elem.style[name] = old[name];
}
return ret;
};
jQuery.text = 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;
};
jQuery.trim = function (text) {
/// <summary>
/// Remove the whitespace from the beginning and end of a string.
/// </summary>
/// <param name="text" type="String">
/// The string to trim.
/// </param>
/// <returns type="String" />
return text == null ?
"" :
core_trim.call(text);
};
jQuery.type = function (obj) {
/// <summary>
/// Determine the internal JavaScript [[Class]] of an object.
/// </summary>
/// <param name="obj" type="PlainObject">
/// Object to get the internal JavaScript [[Class]] of.
/// </param>
/// <returns type="String" />
if (obj == null) {
return String(obj);
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[core_toString.call(obj)] || "object" :
typeof obj;
};
jQuery.unique = function (results) {
/// <summary>
/// Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers.
/// </summary>
/// <param name="results" type="Array">
/// The Array of DOM elements.
/// </param>
/// <returns type="Array" />
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;
};
jQuery.valHooks = {
"option": {},
"select": {},
"radio": {},
"checkbox": {}
};
jQuery.when = function (subordinate /* , ..., subordinateN */) {
/// <summary>
/// Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.
/// </summary>
/// <param name="subordinate/*" type="Deferred">
/// One or more Deferred objects, or plain JavaScript objects.
/// </param>
/// <returns type="Promise" />
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.Event.prototype.isDefaultPrevented = function returnFalse() {
/// <summary>
/// Returns whether event.preventDefault() was ever called on this event object.
/// </summary>
/// <returns type="Boolean" />
return false;
};
jQuery.Event.prototype.isImmediatePropagationStopped = function returnFalse() {
/// <summary>
/// Returns whether event.stopImmediatePropagation() was ever called on this event object.
/// </summary>
/// <returns type="Boolean" />
return false;
};
jQuery.Event.prototype.isPropagationStopped = function returnFalse() {
/// <summary>
/// Returns whether event.stopPropagation() was ever called on this event object.
/// </summary>
/// <returns type="Boolean" />
return false;
};
jQuery.Event.prototype.preventDefault = function () {
/// <summary>
/// If this method is called, the default action of the event will not be triggered.
/// </summary>
/// <returns type="undefined" />
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if (!e) {
return;
}
// If preventDefault exists, run it on the original event
if (e.preventDefault) {
e.preventDefault();
// Support: IE
// Otherwise set the returnValue property of the original event to false
} else {
e.returnValue = false;
}
};
jQuery.Event.prototype.stopImmediatePropagation = function () {
/// <summary>
/// Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.
/// </summary>
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
};
jQuery.Event.prototype.stopPropagation = function () {
/// <summary>
/// Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
/// </summary>
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if (!e) {
return;
}
// If stopPropagation exists, run it on the original event
if (e.stopPropagation) {
e.stopPropagation();
}
// Support: IE
// Set the cancelBubble property of the original event to true
e.cancelBubble = true;
};
jQuery.prototype.add = function (selector, context) {
/// <summary>
/// Add elements to the set of matched elements.
/// 1 - add(selector)
/// 2 - add(elements)
/// 3 - add(html)
/// 4 - add(jQuery object)
/// 5 - add(selector, context)
/// </summary>
/// <param name="selector" type="String">
/// A string representing a selector expression to find additional elements to add to the set of matched elements.
/// </param>
/// <param name="context" domElement="true">
/// The point in the document at which the selector should begin matching; similar to the context argument of the $(selector, context) method.
/// </param>
/// <returns type="jQuery" />
var set = typeof selector === "string" ?
jQuery(selector, context) :
jQuery.makeArray(selector && selector.nodeType ? [selector] : selector),
all = jQuery.merge(this.get(), set);
return this.pushStack(jQuery.unique(all));
};
jQuery.prototype.addBack = function (selector) {
/// <summary>
/// Add the previous set of elements on the stack to the current set, optionally filtered by a selector.
/// </summary>
/// <param name="selector" type="String">
/// A string containing a selector expression to match the current set of elements against.
/// </param>
/// <returns type="jQuery" />
return this.add(selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
};
jQuery.prototype.addClass = function (value) {
/// <summary>
/// Adds the specified class(es) to each of the set of matched elements.
/// 1 - addClass(className)
/// 2 - addClass(function(index, currentClass))
/// </summary>
/// <param name="value" type="String">
/// One or more space-separated classes to be added to the class attribute of each matched element.
/// </param>
/// <returns type="jQuery" />
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if (jQuery.isFunction(value)) {
return this.each(function (j) {
jQuery(this).addClass(value.call(this, j, this.className));
});
}
if (proceed) {
// The disjunction here is for better compressibility (see removeClass)
classes = (value || "").match(core_rnotwhite) || [];
for (; i < len; i++) {
elem = this[i];
cur = elem.nodeType === 1 && (elem.className ?
(" " + elem.className + " ").replace(rclass, " ") :
" "
);
if (cur) {
j = 0;
while ((clazz = classes[j++])) {
if (cur.indexOf(" " + clazz + " ") < 0) {
cur += clazz + " ";
}
}
elem.className = jQuery.trim(cur);
}
}
}
return this;
};
jQuery.prototype.after = function () {
/// <summary>
/// Insert content, specified by the parameter, after each element in the set of matched elements.
/// 1 - after(content, content)
/// 2 - after(function(index))
/// </summary>
/// <param name="" type="jQuery">
/// HTML string, DOM element, or jQuery object to insert after each element in the set of matched elements.
/// </param>
/// <param name="" type="jQuery">
/// One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert after each element in the set of matched elements.
/// </param>
/// <returns type="jQuery" />
return this.domManip(arguments, false, function (elem) {
if (this.parentNode) {
this.parentNode.insertBefore(elem, this.nextSibling);
}
});
};
jQuery.prototype.ajaxComplete = function (fn) {
/// <summary>
/// Register a handler to be called when Ajax requests complete. This is an AjaxEvent.
/// </summary>
/// <param name="fn" type="Function">
/// The function to be invoked.
/// </param>
/// <returns type="jQuery" />
return this.on(type, fn);
};
jQuery.prototype.ajaxError = function (fn) {
/// <summary>
/// Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event.
/// </summary>
/// <param name="fn" type="Function">
/// The function to be invoked.
/// </param>
/// <returns type="jQuery" />
return this.on(type, fn);
};
jQuery.prototype.ajaxSend = function (fn) {
/// <summary>
/// Attach a function to be executed before an Ajax request is sent. This is an Ajax Event.
/// </summary>
/// <param name="fn" type="Function">
/// The function to be invoked.
/// </param>
/// <returns type="jQuery" />
return this.on(type, fn);
};
jQuery.prototype.ajaxStart = function (fn) {
/// <summary>
/// Register a handler to be called when the first Ajax request begins. This is an Ajax Event.
/// </summary>
/// <param name="fn" type="Function">
/// The function to be invoked.
/// </param>
/// <returns type="jQuery" />
return this.on(type, fn);
};
jQuery.prototype.ajaxStop = function (fn) {
/// <summary>
/// Register a handler to be called when all Ajax requests have completed. This is an Ajax Event.
/// </summary>
/// <param name="fn" type="Function">
/// The function to be invoked.
/// </param>
/// <returns type="jQuery" />
return this.on(type, fn);
};
jQuery.prototype.ajaxSuccess = function (fn) {
/// <summary>
/// Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event.
/// </summary>
/// <param name="fn" type="Function">
/// The function to be invoked.
/// </param>
/// <returns type="jQuery" />
return this.on(type, fn);
};
jQuery.prototype.andSelf = function (selector) {
/// <summary>
/// Add the previous set of elements on the stack to the current set.
/// </summary>
/// <returns type="jQuery" />
return this.add(selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
};
jQuery.prototype.animate = function (prop, speed, easing, callback) {
/// <summary>
/// Perform a custom animation of a set of CSS properties.
/// 1 - animate(properties, duration, easing, complete)
/// 2 - animate(properties, options)
/// </summary>
/// <param name="prop" type="PlainObject">
/// An object of CSS properties and values that the animation will move toward.
/// </param>
/// <param name="speed" type="">
/// A string or number determining how long the animation will run.
/// </param>
/// <param name="easing" type="String">
/// A string indicating which easing function to use for the transition.
/// </param>
/// <param name="callback" type="Function">
/// A function to call once the animation is complete.
/// </param>
/// <returns type="jQuery" />
var empty = jQuery.isEmptyObject(prop),
optall = jQuery.speed(speed, easing, callback),
doAnimation = function () {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation(this, jQuery.extend({}, prop), optall);
doAnimation.finish = function () {
anim.stop(true);
};
// Empty animations, or finishing resolves immediately
if (empty || jQuery._data(this, "finish")) {
anim.stop(true);
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each(doAnimation) :
this.queue(optall.queue, doAnimation);
};
jQuery.prototype.append = function () {
/// <summary>
/// Insert content, specified by the parameter, to the end of each element in the set of matched elements.
/// 1 - append(content, content)
/// 2 - append(function(index, html))
/// </summary>
/// <param name="" type="jQuery">
/// DOM element, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.
/// </param>
/// <param name="" type="jQuery">
/// One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.
/// </param>
/// <returns type="jQuery" />
return this.domManip(arguments, true, function (elem) {
if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) {
this.appendChild(elem);
}
});
};
jQuery.prototype.appendTo = function (selector) {
/// <summary>
/// Insert every element in the set of matched elements to the end of the target.
/// </summary>
/// <param name="selector" type="jQuery">
/// A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter.
/// </param>
/// <returns type="jQuery" />
var elems,
i = 0,
ret = [],
insert = jQuery(selector),
last = insert.length - 1;
for (; i <= last; i++) {
elems = i === last ? this : this.clone(true);
jQuery(insert[i])[original](elems);
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
core_push.apply(ret, elems.get());
}
return this.pushStack(ret);
};
jQuery.prototype.attr = function (name, value) {
/// <summary>
/// 1: Get the value of an attribute for the first element in the set of matched elements.
/// 1.1 - attr(attributeName)
/// 2: Set one or more attributes for the set of matched elements.
/// 2.1 - attr(attributeName, value)
/// 2.2 - attr(attributes)
/// 2.3 - attr(attributeName, function(index, attr))
/// </summary>
/// <param name="name" type="String">
/// The name of the attribute to set.
/// </param>
/// <param name="value" type="Number">
/// A value to set for the attribute.
/// </param>
/// <returns type="jQuery" />
return jQuery.access(this, jQuery.attr, name, value, arguments.length > 1);
};
jQuery.prototype.before = function () {
/// <summary>
/// Insert content, specified by the parameter, before each element in the set of matched elements.
/// 1 - before(content, content)
/// 2 - before(function)
/// </summary>
/// <param name="" type="jQuery">
/// HTML string, DOM element, or jQuery object to insert before each element in the set of matched elements.
/// </param>
/// <param name="" type="jQuery">
/// One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert before each element in the set of matched elements.
/// </param>
/// <returns type="jQuery" />
return this.domManip(arguments, false, function (elem) {
if (this.parentNode) {
this.parentNode.insertBefore(elem, this);
}
});
};
jQuery.prototype.bind = function (types, data, fn) {
/// <summary>
/// Attach a handler to an event for the elements.
/// 1 - bind(eventType, eventData, handler(eventObject))
/// 2 - bind(eventType, eventData, preventBubble)
/// 3 - bind(events)
/// </summary>
/// <param name="types" type="String">
/// A string containing one or more DOM event types, such as "click" or "submit," or custom event names.
/// </param>
/// <param name="data" type="Object">
/// An object containing data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return this.on(types, null, data, fn);
};
jQuery.prototype.blur = function (data, fn) {
/// <summary>
/// Bind an event handler to the "blur" JavaScript event, or trigger that event on an element.
/// 1 - blur(handler(eventObject))
/// 2 - blur(eventData, handler(eventObject))
/// 3 - blur()
/// </summary>
/// <param name="data" type="Object">
/// An object containing data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return arguments.length > 0 ?
this.on(name, null, data, fn) :
this.trigger(name);
};
jQuery.prototype.change = function (data, fn) {
/// <summary>
/// Bind an event handler to the "change" JavaScript event, or trigger that event on an element.
/// 1 - change(handler(eventObject))
/// 2 - change(eventData, handler(eventObject))
/// 3 - change()
/// </summary>
/// <param name="data" type="Object">
/// An object containing data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return arguments.length > 0 ?
this.on(name, null, data, fn) :
this.trigger(name);
};
jQuery.prototype.children = function (until, selector) {
/// <summary>
/// Get the children of each element in the set of matched elements, optionally filtered by a selector.
/// </summary>
/// <param name="until" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="jQuery" />
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);
};
jQuery.prototype.clearQueue = function (type) {
/// <summary>
/// Remove from the queue all items that have not yet been run.
/// </summary>
/// <param name="type" type="String">
/// A string containing the name of the queue. Defaults to fx, the standard effects queue.
/// </param>
/// <returns type="jQuery" />
return this.queue(type || "fx", []);
};
jQuery.prototype.click = function (data, fn) {
/// <summary>
/// Bind an event handler to the "click" JavaScript event, or trigger that event on an element.
/// 1 - click(handler(eventObject))
/// 2 - click(eventData, handler(eventObject))
/// 3 - click()
/// </summary>
/// <param name="data" type="Object">
/// An object containing data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return arguments.length > 0 ?
this.on(name, null, data, fn) :
this.trigger(name);
};
jQuery.prototype.clone = function (dataAndEvents, deepDataAndEvents) {
/// <summary>
/// Create a deep copy of the set of matched elements.
/// 1 - clone(withDataAndEvents)
/// 2 - clone(withDataAndEvents, deepWithDataAndEvents)
/// </summary>
/// <param name="dataAndEvents" type="Boolean">
/// A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false. *In jQuery 1.5.0 the default value was incorrectly true; it was changed back to false in 1.5.1 and up.
/// </param>
/// <param name="deepDataAndEvents" type="Boolean">
/// A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to false).
/// </param>
/// <returns type="jQuery" />
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map(function () {
return jQuery.clone(this, dataAndEvents, deepDataAndEvents);
});
};
jQuery.prototype.closest = function (selectors, context) {
/// <summary>
/// 1: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
/// 1.1 - closest(selector)
/// 1.2 - closest(selector, context)
/// 1.3 - closest(jQuery object)
/// 1.4 - closest(element)
/// 2: Get an array of all the elements and selectors matched against the current element up through the DOM tree.
/// 2.1 - closest(selectors, context)
/// </summary>
/// <param name="selectors" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <param name="context" domElement="true">
/// A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead.
/// </param>
/// <returns type="jQuery" />
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;
}
}
return this.pushStack(ret.length > 1 ? jQuery.unique(ret) : ret);
};
jQuery.prototype.constructor = function (selector, context) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init(selector, context, rootjQuery);
};
jQuery.prototype.contents = function (until, selector) {
/// <summary>
/// Get the children of each element in the set of matched elements, including text and comment nodes.
/// </summary>
/// <returns type="jQuery" />
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);
};
jQuery.prototype.contextmenu = function (data, fn) {
return arguments.length > 0 ?
this.on(name, null, data, fn) :
this.trigger(name);
};
jQuery.prototype.css = function (name, value) {
/// <summary>
/// 1: Get the value of style properties for the first element in the set of matched elements.
/// 1.1 - css(propertyName)
/// 1.2 - css(propertyNames)
/// 2: Set one or more CSS properties for the set of matched elements.
/// 2.1 - css(propertyName, value)
/// 2.2 - css(propertyName, function(index, value))
/// 2.3 - css(properties)
/// </summary>
/// <param name="name" type="String">
/// A CSS property name.
/// </param>
/// <param name="value" type="Number">
/// A value to set for the property.
/// </param>
/// <returns type="jQuery" />
return jQuery.access(this, function (elem, name, value) {
var len, styles,
map = {},
i = 0;
if (jQuery.isArray(name)) {
styles = getStyles(elem);
len = name.length;
for (; i < len; i++) {
map[name[i]] = jQuery.css(elem, name[i], false, styles);
}
return map;
}
return value !== undefined ?
jQuery.style(elem, name, value) :
jQuery.css(elem, name);
}, name, value, arguments.length > 1);
};
jQuery.prototype.data = function (key, value) {
/// <summary>
/// 1: Store arbitrary data associated with the matched elements.
/// 1.1 - data(key, value)
/// 1.2 - data(obj)
/// 2: Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.
/// 2.1 - data(key)
/// 2.2 - data()
/// </summary>
/// <param name="key" type="String">
/// A string naming the piece of data to set.
/// </param>
/// <param name="value" type="Object">
/// The new data value; it can be any Javascript type including Array or Object.
/// </param>
/// <returns type="jQuery" />
var attrs, name,
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")) {
attrs = elem.attributes;
for (; i < attrs.length; i++) {
name = attrs[i].name;
if (!name.indexOf("data-")) {
name = jQuery.camelCase(name.slice(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);
});
}
return jQuery.access(this, function (value) {
if (value === undefined) {
// Try to fetch any internally stored data first
return elem ? dataAttr(elem, key, jQuery.data(elem, key)) : null;
}
this.each(function () {
jQuery.data(this, key, value);
});
}, null, value, arguments.length > 1, null, true);
};
jQuery.prototype.dblclick = function (data, fn) {
/// <summary>
/// Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element.
/// 1 - dblclick(handler(eventObject))
/// 2 - dblclick(eventData, handler(eventObject))
/// 3 - dblclick()
/// </summary>
/// <param name="data" type="Object">
/// An object containing data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return arguments.length > 0 ?
this.on(name, null, data, fn) :
this.trigger(name);
};
jQuery.prototype.delay = function (time, type) {
/// <summary>
/// Set a timer to delay execution of subsequent items in the queue.
/// </summary>
/// <param name="time" type="Number">
/// An integer indicating the number of milliseconds to delay execution of the next item in the queue.
/// </param>
/// <param name="type" type="String">
/// A string containing the name of the queue. Defaults to fx, the standard effects queue.
/// </param>
/// <returns type="jQuery" />
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);
};
});
};
jQuery.prototype.delegate = function (selector, types, data, fn) {
/// <summary>
/// Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.
/// 1 - delegate(selector, eventType, handler(eventObject))
/// 2 - delegate(selector, eventType, eventData, handler(eventObject))
/// 3 - delegate(selector, events)
/// </summary>
/// <param name="selector" type="String">
/// A selector to filter the elements that trigger the event.
/// </param>
/// <param name="types" type="String">
/// A string containing one or more space-separated JavaScript event types, such as "click" or "keydown," or custom event names.
/// </param>
/// <param name="data" type="Object">
/// An object containing data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute at the time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return this.on(types, selector, data, fn);
};
jQuery.prototype.dequeue = function (type) {
/// <summary>
/// Execute the next function on the queue for the matched elements.
/// </summary>
/// <param name="type" type="String">
/// A string containing the name of the queue. Defaults to fx, the standard effects queue.
/// </param>
/// <returns type="jQuery" />
return this.each(function () {
jQuery.dequeue(this, type);
});
};
jQuery.prototype.detach = function (selector) {
/// <summary>
/// Remove the set of matched elements from the DOM.
/// </summary>
/// <param name="selector" type="String">
/// A selector expression that filters the set of matched elements to be removed.
/// </param>
/// <returns type="jQuery" />
return this.remove(selector, true);
};
jQuery.prototype.domManip = function (args, table, callback) {
// Flatten any nested arrays
args = core_concat.apply([], args);
var first, node, hasScripts,
scripts, doc, fragment,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[0],
isFunction = jQuery.isFunction(value);
// We can't cloneNode fragments that contain checked, in WebKit
if (isFunction || !(l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test(value))) {
return this.each(function (index) {
var self = set.eq(index);
if (isFunction) {
args[0] = value.call(this, index, table ? self.html() : undefined);
}
self.domManip(args, table, callback);
});
}
if (l) {
fragment = jQuery.buildFragment(args, this[0].ownerDocument, false, this);
first = fragment.firstChild;
if (fragment.childNodes.length === 1) {
fragment = first;
}
if (first) {
table = table && jQuery.nodeName(first, "tr");
scripts = jQuery.map(getAll(fragment, "script"), disableScript);
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for (; i < l; i++) {
node = fragment;
if (i !== iNoClone) {
node = jQuery.clone(node, true, true);
// Keep references to cloned scripts for later restoration
if (hasScripts) {
jQuery.merge(scripts, getAll(node, "script"));
}
}
callback.call(
table && jQuery.nodeName(this[i], "table") ?
findOrAppend(this[i], "tbody") :
this[i],
node,
i
);
}
if (hasScripts) {
doc = scripts[scripts.length - 1].ownerDocument;
// Reenable scripts
jQuery.map(scripts, restoreScript);
// Evaluate executable scripts on first document insertion
for (i = 0; i < hasScripts; i++) {
node = scripts[i];
if (rscriptType.test(node.type || "") &&
!jQuery._data(node, "globalEval") && jQuery.contains(doc, node)) {
if (node.src) {
// Hope ajax is available...
jQuery.ajax({
url: node.src,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
} else {
jQuery.globalEval((node.text || node.textContent || node.innerHTML || "").replace(rcleanScript, ""));
}
}
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
}
}
return this;
};
jQuery.prototype.each = function (callback, args) {
/// <summary>
/// Iterate over a jQuery object, executing a function for each matched element.
/// </summary>
/// <param name="callback" type="Function">
/// A function to execute for each matched element.
/// </param>
/// <returns type="jQuery" />
return jQuery.each(this, callback, args);
};
jQuery.prototype.empty = function () {
/// <summary>
/// Remove all child nodes of the set of matched elements from the DOM.
/// </summary>
/// <returns type="jQuery" />
var elem,
i = 0;
for (; (elem = this[i]) != null; i++) {
// Remove element nodes and prevent memory leaks
if (elem.nodeType === 1) {
jQuery.cleanData(getAll(elem, false));
}
// Remove any remaining nodes
while (elem.firstChild) {
elem.removeChild(elem.firstChild);
}
// If this is a select, ensure that it displays empty (#12336)
// Support: IE<9
if (elem.options && jQuery.nodeName(elem, "select")) {
elem.options.length = 0;
}
}
return this;
};
jQuery.prototype.end = function () {
/// <summary>
/// End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.
/// </summary>
/// <returns type="jQuery" />
return this.prevObject || this.constructor(null);
};
jQuery.prototype.eq = function (i) {
/// <summary>
/// Reduce the set of matched elements to the one at the specified index.
/// 1 - eq(index)
/// 2 - eq(-index)
/// </summary>
/// <param name="i" type="Number">
/// An integer indicating the 0-based position of the element.
/// </param>
/// <returns type="jQuery" />
var len = this.length,
j = +i + (i < 0 ? len : 0);
return this.pushStack(j >= 0 && j < len ? [this[j]] : []);
};
jQuery.prototype.error = function (data, fn) {
/// <summary>
/// Bind an event handler to the "error" JavaScript event.
/// 1 - error(handler(eventObject))
/// 2 - error(eventData, handler(eventObject))
/// </summary>
/// <param name="data" type="Object">
/// An object containing data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return arguments.length > 0 ?
this.on(name, null, data, fn) :
this.trigger(name);
};
jQuery.prototype.extend = function () {
var src, copyIsArray, copy, name, options, 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.prototype.fadeIn = function (speed, easing, callback) {
/// <summary>
/// Display the matched elements by fading them to opaque.
/// 1 - fadeIn(duration, complete)
/// 2 - fadeIn(options)
/// 3 - fadeIn(duration, easing, complete)
/// </summary>
/// <param name="speed" type="">
/// A string or number determining how long the animation will run.
/// </param>
/// <param name="easing" type="String">
/// A string indicating which easing function to use for the transition.
/// </param>
/// <param name="callback" type="Function">
/// A function to call once the animation is complete.
/// </param>
/// <returns type="jQuery" />
return this.animate(props, speed, easing, callback);
};
jQuery.prototype.fadeOut = function (speed, easing, callback) {
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// 1 - fadeOut(duration, complete)
/// 2 - fadeOut(options)
/// 3 - fadeOut(duration, easing, complete)
/// </summary>
/// <param name="speed" type="">
/// A string or number determining how long the animation will run.
/// </param>
/// <param name="easing" type="String">
/// A string indicating which easing function to use for the transition.
/// </param>
/// <param name="callback" type="Function">
/// A function to call once the animation is complete.
/// </param>
/// <returns type="jQuery" />
return this.animate(props, speed, easing, callback);
};
jQuery.prototype.fadeTo = function (speed, to, easing, callback) {
/// <summary>
/// Adjust the opacity of the matched elements.
/// 1 - fadeTo(duration, opacity, complete)
/// 2 - fadeTo(duration, opacity, easing, complete)
/// </summary>
/// <param name="speed" type="Number">
/// A string or number determining how long the animation will run.
/// </param>
/// <param name="to" type="Number">
/// A number between 0 and 1 denoting the target opacity.
/// </param>
/// <param name="easing" type="String">
/// A string indicating which easing function to use for the transition.
/// </param>
/// <param name="callback" type="Function">
/// A function to call once the animation is complete.
/// </param>
/// <returns type="jQuery" />
// show any hidden elements after setting opacity to 0
return this.filter(isHidden).css("opacity", 0).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback);
};
jQuery.prototype.fadeToggle = function (speed, easing, callback) {
/// <summary>
/// Display or hide the matched elements by animating their opacity.
/// 1 - fadeToggle(duration, easing, complete)
/// 2 - fadeToggle(options)
/// </summary>
/// <param name="speed" type="">
/// A string or number determining how long the animation will run.
/// </param>
/// <param name="easing" type="String">
/// A string indicating which easing function to use for the transition.
/// </param>
/// <param name="callback" type="Function">
/// A function to call once the animation is complete.
/// </param>
/// <returns type="jQuery" />
return this.animate(props, speed, easing, callback);
};
jQuery.prototype.filter = function (selector) {
/// <summary>
/// Reduce the set of matched elements to those that match the selector or pass the function's test.
/// 1 - filter(selector)
/// 2 - filter(function(index))
/// 3 - filter(element)
/// 4 - filter(jQuery object)
/// </summary>
/// <param name="selector" type="String">
/// A string containing a selector expression to match the current set of elements against.
/// </param>
/// <returns type="jQuery" />
return this.pushStack(winnow(this, selector, true));
};
jQuery.prototype.find = function (selector) {
/// <summary>
/// Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
/// 1 - find(selector)
/// 2 - find(jQuery object)
/// 3 - find(element)
/// </summary>
/// <param name="selector" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="jQuery" />
var i, ret, self,
len = this.length;
if (typeof selector !== "string") {
self = this;
return this.pushStack(jQuery(selector).filter(function () {
for (i = 0; i < len; i++) {
if (jQuery.contains(self[i], this)) {
return true;
}
}
}));
}
ret = [];
for (i = 0; i < len; i++) {
jQuery.find(selector, this[i], ret);
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack(len > 1 ? jQuery.unique(ret) : ret);
ret.selector = (this.selector ? this.selector + " " : "") + selector;
return ret;
};
jQuery.prototype.finish = function (type) {
/// <summary>
/// Stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements.
/// </summary>
/// <param name="type" type="String">
/// The name of the queue in which to stop animations.
/// </param>
/// <returns type="jQuery" />
if (type !== false) {
type = type || "fx";
}
return this.each(function () {
var index,
data = jQuery._data(this),
queue = data[type + "queue"],
hooks = data[type + "queueHooks"],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// enable finishing flag on private data
data.finish = true;
// empty the queue first
jQuery.queue(this, type, []);
if (hooks && hooks.cur && hooks.cur.finish) {
hooks.cur.finish.call(this);
}
// look for any active animations, and finish them
for (index = timers.length; index--;) {
if (timers[index].elem === this && timers[index].queue === type) {
timers[index].anim.stop(true);
timers.splice(index, 1);
}
}
// look for any animations in the old queue and finish them
for (index = 0; index < length; index++) {
if (queue[index] && queue[index].finish) {
queue[index].finish.call(this);
}
}
// turn off finishing flag
delete data.finish;
});
};
jQuery.prototype.first = function () {
/// <summary>
/// Reduce the set of matched elements to the first in the set.
/// </summary>
/// <returns type="jQuery" />
return this.eq(0);
};
jQuery.prototype.focus = function (data, fn) {
/// <summary>
/// Bind an event handler to the "focus" JavaScript event, or trigger that event on an element.
/// 1 - focus(handler(eventObject))
/// 2 - focus(eventData, handler(eventObject))
/// 3 - focus()
/// </summary>
/// <param name="data" type="Object">
/// An object containing data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return arguments.length > 0 ?
this.on(name, null, data, fn) :
this.trigger(name);
};
jQuery.prototype.focusin = function (data, fn) {
/// <summary>
/// Bind an event handler to the "focusin" event.
/// 1 - focusin(handler(eventObject))
/// 2 - focusin(eventData, handler(eventObject))
/// </summary>
/// <param name="data" type="Object">
/// An object containing data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return arguments.length > 0 ?
this.on(name, null, data, fn) :
this.trigger(name);
};
jQuery.prototype.focusout = function (data, fn) {
/// <summary>
/// Bind an event handler to the "focusout" JavaScript event.
/// 1 - focusout(handler(eventObject))
/// 2 - focusout(eventData, handler(eventObject))
/// </summary>
/// <param name="data" type="Object">
/// An object containing data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return arguments.length > 0 ?
this.on(name, null, data, fn) :
this.trigger(name);
};
jQuery.prototype.get = function (num) {
/// <summary>
/// Retrieve the DOM elements matched by the jQuery object.
/// </summary>
/// <param name="num" type="Number">
/// A zero-based integer indicating which element to retrieve.
/// </param>
/// <returns type="Array" />
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
(num < 0 ? this[this.length + num] : this[num]);
};
jQuery.prototype.has = function (target) {
/// <summary>
/// Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.
/// 1 - has(selector)
/// 2 - has(contained)
/// </summary>
/// <param name="target" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="jQuery" />
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;
}
}
});
};
jQuery.prototype.hasClass = function (selector) {
/// <summary>
/// Determine whether any of the matched elements are assigned the given class.
/// </summary>
/// <param name="selector" type="String">
/// The class name to search for.
/// </param>
/// <returns type="Boolean" />
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;
};
jQuery.prototype.height = function (margin, value) {
/// <summary>
/// 1: Get the current computed height for the first element in the set of matched elements.
/// 1.1 - height()
/// 2: Set the CSS height of every matched element.
/// 2.1 - height(value)
/// 2.2 - height(function(index, height))
/// </summary>
/// <param name="margin" type="Number">
/// An integer representing the number of pixels, or an integer with an optional unit of measure appended (as a string).
/// </param>
/// <returns type="jQuery" />
var chainable = arguments.length && (defaultExtra || typeof margin !== "boolean"),
extra = defaultExtra || (margin === true || value === true ? "margin" : "border");
return jQuery.access(this, function (elem, type, value) {
var doc;
if (jQuery.isWindow(elem)) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement["client" + name];
}
// Get document width or height
if (elem.nodeType === 9) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body["scroll" + name], doc["scroll" + name],
elem.body["offset" + name], doc["offset" + name],
doc["client" + name]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css(elem, type, extra) :
// Set width or height on the element
jQuery.style(elem, type, value, extra);
}, type, chainable ? margin : undefined, chainable, null);
};
jQuery.prototype.hide = function (speed, easing, callback) {
/// <summary>
/// Hide the matched elements.
/// 1 - hide()
/// 2 - hide(duration, complete)
/// 3 - hide(options)
/// 4 - hide(duration, easing, complete)
/// </summary>
/// <param name="speed" type="">
/// A string or number determining how long the animation will run.
/// </param>
/// <param name="easing" type="String">
/// A string indicating which easing function to use for the transition.
/// </param>
/// <param name="callback" type="Function">
/// A function to call once the animation is complete.
/// </param>
/// <returns type="jQuery" />
return speed == null || typeof speed === "boolean" ?
cssFn.apply(this, arguments) :
this.animate(genFx(name, true), speed, easing, callback);
};
jQuery.prototype.hover = function (fnOver, fnOut) {
/// <summary>
/// 1: Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.
/// 1.1 - hover(handlerIn(eventObject), handlerOut(eventObject))
/// 2: Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements.
/// 2.1 - hover(handlerInOut(eventObject))
/// </summary>
/// <param name="fnOver" type="Function">
/// A function to execute when the mouse pointer enters the element.
/// </param>
/// <param name="fnOut" type="Function">
/// A function to execute when the mouse pointer leaves the element.
/// </param>
/// <returns type="jQuery" />
return this.mouseenter(fnOver).mouseleave(fnOut || fnOver);
};
jQuery.prototype.html = function (value) {
/// <summary>
/// 1: Get the HTML contents of the first element in the set of matched elements.
/// 1.1 - html()
/// 2: Set the HTML contents of each element in the set of matched elements.
/// 2.1 - html(htmlString)
/// 2.2 - html(function(index, oldhtml))
/// </summary>
/// <param name="value" type="String">
/// A string of HTML to set as the content of each matched element.
/// </param>
/// <returns type="jQuery" />
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(getAll(elem, false));
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);
};
jQuery.prototype.index = function (elem) {
/// <summary>
/// Search for a given element from among the matched elements.
/// 1 - index()
/// 2 - index(selector)
/// 3 - index(element)
/// </summary>
/// <param name="elem" type="String">
/// A selector representing a jQuery collection in which to look for an element.
/// </param>
/// <returns type="Number" />
// No argument, return index in parent
if (!elem) {
return (this[0] && this[0].parentNode) ? this.first().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);
};
jQuery.prototype.init = function (selector, context, rootjQuery) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if (!selector) {
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;
// scripts is true for back-compat
jQuery.merge(this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
));
// HANDLE: $(html, props)
if (rsingleTag.test(match[1]) && jQuery.isPlainObject(context)) {
for (match in context) {
// Properties of context are called as methods if possible
if (jQuery.isFunction(this[match])) {
this[match](context[match]);
// ...and otherwise set as attributes
} else {
this.attr(match, context[match]);
}
}
}
return this;
// 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: $(DOMElement)
} else if (selector.nodeType) {
this.context = this[0] = selector;
this.length = 1;
return this;
// 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);
};
jQuery.prototype.innerHeight = function (margin, value) {
/// <summary>
/// Get the current computed height for the first element in the set of matched elements, including padding but not border.
/// </summary>
/// <returns type="Number" />
var chainable = arguments.length && (defaultExtra || typeof margin !== "boolean"),
extra = defaultExtra || (margin === true || value === true ? "margin" : "border");
return jQuery.access(this, function (elem, type, value) {
var doc;
if (jQuery.isWindow(elem)) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement["client" + name];
}
// Get document width or height
if (elem.nodeType === 9) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body["scroll" + name], doc["scroll" + name],
elem.body["offset" + name], doc["offset" + name],
doc["client" + name]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css(elem, type, extra) :
// Set width or height on the element
jQuery.style(elem, type, value, extra);
}, type, chainable ? margin : undefined, chainable, null);
};
jQuery.prototype.innerWidth = function (margin, value) {
/// <summary>
/// Get the current computed width for the first element in the set of matched elements, including padding but not border.
/// </summary>
/// <returns type="Number" />
var chainable = arguments.length && (defaultExtra || typeof margin !== "boolean"),
extra = defaultExtra || (margin === true || value === true ? "margin" : "border");
return jQuery.access(this, function (elem, type, value) {
var doc;
if (jQuery.isWindow(elem)) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement["client" + name];
}
// Get document width or height
if (elem.nodeType === 9) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body["scroll" + name], doc["scroll" + name],
elem.body["offset" + name], doc["offset" + name],
doc["client" + name]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css(elem, type, extra) :
// Set width or height on the element
jQuery.style(elem, type, value, extra);
}, type, chainable ? margin : undefined, chainable, null);
};
jQuery.prototype.insertAfter = function (selector) {
/// <summary>
/// Insert every element in the set of matched elements after the target.
/// </summary>
/// <param name="selector" type="jQuery">
/// A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter.
/// </param>
/// <returns type="jQuery" />
var elems,
i = 0,
ret = [],
insert = jQuery(selector),
last = insert.length - 1;
for (; i <= last; i++) {
elems = i === last ? this : this.clone(true);
jQuery(insert[i])[original](elems);
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
core_push.apply(ret, elems.get());
}
return this.pushStack(ret);
};
jQuery.prototype.insertBefore = function (selector) {
/// <summary>
/// Insert every element in the set of matched elements before the target.
/// </summary>
/// <param name="selector" type="jQuery">
/// A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter.
/// </param>
/// <returns type="jQuery" />
var elems,
i = 0,
ret = [],
insert = jQuery(selector),
last = insert.length - 1;
for (; i <= last; i++) {
elems = i === last ? this : this.clone(true);
jQuery(insert[i])[original](elems);
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
core_push.apply(ret, elems.get());
}
return this.pushStack(ret);
};
jQuery.prototype.is = function (selector) {
/// <summary>
/// Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
/// 1 - is(selector)
/// 2 - is(function(index))
/// 3 - is(jQuery object)
/// 4 - is(element)
/// </summary>
/// <param name="selector" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="Boolean" />
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);
};
jQuery.prototype.keydown = function (data, fn) {
/// <summary>
/// Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element.
/// 1 - keydown(handler(eventObject))
/// 2 - keydown(eventData, handler(eventObject))
/// 3 - keydown()
/// </summary>
/// <param name="data" type="PlainObject">
/// An object containing data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return arguments.length > 0 ?
this.on(name, null, data, fn) :
this.trigger(name);
};
jQuery.prototype.keypress = function (data, fn) {
/// <summary>
/// Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element.
/// 1 - keypress(handler(eventObject))
/// 2 - keypress(eventData, handler(eventObject))
/// 3 - keypress()
/// </summary>
/// <param name="data" type="PlainObject">
/// An object containing data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return arguments.length > 0 ?
this.on(name, null, data, fn) :
this.trigger(name);
};
jQuery.prototype.keyup = function (data, fn) {
/// <summary>
/// Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element.
/// 1 - keyup(handler(eventObject))
/// 2 - keyup(eventData, handler(eventObject))
/// 3 - keyup()
/// </summary>
/// <param name="data" type="PlainObject">
/// An object containing data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return arguments.length > 0 ?
this.on(name, null, data, fn) :
this.trigger(name);
};
jQuery.prototype.last = function () {
/// <summary>
/// Reduce the set of matched elements to the final one in the set.
/// </summary>
/// <returns type="jQuery" />
return this.eq(-1);
};
jQuery.prototype.length = 0;
jQuery.prototype.load = function (url, params, callback) {
/// <summary>
/// 1: Bind an event handler to the "load" JavaScript event.
/// 1.1 - load(handler(eventObject))
/// 1.2 - load(eventData, handler(eventObject))
/// 2: Load data from the server and place the returned HTML into the matched element.
/// 2.1 - load(url, data, complete(responseText, textStatus, XMLHttpRequest))
/// </summary>
/// <param name="url" type="String">
/// A string containing the URL to which the request is sent.
/// </param>
/// <param name="params" type="String">
/// A plain object or string that is sent to the server with the request.
/// </param>
/// <param name="callback" type="Function">
/// A callback function that is executed when the request completes.
/// </param>
/// <returns type="jQuery" />
if (typeof url !== "string" && _load) {
return _load.apply(this, arguments);
}
var selector, response, type,
self = this,
off = url.indexOf(" ");
if (off >= 0) {
selector = url.slice(off, url.length);
url = url.slice(0, off);
}
// If it's a function
if (jQuery.isFunction(params)) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if (params && typeof params === "object") {
type = "POST";
}
// If we have elements to modify, make the request
if (self.length > 0) {
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params
}).done(function (responseText) {
// Save response for use in complete callback
response = arguments;
self.html(selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append(jQuery.parseHTML(responseText)).find(selector) :
// Otherwise use the full result
responseText);
}).complete(callback && function (jqXHR, status) {
self.each(callback, response || [jqXHR.responseText, status, jqXHR]);
});
}
return this;
};
jQuery.prototype.map = function (callback) {
/// <summary>
/// Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.
/// </summary>
/// <param name="callback" type="Function">
/// A function object that will be invoked for each element in the current set.
/// </param>
/// <returns type="jQuery" />
return this.pushStack(jQuery.map(this, function (elem, i) {
return callback.call(elem, i, elem);
}));
};
jQuery.prototype.mousedown = function (data, fn) {
/// <summary>
/// Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element.
/// 1 - mousedown(handler(eventObject))
/// 2 - mousedown(eventData, handler(eventObject))
/// 3 - mousedown()
/// </summary>
/// <param name="data" type="PlainObject">
/// An object containing data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return arguments.length > 0 ?
this.on(name, null, data, fn) :
this.trigger(name);
};
jQuery.prototype.mouseenter = function (data, fn) {
/// <summary>
/// Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.
/// 1 - mouseenter(handler(eventObject))
/// 2 - mouseenter(eventData, handler(eventObject))
/// 3 - mouseenter()
/// </summary>
/// <param name="data" type="PlainObject">
/// An object containing data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return arguments.length > 0 ?
this.on(name, null, data, fn) :
this.trigger(name);
};
jQuery.prototype.mouseleave = function (data, fn) {
/// <summary>
/// Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element.
/// 1 - mouseleave(handler(eventObject))
/// 2 - mouseleave(eventData, handler(eventObject))
/// 3 - mouseleave()
/// </summary>
/// <param name="data" type="PlainObject">
/// An object containing data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return arguments.length > 0 ?
this.on(name, null, data, fn) :
this.trigger(name);
};
jQuery.prototype.mousemove = function (data, fn) {
/// <summary>
/// Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element.
/// 1 - mousemove(handler(eventObject))
/// 2 - mousemove(eventData, handler(eventObject))
/// 3 - mousemove()
/// </summary>
/// <param name="data" type="PlainObject">
/// An object containing data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return arguments.length > 0 ?
this.on(name, null, data, fn) :
this.trigger(name);
};
jQuery.prototype.mouseout = function (data, fn) {
/// <summary>
/// Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element.
/// 1 - mouseout(handler(eventObject))
/// 2 - mouseout(eventData, handler(eventObject))
/// 3 - mouseout()
/// </summary>
/// <param name="data" type="PlainObject">
/// An object containing data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return arguments.length > 0 ?
this.on(name, null, data, fn) :
this.trigger(name);
};
jQuery.prototype.mouseover = function (data, fn) {
/// <summary>
/// Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.
/// 1 - mouseover(handler(eventObject))
/// 2 - mouseover(eventData, handler(eventObject))
/// 3 - mouseover()
/// </summary>
/// <param name="data" type="PlainObject">
/// An object containing data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return arguments.length > 0 ?
this.on(name, null, data, fn) :
this.trigger(name);
};
jQuery.prototype.mouseup = function (data, fn) {
/// <summary>
/// Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element.
/// 1 - mouseup(handler(eventObject))
/// 2 - mouseup(eventData, handler(eventObject))
/// 3 - mouseup()
/// </summary>
/// <param name="data" type="PlainObject">
/// An object containing data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return arguments.length > 0 ?
this.on(name, null, data, fn) :
this.trigger(name);
};
jQuery.prototype.next = function (until, selector) {
/// <summary>
/// Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
/// </summary>
/// <param name="until" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="jQuery" />
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);
};
jQuery.prototype.nextAll = function (until, selector) {
/// <summary>
/// Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.
/// </summary>
/// <param name="until" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="jQuery" />
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);
};
jQuery.prototype.nextUntil = function (until, selector) {
/// <summary>
/// Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed.
/// 1 - nextUntil(selector, filter)
/// 2 - nextUntil(element, filter)
/// </summary>
/// <param name="until" type="String">
/// A string containing a selector expression to indicate where to stop matching following sibling elements.
/// </param>
/// <param name="selector" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="jQuery" />
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);
};
jQuery.prototype.not = function (selector) {
/// <summary>
/// Remove elements from the set of matched elements.
/// 1 - not(selector)
/// 2 - not(elements)
/// 3 - not(function(index))
/// 4 - not(jQuery object)
/// </summary>
/// <param name="selector" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="jQuery" />
return this.pushStack(winnow(this, selector, false));
};
jQuery.prototype.off = function (types, selector, fn) {
/// <summary>
/// Remove an event handler.
/// 1 - off(events, selector, handler(eventObject))
/// 2 - off(events, selector)
/// </summary>
/// <param name="types" type="String">
/// One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin".
/// </param>
/// <param name="selector" type="String">
/// A selector which should match the one originally passed to .on() when attaching event handlers.
/// </param>
/// <param name="fn" type="Function">
/// A handler function previously attached for the event(s), or the special value false.
/// </param>
/// <returns type="jQuery" />
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);
});
};
jQuery.prototype.offset = function (options) {
/// <summary>
/// 1: Get the current coordinates of the first element in the set of matched elements, relative to the document.
/// 1.1 - offset()
/// 2: Set the current coordinates of every element in the set of matched elements, relative to the document.
/// 2.1 - offset(coordinates)
/// 2.2 - offset(function(index, coords))
/// </summary>
/// <param name="options" type="PlainObject">
/// An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements.
/// </param>
/// <returns type="jQuery" />
if (arguments.length) {
return options === undefined ?
this :
this.each(function (i) {
jQuery.offset.setOffset(this, options, i);
});
}
var docElem, win,
box = { top: 0, left: 0 },
elem = this[0],
doc = elem && elem.ownerDocument;
if (!doc) {
return;
}
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 !== core_strundefined) {
box = elem.getBoundingClientRect();
}
win = getWindow(doc);
return {
top: box.top + (win.pageYOffset || docElem.scrollTop) - (docElem.clientTop || 0),
left: box.left + (win.pageXOffset || docElem.scrollLeft) - (docElem.clientLeft || 0)
};
};
jQuery.prototype.offsetParent = function () {
/// <summary>
/// Get the closest ancestor element that is positioned.
/// </summary>
/// <returns type="jQuery" />
return this.map(function () {
var offsetParent = this.offsetParent || document.documentElement;
while (offsetParent && (!jQuery.nodeName(offsetParent, "html") && jQuery.css(offsetParent, "position") === "static")) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || document.documentElement;
});
};
jQuery.prototype.on = function (types, selector, data, fn, /*INTERNAL*/ one) {
/// <summary>
/// Attach an event handler function for one or more events to the selected elements.
/// 1 - on(events, selector, data, handler(eventObject))
/// 2 - on(events, selector, data)
/// </summary>
/// <param name="types" type="String">
/// One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".
/// </param>
/// <param name="selector" type="String">
/// A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.
/// </param>
/// <param name="data" type="Anything">
/// Data to be passed to the handler in event.data when an event is triggered.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false.
/// </param>
/// <returns type="jQuery" />
var type, origFn;
// Types can be a map of types/handlers
if (typeof types === "object") {
// ( types-Object, selector, data )
if (typeof selector !== "string") {
// ( 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);
});
};
jQuery.prototype.one = function (types, selector, data, fn) {
/// <summary>
/// Attach a handler to an event for the elements. The handler is executed at most once per element.
/// 1 - one(events, data, handler(eventObject))
/// 2 - one(events, selector, data, handler(eventObject))
/// 3 - one(events, selector, data)
/// </summary>
/// <param name="types" type="String">
/// One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".
/// </param>
/// <param name="selector" type="String">
/// A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.
/// </param>
/// <param name="data" type="Anything">
/// Data to be passed to the handler in event.data when an event is triggered.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false.
/// </param>
/// <returns type="jQuery" />
return this.on(types, selector, data, fn, 1);
};
jQuery.prototype.outerHeight = function (margin, value) {
/// <summary>
/// Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin. Returns an integer (without "px") representation of the value or null if called on an empty set of elements.
/// </summary>
/// <param name="margin" type="Boolean">
/// A Boolean indicating whether to include the element's margin in the calculation.
/// </param>
/// <returns type="Number" />
var chainable = arguments.length && (defaultExtra || typeof margin !== "boolean"),
extra = defaultExtra || (margin === true || value === true ? "margin" : "border");
return jQuery.access(this, function (elem, type, value) {
var doc;
if (jQuery.isWindow(elem)) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement["client" + name];
}
// Get document width or height
if (elem.nodeType === 9) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body["scroll" + name], doc["scroll" + name],
elem.body["offset" + name], doc["offset" + name],
doc["client" + name]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css(elem, type, extra) :
// Set width or height on the element
jQuery.style(elem, type, value, extra);
}, type, chainable ? margin : undefined, chainable, null);
};
jQuery.prototype.outerWidth = function (margin, value) {
/// <summary>
/// Get the current computed width for the first element in the set of matched elements, including padding and border.
/// </summary>
/// <param name="margin" type="Boolean">
/// A Boolean indicating whether to include the element's margin in the calculation.
/// </param>
/// <returns type="Number" />
var chainable = arguments.length && (defaultExtra || typeof margin !== "boolean"),
extra = defaultExtra || (margin === true || value === true ? "margin" : "border");
return jQuery.access(this, function (elem, type, value) {
var doc;
if (jQuery.isWindow(elem)) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement["client" + name];
}
// Get document width or height
if (elem.nodeType === 9) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body["scroll" + name], doc["scroll" + name],
elem.body["offset" + name], doc["offset" + name],
doc["client" + name]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css(elem, type, extra) :
// Set width or height on the element
jQuery.style(elem, type, value, extra);
}, type, chainable ? margin : undefined, chainable, null);
};
jQuery.prototype.parent = function (until, selector) {
/// <summary>
/// Get the parent of each element in the current set of matched elements, optionally filtered by a selector.
/// </summary>
/// <param name="until" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="jQuery" />
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);
};
jQuery.prototype.parents = function (until, selector) {
/// <summary>
/// Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.
/// </summary>
/// <param name="until" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="jQuery" />
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);
};
jQuery.prototype.parentsUntil = function (until, selector) {
/// <summary>
/// Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object.
/// 1 - parentsUntil(selector, filter)
/// 2 - parentsUntil(element, filter)
/// </summary>
/// <param name="until" type="String">
/// A string containing a selector expression to indicate where to stop matching ancestor elements.
/// </param>
/// <param name="selector" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="jQuery" />
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);
};
jQuery.prototype.position = function () {
/// <summary>
/// Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.
/// </summary>
/// <returns type="Object" />
if (!this[0]) {
return;
}
var offsetParent, offset,
parentOffset = { top: 0, left: 0 },
elem = this[0];
// fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent
if (jQuery.css(elem, "position") === "fixed") {
// we assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if (!jQuery.nodeName(offsetParent[0], "html")) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css(offsetParent[0], "borderTopWidth", true);
parentOffset.left += jQuery.css(offsetParent[0], "borderLeftWidth", true);
}
// Subtract parent offsets and 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
return {
top: offset.top - parentOffset.top - jQuery.css(elem, "marginTop", true),
left: offset.left - parentOffset.left - jQuery.css(elem, "marginLeft", true)
};
};
jQuery.prototype.prepend = function () {
/// <summary>
/// Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.
/// 1 - prepend(content, content)
/// 2 - prepend(function(index, html))
/// </summary>
/// <param name="" type="jQuery">
/// DOM element, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements.
/// </param>
/// <param name="" type="jQuery">
/// One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the beginning of each element in the set of matched elements.
/// </param>
/// <returns type="jQuery" />
return this.domManip(arguments, true, function (elem) {
if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) {
this.insertBefore(elem, this.firstChild);
}
});
};
jQuery.prototype.prependTo = function (selector) {
/// <summary>
/// Insert every element in the set of matched elements to the beginning of the target.
/// </summary>
/// <param name="selector" type="jQuery">
/// A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter.
/// </param>
/// <returns type="jQuery" />
var elems,
i = 0,
ret = [],
insert = jQuery(selector),
last = insert.length - 1;
for (; i <= last; i++) {
elems = i === last ? this : this.clone(true);
jQuery(insert[i])[original](elems);
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
core_push.apply(ret, elems.get());
}
return this.pushStack(ret);
};
jQuery.prototype.prev = function (until, selector) {
/// <summary>
/// Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.
/// </summary>
/// <param name="until" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="jQuery" />
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);
};
jQuery.prototype.prevAll = function (until, selector) {
/// <summary>
/// Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector.
/// </summary>
/// <param name="until" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="jQuery" />
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);
};
jQuery.prototype.prevUntil = function (until, selector) {
/// <summary>
/// Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object.
/// 1 - prevUntil(selector, filter)
/// 2 - prevUntil(element, filter)
/// </summary>
/// <param name="until" type="String">
/// A string containing a selector expression to indicate where to stop matching preceding sibling elements.
/// </param>
/// <param name="selector" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="jQuery" />
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);
};
jQuery.prototype.promise = function (type, obj) {
/// <summary>
/// Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished.
/// </summary>
/// <param name="type" type="String">
/// The type of queue that needs to be observed.
/// </param>
/// <param name="obj" type="PlainObject">
/// Object onto which the promise methods have to be attached
/// </param>
/// <returns type="Promise" />
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);
};
jQuery.prototype.prop = function (name, value) {
/// <summary>
/// 1: Get the value of a property for the first element in the set of matched elements.
/// 1.1 - prop(propertyName)
/// 2: Set one or more properties for the set of matched elements.
/// 2.1 - prop(propertyName, value)
/// 2.2 - prop(properties)
/// 2.3 - prop(propertyName, function(index, oldPropertyValue))
/// </summary>
/// <param name="name" type="String">
/// The name of the property to set.
/// </param>
/// <param name="value" type="Boolean">
/// A value to set for the property.
/// </param>
/// <returns type="jQuery" />
return jQuery.access(this, jQuery.prop, name, value, arguments.length > 1);
};
jQuery.prototype.pushStack = function (elems) {
/// <summary>
/// Add a collection of DOM elements onto the jQuery stack.
/// 1 - pushStack(elements)
/// 2 - pushStack(elements, name, arguments)
/// </summary>
/// <param name="elems" type="Array">
/// An array of elements to push onto the stack and make into a new jQuery object.
/// </param>
/// <param name="" type="String">
/// The name of a jQuery method that generated the array of elements.
/// </param>
/// <param name="" type="Array">
/// The arguments that were passed in to the jQuery method (for serialization).
/// </param>
/// <returns type="jQuery" />
// 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;
// Return the newly-formed element set
return ret;
};
jQuery.prototype.queue = function (type, data) {
/// <summary>
/// 1: Show the queue of functions to be executed on the matched elements.
/// 1.1 - queue(queueName)
/// 2: Manipulate the queue of functions to be executed, once for each matched element.
/// 2.1 - queue(queueName, newQueue)
/// 2.2 - queue(queueName, callback( next ))
/// </summary>
/// <param name="type" type="String">
/// A string containing the name of the queue. Defaults to fx, the standard effects queue.
/// </param>
/// <param name="data" type="Array">
/// An array of functions to replace the current queue contents.
/// </param>
/// <returns type="jQuery" />
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);
}
});
};
jQuery.prototype.ready = function (fn) {
/// <summary>
/// Specify a function to execute when the DOM is fully loaded.
/// </summary>
/// <param name="fn" type="Function">
/// A function to execute after the DOM is ready.
/// </param>
/// <returns type="jQuery" />
// Add the callback
jQuery.ready.promise().done(fn);
return this;
};
jQuery.prototype.remove = function (selector, keepData) {
/// <summary>
/// Remove the set of matched elements from the DOM.
/// </summary>
/// <param name="selector" type="String">
/// A selector expression that filters the set of matched elements to be removed.
/// </param>
/// <returns type="jQuery" />
var elem,
i = 0;
for (; (elem = this[i]) != null; i++) {
if (!selector || jQuery.filter(selector, [elem]).length > 0) {
if (!keepData && elem.nodeType === 1) {
jQuery.cleanData(getAll(elem));
}
if (elem.parentNode) {
if (keepData && jQuery.contains(elem.ownerDocument, elem)) {
setGlobalEval(getAll(elem, "script"));
}
elem.parentNode.removeChild(elem);
}
}
}
return this;
};
jQuery.prototype.removeAttr = function (name) {
/// <summary>
/// Remove an attribute from each element in the set of matched elements.
/// </summary>
/// <param name="name" type="String">
/// An attribute to remove; as of version 1.7, it can be a space-separated list of attributes.
/// </param>
/// <returns type="jQuery" />
return this.each(function () {
jQuery.removeAttr(this, name);
});
};
jQuery.prototype.removeClass = function (value) {
/// <summary>
/// Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
/// 1 - removeClass(className)
/// 2 - removeClass(function(index, class))
/// </summary>
/// <param name="value" type="String">
/// One or more space-separated classes to be removed from the class attribute of each matched element.
/// </param>
/// <returns type="jQuery" />
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if (jQuery.isFunction(value)) {
return this.each(function (j) {
jQuery(this).removeClass(value.call(this, j, this.className));
});
}
if (proceed) {
classes = (value || "").match(core_rnotwhite) || [];
for (; i < len; i++) {
elem = this[i];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && (elem.className ?
(" " + elem.className + " ").replace(rclass, " ") :
""
);
if (cur) {
j = 0;
while ((clazz = classes[j++])) {
// Remove *all* instances
while (cur.indexOf(" " + clazz + " ") >= 0) {
cur = cur.replace(" " + clazz + " ", " ");
}
}
elem.className = value ? jQuery.trim(cur) : "";
}
}
}
return this;
};
jQuery.prototype.removeData = function (key) {
/// <summary>
/// Remove a previously-stored piece of data.
/// 1 - removeData(name)
/// 2 - removeData(list)
/// </summary>
/// <param name="key" type="String">
/// A string naming the piece of data to delete.
/// </param>
/// <returns type="jQuery" />
return this.each(function () {
jQuery.removeData(this, key);
});
};
jQuery.prototype.removeProp = function (name) {
/// <summary>
/// Remove a property for the set of matched elements.
/// </summary>
/// <param name="name" type="String">
/// The name of the property to remove.
/// </param>
/// <returns type="jQuery" />
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) { }
});
};
jQuery.prototype.replaceAll = function (selector) {
/// <summary>
/// Replace each target element with the set of matched elements.
/// </summary>
/// <param name="selector" type="String">
/// A selector expression indicating which element(s) to replace.
/// </param>
/// <returns type="jQuery" />
var elems,
i = 0,
ret = [],
insert = jQuery(selector),
last = insert.length - 1;
for (; i <= last; i++) {
elems = i === last ? this : this.clone(true);
jQuery(insert[i])[original](elems);
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
core_push.apply(ret, elems.get());
}
return this.pushStack(ret);
};
jQuery.prototype.replaceWith = function (value) {
/// <summary>
/// Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed.
/// 1 - replaceWith(newContent)
/// 2 - replaceWith(function)
/// </summary>
/// <param name="value" type="jQuery">
/// The content to insert. May be an HTML string, DOM element, or jQuery object.
/// </param>
/// <returns type="jQuery" />
var isFunc = jQuery.isFunction(value);
// 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 (!isFunc && typeof value !== "string") {
value = jQuery(value).not(this).detach();
}
return this.domManip([value], true, function (elem) {
var next = this.nextSibling,
parent = this.parentNode;
if (parent) {
jQuery(this).remove();
parent.insertBefore(elem, next);
}
});
};
jQuery.prototype.resize = function (data, fn) {
/// <summary>
/// Bind an event handler to the "resize" JavaScript event, or trigger that event on an element.
/// 1 - resize(handler(eventObject))
/// 2 - resize(eventData, handler(eventObject))
/// 3 - resize()
/// </summary>
/// <param name="data" type="PlainObject">
/// An object containing data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return arguments.length > 0 ?
this.on(name, null, data, fn) :
this.trigger(name);
};
jQuery.prototype.scroll = function (data, fn) {
/// <summary>
/// Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element.
/// 1 - scroll(handler(eventObject))
/// 2 - scroll(eventData, handler(eventObject))
/// 3 - scroll()
/// </summary>
/// <param name="data" type="PlainObject">
/// An object containing data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return arguments.length > 0 ?
this.on(name, null, data, fn) :
this.trigger(name);
};
jQuery.prototype.scrollLeft = function (val) {
/// <summary>
/// 1: Get the current horizontal position of the scroll bar for the first element in the set of matched elements.
/// 1.1 - scrollLeft()
/// 2: Set the current horizontal position of the scroll bar for each of the set of matched elements.
/// 2.1 - scrollLeft(value)
/// </summary>
/// <param name="val" type="Number">
/// An integer indicating the new position to set the scroll bar to.
/// </param>
/// <returns type="jQuery" />
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);
};
jQuery.prototype.scrollTop = function (val) {
/// <summary>
/// 1: Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element.
/// 1.1 - scrollTop()
/// 2: Set the current vertical position of the scroll bar for each of the set of matched elements.
/// 2.1 - scrollTop(value)
/// </summary>
/// <param name="val" type="Number">
/// An integer indicating the new position to set the scroll bar to.
/// </param>
/// <returns type="jQuery" />
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);
};
jQuery.prototype.select = function (data, fn) {
/// <summary>
/// Bind an event handler to the "select" JavaScript event, or trigger that event on an element.
/// 1 - select(handler(eventObject))
/// 2 - select(eventData, handler(eventObject))
/// 3 - select()
/// </summary>
/// <param name="data" type="PlainObject">
/// An object containing data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return arguments.length > 0 ?
this.on(name, null, data, fn) :
this.trigger(name);
};
jQuery.prototype.serialize = function () {
/// <summary>
/// Encode a set of form elements as a string for submission.
/// </summary>
/// <returns type="String" />
return jQuery.param(this.serializeArray());
};
jQuery.prototype.serializeArray = function () {
/// <summary>
/// Encode a set of form elements as an array of names and values.
/// </summary>
/// <returns type="Array" />
return this.map(function () {
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop(this, "elements");
return elements ? jQuery.makeArray(elements) : this;
})
.filter(function () {
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !jQuery(this).is(":disabled") &&
rsubmittable.test(this.nodeName) && !rsubmitterTypes.test(type) &&
(this.checked || !manipulation_rcheckableType.test(type));
})
.map(function (i, elem) {
var val = jQuery(this).val();
return val == null ?
null :
jQuery.isArray(val) ?
jQuery.map(val, function (val) {
return { name: elem.name, value: val.replace(rCRLF, "\r\n") };
}) :
{ name: elem.name, value: val.replace(rCRLF, "\r\n") };
}).get();
};
jQuery.prototype.show = function (speed, easing, callback) {
/// <summary>
/// Display the matched elements.
/// 1 - show()
/// 2 - show(duration, complete)
/// 3 - show(options)
/// 4 - show(duration, easing, complete)
/// </summary>
/// <param name="speed" type="">
/// A string or number determining how long the animation will run.
/// </param>
/// <param name="easing" type="String">
/// A string indicating which easing function to use for the transition.
/// </param>
/// <param name="callback" type="Function">
/// A function to call once the animation is complete.
/// </param>
/// <returns type="jQuery" />
return speed == null || typeof speed === "boolean" ?
cssFn.apply(this, arguments) :
this.animate(genFx(name, true), speed, easing, callback);
};
jQuery.prototype.siblings = function (until, selector) {
/// <summary>
/// Get the siblings of each element in the set of matched elements, optionally filtered by a selector.
/// </summary>
/// <param name="until" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="jQuery" />
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);
};
jQuery.prototype.size = function () {
/// <summary>
/// Return the number of elements in the jQuery object.
/// </summary>
/// <returns type="Number" />
return this.length;
};
jQuery.prototype.slice = function () {
/// <summary>
/// Reduce the set of matched elements to a subset specified by a range of indices.
/// </summary>
/// <param name="" type="Number">
/// An integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set.
/// </param>
/// <param name="" type="Number">
/// An integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from the end of the set. If omitted, the range continues until the end of the set.
/// </param>
/// <returns type="jQuery" />
return this.pushStack(core_slice.apply(this, arguments));
};
jQuery.prototype.slideDown = function (speed, easing, callback) {
/// <summary>
/// Display the matched elements with a sliding motion.
/// 1 - slideDown(duration, complete)
/// 2 - slideDown(options)
/// 3 - slideDown(duration, easing, complete)
/// </summary>
/// <param name="speed" type="">
/// A string or number determining how long the animation will run.
/// </param>
/// <param name="easing" type="String">
/// A string indicating which easing function to use for the transition.
/// </param>
/// <param name="callback" type="Function">
/// A function to call once the animation is complete.
/// </param>
/// <returns type="jQuery" />
return this.animate(props, speed, easing, callback);
};
jQuery.prototype.slideToggle = function (speed, easing, callback) {
/// <summary>
/// Display or hide the matched elements with a sliding motion.
/// 1 - slideToggle(duration, complete)
/// 2 - slideToggle(options)
/// 3 - slideToggle(duration, easing, complete)
/// </summary>
/// <param name="speed" type="">
/// A string or number determining how long the animation will run.
/// </param>
/// <param name="easing" type="String">
/// A string indicating which easing function to use for the transition.
/// </param>
/// <param name="callback" type="Function">
/// A function to call once the animation is complete.
/// </param>
/// <returns type="jQuery" />
return this.animate(props, speed, easing, callback);
};
jQuery.prototype.slideUp = function (speed, easing, callback) {
/// <summary>
/// Hide the matched elements with a sliding motion.
/// 1 - slideUp(duration, complete)
/// 2 - slideUp(options)
/// 3 - slideUp(duration, easing, complete)
/// </summary>
/// <param name="speed" type="">
/// A string or number determining how long the animation will run.
/// </param>
/// <param name="easing" type="String">
/// A string indicating which easing function to use for the transition.
/// </param>
/// <param name="callback" type="Function">
/// A function to call once the animation is complete.
/// </param>
/// <returns type="jQuery" />
return this.animate(props, speed, easing, callback);
};
jQuery.prototype.stop = function (type, clearQueue, gotoEnd) {
/// <summary>
/// Stop the currently-running animation on the matched elements.
/// 1 - stop(clearQueue, jumpToEnd)
/// 2 - stop(queue, clearQueue, jumpToEnd)
/// </summary>
/// <param name="type" type="String">
/// The name of the queue in which to stop animations.
/// </param>
/// <param name="clearQueue" type="Boolean">
/// A Boolean indicating whether to remove queued animation as well. Defaults to false.
/// </param>
/// <param name="gotoEnd" type="Boolean">
/// A Boolean indicating whether to complete the current animation immediately. Defaults to false.
/// </param>
/// <returns type="jQuery" />
var stopQueue = function (hooks) {
var stop = hooks.stop;
delete hooks.stop;
stop(gotoEnd);
};
if (typeof type !== "string") {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if (clearQueue && type !== false) {
this.queue(type || "fx", []);
}
return this.each(function () {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data(this);
if (index) {
if (data[index] && data[index].stop) {
stopQueue(data[index]);
}
} else {
for (index in data) {
if (data[index] && data[index].stop && rrun.test(index)) {
stopQueue(data[index]);
}
}
}
for (index = timers.length; index--;) {
if (timers[index].elem === this && (type == null || timers[index].queue === type)) {
timers[index].anim.stop(gotoEnd);
dequeue = false;
timers.splice(index, 1);
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if (dequeue || !gotoEnd) {
jQuery.dequeue(this, type);
}
});
};
jQuery.prototype.submit = function (data, fn) {
/// <summary>
/// Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.
/// 1 - submit(handler(eventObject))
/// 2 - submit(eventData, handler(eventObject))
/// 3 - submit()
/// </summary>
/// <param name="data" type="PlainObject">
/// An object containing data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return arguments.length > 0 ?
this.on(name, null, data, fn) :
this.trigger(name);
};
jQuery.prototype.text = function (value) {
/// <summary>
/// 1: Get the combined text contents of each element in the set of matched elements, including their descendants.
/// 1.1 - text()
/// 2: Set the content of each element in the set of matched elements to the specified text.
/// 2.1 - text(textString)
/// 2.2 - text(function(index, text))
/// </summary>
/// <param name="value" type="String">
/// A string of text to set as the content of each matched element.
/// </param>
/// <returns type="jQuery" />
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);
};
jQuery.prototype.toArray = function () {
/// <summary>
/// Retrieve all the DOM elements contained in the jQuery set, as an array.
/// </summary>
/// <returns type="Array" />
return core_slice.call(this);
};
jQuery.prototype.toggle = function (speed, easing, callback) {
/// <summary>
/// 1: Bind two or more handlers to the matched elements, to be executed on alternate clicks.
/// 1.1 - toggle(handler(eventObject), handler(eventObject), handler(eventObject))
/// 2: Display or hide the matched elements.
/// 2.1 - toggle(duration, complete)
/// 2.2 - toggle(options)
/// 2.3 - toggle(duration, easing, complete)
/// 2.4 - toggle(showOrHide)
/// </summary>
/// <param name="speed" type="Function">
/// A function to execute every even time the element is clicked.
/// </param>
/// <param name="easing" type="Function">
/// A function to execute every odd time the element is clicked.
/// </param>
/// <param name="callback" type="Function">
/// Additional handlers to cycle through after clicks.
/// </param>
/// <returns type="jQuery" />
return speed == null || typeof speed === "boolean" ?
cssFn.apply(this, arguments) :
this.animate(genFx(name, true), speed, easing, callback);
};
jQuery.prototype.toggleClass = function (value, stateVal) {
/// <summary>
/// Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.
/// 1 - toggleClass(className)
/// 2 - toggleClass(className, switch)
/// 3 - toggleClass(switch)
/// 4 - toggleClass(function(index, class, switch), switch)
/// </summary>
/// <param name="value" type="String">
/// One or more class names (separated by spaces) to be toggled for each element in the matched set.
/// </param>
/// <param name="stateVal" type="Boolean">
/// A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed.
/// </param>
/// <returns type="jQuery" />
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.match(core_rnotwhite) || [];
while ((className = classNames[i++])) {
// check each className given, space separated list
state = isBool ? state : !self.hasClass(className);
self[state ? "addClass" : "removeClass"](className);
}
// Toggle whole class name
} else if (type === core_strundefined || type === "boolean") {
if (this.className) {
// store className if set
jQuery._data(this, "__className__", this.className);
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : jQuery._data(this, "__className__") || "";
}
});
};
jQuery.prototype.trigger = function (type, data) {
/// <summary>
/// Execute all handlers and behaviors attached to the matched elements for the given event type.
/// 1 - trigger(eventType, extraParameters)
/// 2 - trigger(event)
/// </summary>
/// <param name="type" type="String">
/// A string containing a JavaScript event type, such as click or submit.
/// </param>
/// <param name="data" type="PlainObject">
/// Additional parameters to pass along to the event handler.
/// </param>
/// <returns type="jQuery" />
return this.each(function () {
jQuery.event.trigger(type, data, this);
});
};
jQuery.prototype.triggerHandler = function (type, data) {
/// <summary>
/// Execute all handlers attached to an element for an event.
/// </summary>
/// <param name="type" type="String">
/// A string containing a JavaScript event type, such as click or submit.
/// </param>
/// <param name="data" type="Array">
/// An array of additional parameters to pass along to the event handler.
/// </param>
/// <returns type="Object" />
var elem = this[0];
if (elem) {
return jQuery.event.trigger(type, data, elem, true);
}
};
jQuery.prototype.unbind = function (types, fn) {
/// <summary>
/// Remove a previously-attached event handler from the elements.
/// 1 - unbind(eventType, handler(eventObject))
/// 2 - unbind(eventType, false)
/// 3 - unbind(event)
/// </summary>
/// <param name="types" type="String">
/// A string containing a JavaScript event type, such as click or submit.
/// </param>
/// <param name="fn" type="Function">
/// The function that is to be no longer executed.
/// </param>
/// <returns type="jQuery" />
return this.off(types, null, fn);
};
jQuery.prototype.undelegate = function (selector, types, fn) {
/// <summary>
/// Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements.
/// 1 - undelegate()
/// 2 - undelegate(selector, eventType)
/// 3 - undelegate(selector, eventType, handler(eventObject))
/// 4 - undelegate(selector, events)
/// 5 - undelegate(namespace)
/// </summary>
/// <param name="selector" type="String">
/// A selector which will be used to filter the event results.
/// </param>
/// <param name="types" type="String">
/// A string containing a JavaScript event type, such as "click" or "keydown"
/// </param>
/// <param name="fn" type="Function">
/// A function to execute at the time the event is triggered.
/// </param>
/// <returns type="jQuery" />
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off(selector, "**") : this.off(types, selector || "**", fn);
};
jQuery.prototype.unload = function (data, fn) {
/// <summary>
/// Bind an event handler to the "unload" JavaScript event.
/// 1 - unload(handler(eventObject))
/// 2 - unload(eventData, handler(eventObject))
/// </summary>
/// <param name="data" type="Object">
/// A plain object of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return arguments.length > 0 ?
this.on(name, null, data, fn) :
this.trigger(name);
};
jQuery.prototype.unwrap = function () {
/// <summary>
/// Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.
/// </summary>
/// <returns type="jQuery" />
return this.parent().each(function () {
if (!jQuery.nodeName(this, "body")) {
jQuery(this).replaceWith(this.childNodes);
}
}).end();
};
jQuery.prototype.val = function (value) {
/// <summary>
/// 1: Get the current value of the first element in the set of matched elements.
/// 1.1 - val()
/// 2: Set the value of each element in the set of matched elements.
/// 2.1 - val(value)
/// 2.2 - val(function(index, value))
/// </summary>
/// <param name="value" type="Array">
/// A string of text or an array of strings corresponding to the value of each matched element to set as selected/checked.
/// </param>
/// <returns type="jQuery" />
var ret, hooks, 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.prototype.width = function (margin, value) {
/// <summary>
/// 1: Get the current computed width for the first element in the set of matched elements.
/// 1.1 - width()
/// 2: Set the CSS width of each element in the set of matched elements.
/// 2.1 - width(value)
/// 2.2 - width(function(index, width))
/// </summary>
/// <param name="margin" type="Number">
/// An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string).
/// </param>
/// <returns type="jQuery" />
var chainable = arguments.length && (defaultExtra || typeof margin !== "boolean"),
extra = defaultExtra || (margin === true || value === true ? "margin" : "border");
return jQuery.access(this, function (elem, type, value) {
var doc;
if (jQuery.isWindow(elem)) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement["client" + name];
}
// Get document width or height
if (elem.nodeType === 9) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body["scroll" + name], doc["scroll" + name],
elem.body["offset" + name], doc["offset" + name],
doc["client" + name]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css(elem, type, extra) :
// Set width or height on the element
jQuery.style(elem, type, value, extra);
}, type, chainable ? margin : undefined, chainable, null);
};
jQuery.prototype.wrap = function (html) {
/// <summary>
/// Wrap an HTML structure around each element in the set of matched elements.
/// 1 - wrap(wrappingElement)
/// 2 - wrap(function(index))
/// </summary>
/// <param name="html" type="jQuery">
/// An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the matched elements.
/// </param>
/// <returns type="jQuery" />
var isFunction = jQuery.isFunction(html);
return this.each(function (i) {
jQuery(this).wrapAll(isFunction ? html.call(this, i) : html);
});
};
jQuery.prototype.wrapAll = function (html) {
/// <summary>
/// Wrap an HTML structure around all elements in the set of matched elements.
/// </summary>
/// <param name="html" type="jQuery">
/// An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the matched elements.
/// </param>
/// <returns type="jQuery" />
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;
};
jQuery.prototype.wrapInner = function (html) {
/// <summary>
/// Wrap an HTML structure around the content of each element in the set of matched elements.
/// 1 - wrapInner(wrappingElement)
/// 2 - wrapInner(function(index))
/// </summary>
/// <param name="html" type="String">
/// An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the content of the matched elements.
/// </param>
/// <returns type="jQuery" />
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);
}
});
};
jQuery.fn = jQuery.prototype;
jQuery.fn.init.prototype = jQuery.fn;
window.jQuery = window.$ = jQuery;
})(window); |
var LagerApp = React.createClass({
_loadServersData: function() {
var username = localStorage.getItem('username');
var authToken = localStorage.getItem('auth_token');
$.ajax({
headers: {
'Authorization': 'Basic ' + btoa(username + ':' + authToken)
},
url: "/servers",
dataType: 'json',
cache: true,
success: function(data) {
this.setState({ servers: data });
}.bind(this)
});
},
_loadServicesData: function() {
var username = localStorage.getItem('username');
var authToken = localStorage.getItem('auth_token');
$.ajax({
headers: {
'Authorization': 'Basic ' + btoa(username + ':' + authToken)
},
url: "/services",
dataType: 'json',
cache: true,
success: function(data) {
this.setState({ services: data });
}.bind(this)
});
},
loadServerServiceData: function(server) {
this.setState({
services: server.services
});
},
getInitialState: function() {
var page = "servers";
if (window.location.hash) {
page = window.location.hash.substring(1);
$('header a.pull-right').attr('href', '/' + page + '/new');
} else {
window.location.hash = 'servers';
}
return {
logs: [],
page: page,
services: [],
servers: [],
loggedIn: localStorage.getItem('auth_token') !== ''
};
},
_loadData: function() {
this._loadServersData();
this._loadServicesData();
},
componentWillMount: function() {
$.ajaxSetup({cache: true});
if (localStorage.getItem('auth_token') == undefined) {
localStorage.setItem('auth_token', '');
}
if (localStorage.getItem('username') == undefined) {
localStorage.setItem('username', '');
}
},
componentDidMount: function() {
window.onhashchange = function() {
var hash = window.location.hash.substring(1);
$('header .title').text(function(hash){
if (hash === "servers") {
return "Lager | Servers";
} else if (hash === 'services') {
return "Lager | Services";
} else {
return 'Lager | Settings';
}
}(hash));
$('header a.pull-right').attr('href', '/' + hash + '/new');
this.setState({page: hash});
}.bind(this);
if (this.state.loggedIn) {
this._loadData();
} else {
window.location.hash = 'settings';
}
},
componentDidUpdate: function(prevProps, prevState) {
if (localStorage.getItem('auth_token') === '') {
window.location.hash = 'settings';
}
},
render: function() {
var tableView;
if (this.state.page === "servers") {
$('#settings-tab-item').removeClass('active');
$("#servers-tab-item").addClass("active");
$("#services-tab-item").removeClass("active");
$('header a.pull-right').show();
tableView = <ServerTableView servers={this.state.servers} loadServerServiceData={this.loadServerServiceData} />
} else if (this.state.page === 'services') {
$('#settings-tab-item').removeClass('active');
$("#servers-tab-item").removeClass("active");
$("#services-tab-item").addClass("active");
$('header a.pull-right').show();
tableView = <ServiceTableView services={this.state.services} />
} else if (this.state.page === 'server-services') {
tableView = <ServerServicesTableView services={this.state.services} />
} else {
$('#settings-tab-item').addClass('active');
$("#servers-tab-item").removeClass("active");
$("#services-tab-item").removeClass("active");
$('header a.pull-right').hide();
tableView = <SettingsView loggedIn={this.state.loggedIn} loadData={this._loadData} />;
}
return (
<div>
{tableView}
<div ref="line"></div>
</div>
);
}
});
var ServiceTableView = React.createClass({
_generateServiceTableViewCells: function() {
return this.props.services.map(function(service){
return (<ServiceTableViewCell service={service} key={service.name + service.id} />)
});
},
render: function() {
return (
<div>
<ul className="table-view">
{this._generateServiceTableViewCells()}
</ul>
</div>
);
}
});
var ServiceTableViewCell = React.createClass({
render: function() {
var serverCountLabel = '';
if (this.props.service.servers) {
serverCountLabel = <p>Server count: {this.props.service.servers.length}</p>;
}
console.log(this.props.service);
return (
<li className="table-view-cell">
<a className="navigate-right" data-ignore="push" href={"/logs/service/" + this.props.service.id}>
<div>
<h4>{this.props.service.name}</h4>
<h5>{this.props.service.log_path}</h5>
{serverCountLabel}
</div>
</a>
</li>
);
}
});
var ServerTableView = React.createClass({
_generateServerTableViewCells: function() {
var loadServerServiceData = this.props.loadServerServiceData;
return this.props.servers.map(function(server, idx){
return (<ServerTableViewCell server={server} key={idx} loadServerServiceData={loadServerServiceData} />)
});
},
render: function() {
return (
<div>
<ul className="table-view">
{this._generateServerTableViewCells()}
</ul>
</div>
);
}
});
var ServerTableViewCell = React.createClass({
componentDidMount: function() {
if (localStorage.getItem('auth_token') !== '') {
this._getServerStatus(this.props.server)
}
},
getInitialState: function() {
return {
status: false
};
},
_getServerStatus: function(server) {
var username = localStorage.getItem('username');
var authToken = localStorage.getItem('auth_token');
$.ajax({
url: "/server/" + server.id + "/status",
headers: {
'Authorization': 'Basic ' + btoa(username + ':' + authToken)
},
dataType: 'json',
cache: false,
success: function(data) { this.setState(data) }.bind(this)
});
},
render: function() {
var server = this.props.server;
var statusClass = this.state.status ? "btn btn-positive" : "btn btn-negative";
var status = this.state.status ? "Up" : "Down";
return (
<li className="table-view-cell">
<a className="navigate-right" href="#server-services" onClick={this.props.loadServerServiceData.bind(null, server)}>
<div style={{float: "left"}}>
<h4>{server.host}</h4>
<h5>{server.label}</h5>
</div>
<button className={statusClass} style={{float: "right"}}>
{status}
</button>
</a>
</li>
);
}
});
var ServerServicesTableView = React.createClass({
componentWillMount: function() {
$('.bar-nav').append('<a id="left-nav-button" class="icon icon-left-nav pull-left"></a>');
$('#left-nav-button').on('click', function() {
history.back();
});
},
componentDidMount: function() {
$('header a.pull-right').attr('href', '/services/new');
},
componentWillUnmount: function() {
$('#left-nav-button').remove();
},
_generateServiceTableViewCells: function() {
if (this.props.services.length > 0) {
return this.props.services.map(function(service, idx){
return (<ServiceTableViewCell service={service} key={idx} />)
});
} else {
return (
<li className="table-view-cell">
<p>
No services configured. Please <a href="/services/new" data-ignore="push">add a service</a> to this server.
</p>
</li>
)
}
},
render: function() {
return (
<div>
<ul className="table-view">
{this._generateServiceTableViewCells()}
</ul>
</div>
);
}
});
var SettingsView = React.createClass({
render: function() {
return (
<div>
<SettingsSelectorView />
<div>
<div id="item1mobile" className="control-content active">
<NewAccountView loadData={this.props.loadData} />
</div>
<div id="item2mobile" className="control-content" style={{ margin: "10px"}}>
<p>Select the number of log entries to display</p>
<LogReaderSettingView />
</div>
</div>
</div>
);
}
});
var SettingsSelectorView = React.createClass({
render: function() {
return (
<div className="segmented-control" style={{margin: "10px"}}>
<a className="control-item active" href="#item1mobile">
Account
</a>
<a className="control-item" href="#item2mobile">
Log Viewer
</a>
</div>
);
}
});
var NewAccountView = React.createClass({
_createAccount: function(e) {
e.preventDefault();
var username = React.findDOMNode(this.refs.username).value;
var password = React.findDOMNode(this.refs.password).value;
$.ajax({
type: 'POST',
url: '/user/auth',
data: {
username: username,
password: password
},
success: function(res) {
localStorage.setItem('auth_token', JSON.parse(res).auth_token);
localStorage.setItem('username', username);
window.location.hash = 'servers';
this.props.loadData();
}.bind(this)
});
},
_logout: function() {
localStorage.setItem('auth_token', '');
localStorage.setItem('username', '');
this.forceUpdate();
},
render: function() {
var loggedIn = localStorage.getItem('auth_token') !== '';
if (loggedIn) {
return (
<div className="content-padded">
<p>You're already logged in!</p>
<button className="btn btn-negative btn-block" onClick={this._logout}>Logout</button>
</div>
);
}
return (
<form style={{padding: "10px"}} onSubmit={this._createAccount}>
<input ref="username" type="text" placeholder="Username" />
<input ref="password" type="text" type="password" placeholder="Password" />
<button type="submit" className="btn btn-positive btn-block">Log in</button>
</form>
);
}
});
var LogReaderSettingView = React.createClass({
_setLines: function() {
var lines = React.findDOMNode(this.refs.logLines).value;
localStorage.setItem('lines', lines);
},
render: function() {
var options = [];
for (var i=10; i <= 100; i+=10) {
options.push(<LogReaderLineOption lines={i} key={i} />);
}
return (
<select style={{margin: "0px"}} ref="logLines" onChange={this._setLines}>
{options}
</select>
);
}
});
var LogReaderLineOption = React.createClass({
render: function() {
return (
<option value={this.props.lines}>{this.props.lines}</option>
);
}
});
React.render(<LagerApp />, document.getElementById('content'));
|
(function(){
Template.__checkName("users_list_email");
Template["users_list_email"] = new Template("Template.users_list_email", (function() {
var view = this;
return HTML.A({
href: function() {
return [ "mailto:", Spacebars.mustache(Spacebars.dot(view.lookup("profile"), "email")) ];
}
}, Blaze.View("lookup:profile.email", function() {
return Spacebars.mustache(Spacebars.dot(view.lookup("profile"), "email"));
}));
}));
})();
|
import React, { Component } from "react"
import { connect } from "react-redux"
import { Button, Form, Modal } from "semantic-ui-react"
import { createMapping, resetNewMapping } from "../../../../actions/instruments"
import { noteMap } from "../../../../utils/mapping"
import "./MappingCreateForm.css"
class MappingCreateForm extends Component {
constructor(props) {
super(props)
this.state = {
input: {
lowerRank: null,
upperRank: null,
referenceRank: null,
sampleId: null,
instrumentId: this.props.instrumentId,
},
error: {
lowerRank: false,
upperRank: false,
referenceRank: false,
sampleId: false,
},
}
this.handleInputChange = this.handleInputChange.bind(this)
this.onSubmit = this.onSubmit.bind(this)
}
handleInputChange(event, SuiObject) {
const target = event.target
const inputValue = SuiObject ? SuiObject.value : target.value
const inputName = SuiObject ? SuiObject.name : target.name
const { input } = this.state
input[inputName] = inputValue
this.setState({ input })
this.checkValidity(inputName, inputValue)
}
checkValidity(name, value) {
const { error } = this.state
error[name] = !value
this.setState({ error })
}
onSubmit() {
const { input } = this.state
for (let name in input) {
this.checkValidity(name, input[name])
}
if (
this.state.error.lowerRank ||
this.state.error.upperRank ||
this.state.error.referenceRank ||
this.state.error.sampleId
) {
return
}
this.props.handleSubmit(this.state.input)
}
render() {
const { instrId, newMapping, sampleChoices } = this.props
const sampleOptions = sampleChoices.map(sample => {
return {
key: sample.id,
text: `${sample.label} - ${sample.label}`,
value: sample.id,
}
})
const noteOptions = []
for (let [rank, value] of noteMap.entries()) {
noteOptions.push({
key: rank,
text: value,
value: rank,
})
}
return (
<Modal
size="small"
open={newMapping.open && newMapping.instrumentId === instrId}
onClose={this.props.closeModal}
closeIcon
>
<Modal.Header>
Mapping for instrument n°{newMapping.instrumentId}
</Modal.Header>
<Modal.Content>
<Form>
<Form.Group widths="equal">
<Form.Select
fluid
required
label="Lower note"
options={noteOptions}
name="lowerRank"
placeholder="Select a note in the list"
onChange={this.handleInputChange}
error={this.state.error.lowerRank}
/>
<Form.Select
fluid
required
label="Upper note"
options={noteOptions}
name="upperRank"
placeholder="Select a note in the list"
onChange={this.handleInputChange}
error={this.state.error.upperRank}
/>
<Form.Select
fluid
required
label="Reference note"
options={noteOptions}
name="referenceRank"
placeholder="Select a note in the list"
onChange={this.handleInputChange}
error={this.state.error.referenceRank}
/>
</Form.Group>
<Form.Select
required
label="Sample"
options={sampleOptions}
name="sampleId"
placeholder={"Select a sample in the list"}
onChange={this.handleInputChange}
error={this.state.error.sampleId}
/>
</Form>
</Modal.Content>
<Modal.Actions>
<Button
positive
icon="add"
loading={newMapping.loading}
labelPosition="right"
content="Add mapping"
onClick={this.onSubmit}
/>
</Modal.Actions>
</Modal>
)
}
}
const mapStateToProps = (state, ownProps) => ({
newMapping: state.instruments.newMapping,
})
const mapDispatchToProps = (dispatch, ownProps) => ({
handleSubmit: inputs => {
const {
lowerRank,
upperRank,
referenceRank,
sampleId,
instrumentId,
} = inputs
// eslint-disable-next-line no-undef
const formData = new FormData()
formData.append("lowerRank", lowerRank)
formData.append("upperRank", upperRank)
formData.append("referenceRank", referenceRank)
formData.append("sampleId", sampleId)
dispatch(createMapping(instrumentId, formData))
},
closeModal() {
dispatch(resetNewMapping())
},
})
export default connect(
mapStateToProps,
mapDispatchToProps
)(MappingCreateForm)
|
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _CordoWrap = require('./CordoWrap');
var _CordoWrap2 = _interopRequireDefault(_CordoWrap);
exports['default'] = new _CordoWrap2['default']();
module.exports = exports['default']; |
'use strict';
angular.module( 'StartupRI' ).controller( 'StartupsCtrl', ['$scope', "$http", function( $scope, $http, $auth) {
$scope.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
$http.get('/api/v1/startups.json').success(function(data) {
$scope.startups = data;
});
$scope.handleRegBtnClick = function() {
$auth.submitRegistration($scope.registrationForm)
.then(function(resp) {
// handle success response
})
.catch(function(resp) {
// handle error response
});
};
$scope.$on('auth:registration-email-success', function(ev, message) {
toastr.clear()
toastr.success("You're now a StartupRI VIP!");
});
$scope.$on('auth:registration-email-error', function(ev, reason) {
toastr.clear()
toastr.error("Registration Failed");
});
}]); |
function BranchData() {
this.position = -1;
this.nodeLength = -1;
this.src = null;
this.evalFalse = 0;
this.evalTrue = 0;
this.init = function(position, nodeLength, src) {
this.position = position;
this.nodeLength = nodeLength;
this.src = src;
return this;
}
this.ranCondition = function(result) {
if (result)
this.evalTrue++;
else
this.evalFalse++;
};
this.pathsCovered = function() {
var paths = 0;
if (this.evalTrue > 0)
paths++;
if (this.evalFalse > 0)
paths++;
return paths;
};
this.covered = function() {
return this.evalTrue > 0 && this.evalFalse > 0;
};
this.toJSON = function() {
return '{"position":' + this.position
+ ',"nodeLength":' + this.nodeLength
+ ',"src":' + jscoverage_quote(this.src)
+ ',"evalFalse":' + this.evalFalse
+ ',"evalTrue":' + this.evalTrue + '}';
};
this.message = function() {
if (this.evalTrue === 0 && this.evalFalse === 0)
return 'Condition never evaluated :\t' + this.src;
else if (this.evalTrue === 0)
return 'Condition never evaluated to true :\t' + this.src;
else if (this.evalFalse === 0)
return 'Condition never evaluated to false:\t' + this.src;
else
return 'Condition covered';
};
}
BranchData.fromJson = function(jsonString) {
var json = eval('(' + jsonString + ')');
var branchData = new BranchData();
branchData.init(json.position, json.nodeLength, json.src);
branchData.evalFalse = json.evalFalse;
branchData.evalTrue = json.evalTrue;
return branchData;
};
BranchData.fromJsonObject = function(json) {
var branchData = new BranchData();
branchData.init(json.position, json.nodeLength, json.src);
branchData.evalFalse = json.evalFalse;
branchData.evalTrue = json.evalTrue;
return branchData;
};
function buildBranchMessage(conditions) {
var message = 'The following was not covered:';
for (var i = 0; i < conditions.length; i++) {
if (conditions[i] !== undefined && conditions[i] !== null && !conditions[i].covered())
message += '\n- '+ conditions[i].message();
}
return message;
};
function convertBranchDataConditionArrayToJSON(branchDataConditionArray) {
var array = [];
var length = branchDataConditionArray.length;
for (var condition = 0; condition < length; condition++) {
var branchDataObject = branchDataConditionArray[condition];
if (branchDataObject === undefined || branchDataObject === null) {
value = 'null';
} else {
value = branchDataObject.toJSON();
}
array.push(value);
}
return '[' + array.join(',') + ']';
}
function convertBranchDataLinesToJSON(branchData) {
if (branchData === undefined) {
return '{}'
}
var json = '';
for (var line in branchData) {
if (json !== '')
json += ','
json += '"' + line + '":' + convertBranchDataConditionArrayToJSON(branchData[line]);
}
return '{' + json + '}';
}
function convertBranchDataLinesFromJSON(jsonObject) {
if (jsonObject === undefined) {
return {};
}
for (var line in jsonObject) {
var branchDataJSON = jsonObject[line];
if (branchDataJSON !== null) {
for (var conditionIndex = 0; conditionIndex < branchDataJSON.length; conditionIndex ++) {
var condition = branchDataJSON[conditionIndex];
if (condition !== null) {
branchDataJSON[conditionIndex] = BranchData.fromJsonObject(condition);
}
}
}
}
return jsonObject;
}
function jscoverage_quote(s) {
return '"' + s.replace(/[\u0000-\u001f"\\\u007f-\uffff]/g, function (c) {
switch (c) {
case '\b':
return '\\b';
case '\f':
return '\\f';
case '\n':
return '\\n';
case '\r':
return '\\r';
case '\t':
return '\\t';
// IE doesn't support this
/*
case '\v':
return '\\v';
*/
case '"':
return '\\"';
case '\\':
return '\\\\';
default:
return '\\u' + jscoverage_pad(c.charCodeAt(0).toString(16));
}
}) + '"';
}
function getArrayJSON(coverage) {
var array = [];
if (coverage === undefined)
return array;
var length = coverage.length;
for (var line = 0; line < length; line++) {
var value = coverage[line];
if (value === undefined || value === null) {
value = 'null';
}
array.push(value);
}
return array;
}
function jscoverage_serializeCoverageToJSON() {
var json = [];
for (var file in _$jscoverage) {
var lineArray = getArrayJSON(_$jscoverage[file].lineData);
var fnArray = getArrayJSON(_$jscoverage[file].functionData);
json.push(jscoverage_quote(file) + ':{"lineData":[' + lineArray.join(',') + '],"functionData":[' + fnArray.join(',') + '],"branchData":' + convertBranchDataLinesToJSON(_$jscoverage[file].branchData) + '}');
}
return '{' + json.join(',') + '}';
}
function jscoverage_pad(s) {
return '0000'.substr(s.length) + s;
}
function jscoverage_html_escape(s) {
return s.replace(/[<>\&\"\']/g, function (c) {
return '&#' + c.charCodeAt(0) + ';';
});
}
try {
if (typeof top === 'object' && top !== null && typeof top.opener === 'object' && top.opener !== null) {
// this is a browser window that was opened from another window
if (! top.opener._$jscoverage) {
top.opener._$jscoverage = {};
}
}
}
catch (e) {}
try {
if (typeof top === 'object' && top !== null) {
// this is a browser window
try {
if (typeof top.opener === 'object' && top.opener !== null && top.opener._$jscoverage) {
top._$jscoverage = top.opener._$jscoverage;
}
}
catch (e) {}
if (! top._$jscoverage) {
top._$jscoverage = {};
}
}
}
catch (e) {}
try {
if (typeof top === 'object' && top !== null && top._$jscoverage) {
this._$jscoverage = top._$jscoverage;
}
}
catch (e) {}
if (! this._$jscoverage) {
this._$jscoverage = {};
}
if (! _$jscoverage['/dialog.js']) {
_$jscoverage['/dialog.js'] = {};
_$jscoverage['/dialog.js'].lineData = [];
_$jscoverage['/dialog.js'].lineData[6] = 0;
_$jscoverage['/dialog.js'].lineData[7] = 0;
_$jscoverage['/dialog.js'].lineData[8] = 0;
_$jscoverage['/dialog.js'].lineData[9] = 0;
_$jscoverage['/dialog.js'].lineData[10] = 0;
_$jscoverage['/dialog.js'].lineData[11] = 0;
_$jscoverage['/dialog.js'].lineData[12] = 0;
_$jscoverage['/dialog.js'].lineData[14] = 0;
_$jscoverage['/dialog.js'].lineData[53] = 0;
_$jscoverage['/dialog.js'].lineData[84] = 0;
_$jscoverage['/dialog.js'].lineData[85] = 0;
_$jscoverage['/dialog.js'].lineData[88] = 0;
_$jscoverage['/dialog.js'].lineData[90] = 0;
_$jscoverage['/dialog.js'].lineData[94] = 0;
_$jscoverage['/dialog.js'].lineData[105] = 0;
_$jscoverage['/dialog.js'].lineData[107] = 0;
_$jscoverage['/dialog.js'].lineData[108] = 0;
_$jscoverage['/dialog.js'].lineData[109] = 0;
_$jscoverage['/dialog.js'].lineData[119] = 0;
_$jscoverage['/dialog.js'].lineData[120] = 0;
_$jscoverage['/dialog.js'].lineData[121] = 0;
_$jscoverage['/dialog.js'].lineData[124] = 0;
_$jscoverage['/dialog.js'].lineData[127] = 0;
_$jscoverage['/dialog.js'].lineData[131] = 0;
_$jscoverage['/dialog.js'].lineData[133] = 0;
_$jscoverage['/dialog.js'].lineData[134] = 0;
_$jscoverage['/dialog.js'].lineData[136] = 0;
_$jscoverage['/dialog.js'].lineData[140] = 0;
_$jscoverage['/dialog.js'].lineData[147] = 0;
_$jscoverage['/dialog.js'].lineData[148] = 0;
_$jscoverage['/dialog.js'].lineData[150] = 0;
_$jscoverage['/dialog.js'].lineData[151] = 0;
_$jscoverage['/dialog.js'].lineData[153] = 0;
_$jscoverage['/dialog.js'].lineData[156] = 0;
_$jscoverage['/dialog.js'].lineData[157] = 0;
_$jscoverage['/dialog.js'].lineData[158] = 0;
_$jscoverage['/dialog.js'].lineData[160] = 0;
_$jscoverage['/dialog.js'].lineData[162] = 0;
_$jscoverage['/dialog.js'].lineData[163] = 0;
_$jscoverage['/dialog.js'].lineData[166] = 0;
_$jscoverage['/dialog.js'].lineData[167] = 0;
_$jscoverage['/dialog.js'].lineData[169] = 0;
_$jscoverage['/dialog.js'].lineData[173] = 0;
}
if (! _$jscoverage['/dialog.js'].functionData) {
_$jscoverage['/dialog.js'].functionData = [];
_$jscoverage['/dialog.js'].functionData[0] = 0;
_$jscoverage['/dialog.js'].functionData[1] = 0;
_$jscoverage['/dialog.js'].functionData[2] = 0;
_$jscoverage['/dialog.js'].functionData[3] = 0;
_$jscoverage['/dialog.js'].functionData[4] = 0;
_$jscoverage['/dialog.js'].functionData[5] = 0;
_$jscoverage['/dialog.js'].functionData[6] = 0;
}
if (! _$jscoverage['/dialog.js'].branchData) {
_$jscoverage['/dialog.js'].branchData = {};
_$jscoverage['/dialog.js'].branchData['131'] = [];
_$jscoverage['/dialog.js'].branchData['131'][1] = new BranchData();
_$jscoverage['/dialog.js'].branchData['151'] = [];
_$jscoverage['/dialog.js'].branchData['151'][1] = new BranchData();
_$jscoverage['/dialog.js'].branchData['151'][2] = new BranchData();
_$jscoverage['/dialog.js'].branchData['151'][3] = new BranchData();
_$jscoverage['/dialog.js'].branchData['153'] = [];
_$jscoverage['/dialog.js'].branchData['153'][1] = new BranchData();
_$jscoverage['/dialog.js'].branchData['153'][2] = new BranchData();
_$jscoverage['/dialog.js'].branchData['154'] = [];
_$jscoverage['/dialog.js'].branchData['154'][1] = new BranchData();
_$jscoverage['/dialog.js'].branchData['157'] = [];
_$jscoverage['/dialog.js'].branchData['157'][1] = new BranchData();
_$jscoverage['/dialog.js'].branchData['166'] = [];
_$jscoverage['/dialog.js'].branchData['166'][1] = new BranchData();
}
_$jscoverage['/dialog.js'].branchData['166'][1].init(17, 12, '!this.dialog');
function visit9_166_1(result) {
_$jscoverage['/dialog.js'].branchData['166'][1].ranCondition(result);
return result;
}_$jscoverage['/dialog.js'].branchData['157'][1].init(89, 8, '!S.UA.ie');
function visit8_157_1(result) {
_$jscoverage['/dialog.js'].branchData['157'][1].ranCondition(result);
return result;
}_$jscoverage['/dialog.js'].branchData['154'][1].init(27, 76, 'xhtmlDtd.$block[nextName] && xhtmlDtd[nextName][\'#text\']');
function visit7_154_1(result) {
_$jscoverage['/dialog.js'].branchData['154'][1].ranCondition(result);
return result;
}_$jscoverage['/dialog.js'].branchData['153'][2].init(1006, 104, 'nextName && xhtmlDtd.$block[nextName] && xhtmlDtd[nextName][\'#text\']');
function visit6_153_2(result) {
_$jscoverage['/dialog.js'].branchData['153'][2].ranCondition(result);
return result;
}_$jscoverage['/dialog.js'].branchData['153'][1].init(1004, 107, '!(nextName && xhtmlDtd.$block[nextName] && xhtmlDtd[nextName][\'#text\'])');
function visit5_153_1(result) {
_$jscoverage['/dialog.js'].branchData['153'][1].ranCondition(result);
return result;
}_$jscoverage['/dialog.js'].branchData['151'][3].init(862, 42, 'next[0].nodeType === NodeType.ELEMENT_NODE');
function visit4_151_3(result) {
_$jscoverage['/dialog.js'].branchData['151'][3].ranCondition(result);
return result;
}_$jscoverage['/dialog.js'].branchData['151'][2].init(862, 60, 'next[0].nodeType === NodeType.ELEMENT_NODE && next.nodeName()');
function visit3_151_2(result) {
_$jscoverage['/dialog.js'].branchData['151'][2].ranCondition(result);
return result;
}_$jscoverage['/dialog.js'].branchData['151'][1].init(854, 68, 'next && next[0].nodeType === NodeType.ELEMENT_NODE && next.nodeName()');
function visit2_151_1(result) {
_$jscoverage['/dialog.js'].branchData['151'][1].ranCondition(result);
return result;
}_$jscoverage['/dialog.js'].branchData['131'][1].init(139, 25, '!S.trim(val = code.val())');
function visit1_131_1(result) {
_$jscoverage['/dialog.js'].branchData['131'][1].ranCondition(result);
return result;
}_$jscoverage['/dialog.js'].lineData[6]++;
KISSY.add(function(S, require) {
_$jscoverage['/dialog.js'].functionData[0]++;
_$jscoverage['/dialog.js'].lineData[7]++;
var Editor = require('editor');
_$jscoverage['/dialog.js'].lineData[8]++;
var MenuButton = require('menubutton');
_$jscoverage['/dialog.js'].lineData[9]++;
var xhtmlDtd = Editor.XHTML_DTD;
_$jscoverage['/dialog.js'].lineData[10]++;
var NodeType = S.DOM.NodeType;
_$jscoverage['/dialog.js'].lineData[11]++;
var notWhitespaceEval = Editor.Walker.whitespaces(true);
_$jscoverage['/dialog.js'].lineData[12]++;
var Dialog4E = require('../dialog');
_$jscoverage['/dialog.js'].lineData[14]++;
var codeTypes = [['ActionScript3', 'as3'], ['Bash/Shell', 'bash'], ['C/C++', 'cpp'], ['Css', 'css'], ['CodeFunction', 'cf'], ['C#', 'c#'], ['Delphi', 'delphi'], ['Diff', 'diff'], ['Erlang', 'erlang'], ['Groovy', 'groovy'], ['HTML', 'html'], ['Java', 'java'], ['JavaFx', 'jfx'], ['Javascript', 'js'], ['Perl', 'pl'], ['Php', 'php'], ['Plain Text', 'plain'], ['PowerShell', 'ps'], ['Python', 'python'], ['Ruby', 'ruby'], ['Scala', 'scala'], ['Sql', 'sql'], ['Vb', 'vb'], ['Xml', 'xml']], bodyTpl = '<div class="{prefixCls}code-wrap">' + '<table class="{prefixCls}code-table">' + '<tr>' + '<td class="{prefixCls}code-label">' + '<label for="ks-editor-code-type">' + '\u7c7b\u578b\uff1a' + '</label>' + '</td>' + '<td class="{prefixCls}code-content">' + '<select ' + 'id="ks-editor-code-type" ' + ' class="{prefixCls}code-type">' + S.map(codeTypes, function(codeType) {
_$jscoverage['/dialog.js'].functionData[1]++;
_$jscoverage['/dialog.js'].lineData[53]++;
return '<option value="' + codeType[1] + '">' + codeType[0] + '</option>';
}) + '</select>' + '</td>' + '</tr>' + '<tr>' + '<td>' + '<label for="ks-editor-code-textarea">' + '\u4ee3\u7801\uff1a' + '</label>' + '</td>' + '<td>' + '<textarea ' + 'id="ks-editor-code-textarea" ' + ' class="{prefixCls}code-textarea {prefixCls}input">' + '</textarea>' + '</td>' + '</tr>' + '</table>' + '</div>', footTpl = '<div class="{prefixCls}code-table-action">' + '<a href="javascript:void(\'\u63d2\u5165\')"' + ' class="{prefixCls}code-insert {prefixCls}button">\u63d2\u5165</a>' + '<a href="javascript:void(\'\u53d6\u6d88\')"' + ' class="{prefixCls}code-cancel {prefixCls}button">\u53d6\u6d88</a>' + '</td>' + '</div>', codeTpl = '<pre class="prettyprint ks-editor-code brush:{type};toolbar:false;">' + '{code}' + '</pre>';
_$jscoverage['/dialog.js'].lineData[84]++;
function CodeDialog(editor) {
_$jscoverage['/dialog.js'].functionData[2]++;
_$jscoverage['/dialog.js'].lineData[85]++;
this.editor = editor;
}
_$jscoverage['/dialog.js'].lineData[88]++;
S.augment(CodeDialog, {
initDialog: function() {
_$jscoverage['/dialog.js'].functionData[3]++;
_$jscoverage['/dialog.js'].lineData[90]++;
var self = this, prefixCls = self.editor.get('prefixCls') + 'editor-', el, d;
_$jscoverage['/dialog.js'].lineData[94]++;
d = self.dialog = new Dialog4E({
width: 500,
mask: true,
headerContent: '\u63d2\u5165\u4ee3\u7801',
bodyContent: S.substitute(bodyTpl, {
prefixCls: prefixCls}),
footerContent: S.substitute(footTpl, {
prefixCls: prefixCls})}).render();
_$jscoverage['/dialog.js'].lineData[105]++;
el = d.get('el');
_$jscoverage['/dialog.js'].lineData[107]++;
self.insert = el.one('.' + prefixCls + 'code-insert');
_$jscoverage['/dialog.js'].lineData[108]++;
self.cancel = el.one('.' + prefixCls + 'code-cancel');
_$jscoverage['/dialog.js'].lineData[109]++;
self.type = MenuButton.Select.decorate(el.one('.' + prefixCls + 'code-type'), {
prefixCls: prefixCls + 'big-',
width: 150,
menuCfg: {
prefixCls: prefixCls,
height: 320,
render: d.get('contentEl')}});
_$jscoverage['/dialog.js'].lineData[119]++;
self.code = el.one('.' + prefixCls + 'code-textarea');
_$jscoverage['/dialog.js'].lineData[120]++;
self.insert.on('click', self._insert, self);
_$jscoverage['/dialog.js'].lineData[121]++;
self.cancel.on('click', self.hide, self);
},
hide: function() {
_$jscoverage['/dialog.js'].functionData[4]++;
_$jscoverage['/dialog.js'].lineData[124]++;
this.dialog.hide();
},
_insert: function() {
_$jscoverage['/dialog.js'].functionData[5]++;
_$jscoverage['/dialog.js'].lineData[127]++;
var self = this, val, editor = self.editor, code = self.code;
_$jscoverage['/dialog.js'].lineData[131]++;
if (visit1_131_1(!S.trim(val = code.val()))) {
_$jscoverage['/dialog.js'].lineData[133]++;
alert('\u8bf7\u8f93\u5165\u4ee3\u7801!');
_$jscoverage['/dialog.js'].lineData[134]++;
return;
}
_$jscoverage['/dialog.js'].lineData[136]++;
var codeEl = S.all(S.substitute(codeTpl, {
type: self.type.get('value'),
code: S.escapeHtml(val)}), editor.get('document')[0]);
_$jscoverage['/dialog.js'].lineData[140]++;
self.dialog.hide();
_$jscoverage['/dialog.js'].lineData[147]++;
editor.insertElement(codeEl);
_$jscoverage['/dialog.js'].lineData[148]++;
var range = editor.getSelection().getRanges()[0];
_$jscoverage['/dialog.js'].lineData[150]++;
var next = codeEl.next(notWhitespaceEval, 1);
_$jscoverage['/dialog.js'].lineData[151]++;
var nextName = visit2_151_1(next && visit3_151_2(visit4_151_3(next[0].nodeType === NodeType.ELEMENT_NODE) && next.nodeName()));
_$jscoverage['/dialog.js'].lineData[153]++;
if (visit5_153_1(!(visit6_153_2(nextName && visit7_154_1(xhtmlDtd.$block[nextName] && xhtmlDtd[nextName]['#text']))))) {
_$jscoverage['/dialog.js'].lineData[156]++;
next = S.all('<p></p>', editor.get('document')[0]);
_$jscoverage['/dialog.js'].lineData[157]++;
if (visit8_157_1(!S.UA.ie)) {
_$jscoverage['/dialog.js'].lineData[158]++;
next._4eAppendBogus();
}
_$jscoverage['/dialog.js'].lineData[160]++;
codeEl.after(next);
}
_$jscoverage['/dialog.js'].lineData[162]++;
range.moveToElementEditablePosition(next);
_$jscoverage['/dialog.js'].lineData[163]++;
editor.getSelection().selectRanges([range]);
},
show: function() {
_$jscoverage['/dialog.js'].functionData[6]++;
_$jscoverage['/dialog.js'].lineData[166]++;
if (visit9_166_1(!this.dialog)) {
_$jscoverage['/dialog.js'].lineData[167]++;
this.initDialog();
}
_$jscoverage['/dialog.js'].lineData[169]++;
this.dialog.show();
}});
_$jscoverage['/dialog.js'].lineData[173]++;
return CodeDialog;
});
|
var nps = require('path');
var Picidae = require('../lib');
var getPath = require('./lib/getPath');
module.exports = function (commander) {
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = 'production'
}
var p = getPath(commander.config)
var configPath = p.configPath, cwd = p.cwd
var config = require(configPath)
process.chdir(cwd)
config.force = commander.force;
config.noSpider = !commander.spider;
config.noSw = !commander.sw;
config.sourceMap = commander.sourceMap;
config.id = require('md5')(configPath).substr(2, 8)
config.watch = false;
config.ssr = commander.ssr;
var picidae = new Picidae(config)
picidae.build(function () {
picidae.clearTmp();
});
process.on('SIGINT', function () {
picidae.clearTmp();
process.exit(1);
});
}
|
'use strict';
var Can = require('./can');
var internals = {};
internals.applyUserProperties = function (target) {
[target, target.prototype].forEach(internals.registerCan, this);
};
internals.registerCan = function (target) {
Object.defineProperty(target, 'can', {
enumerable: true,
get: function () {
return Can.create(this);
}
});
};
module.exports = function (ModelBase) {
var User = ModelBase.extend();
internals.applyUserProperties.call(this, User);
User.extend = function () {
var Extended = ModelBase.extend.apply(this, arguments);
internals.applyUserProperties(Extended);
return Extended;
};
return User;
}; |
/* */
'use strict';
Object.defineProperty(exports, "__esModule", {value: true});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin');
var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixin);
var _svgIcon = require('../../svg-icon');
var _svgIcon2 = _interopRequireDefault(_svgIcon);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
var ImageFlip = _react2.default.createClass({
displayName: 'ImageFlip',
mixins: [_reactAddonsPureRenderMixin2.default],
render: function render() {
return _react2.default.createElement(_svgIcon2.default, this.props, _react2.default.createElement('path', {d: 'M15 21h2v-2h-2v2zm4-12h2V7h-2v2zM3 5v14c0 1.1.9 2 2 2h4v-2H5V5h4V3H5c-1.1 0-2 .9-2 2zm16-2v2h2c0-1.1-.9-2-2-2zm-8 20h2V1h-2v22zm8-6h2v-2h-2v2zM15 5h2V3h-2v2zm4 8h2v-2h-2v2zm0 8c1.1 0 2-.9 2-2h-2v2z'}));
}
});
exports.default = ImageFlip;
module.exports = exports['default'];
|
$(document).ready(function() {
$("#departing").datepicker();
$("#returning").datepicker();
$("button").click(function() {
var selected = $("#dropdown option:selected").text();
var departing = $("#departing").val();
var returning = $("#returning").val();
});
});
var config = {
apiKey: "AIzaSyDCY3lAwOFJn9QaR83WlUOOK1AauG_ezWY",
authDomain: "buddy-3f375.firebaseapp.com",
databaseURL: "https://buddy-3f375.firebaseio.com",
projectId: "buddy-3f375",
storageBucket: "buddy-3f375.appspot.com",
messagingSenderId: "501948672835"
};
firebase.initializeApp(config);
var database = firebase.database();
var postRef = database.ref('events');
var usersRef = database.ref('users');
var storage = firebase.storage();
var storageRef = firebase.storage().ref();
var provider = new firebase.auth.GoogleAuthProvider();
//var user = [];
//var Profilep = document.getElementById("ProfilePic");
//var Welom = document.getElementById("Welcome");
// firebase.auth().onAuthStateChanged(function(currentUser) {
// if (currentUser) {
// // User is signed in.
// user = currentUser;
// x.style.display = 'none';
// Profilep.style.display = 'inline';
// Profilep.src = user.photoURL;
// Welom.innerHTML = ('Welcome, ' + user.displayName).bold();
// console.log("already signed in"+user.displayName);
// } else {
// // No user is signed in.
// console.log("user is not logged in");
// }
// });
// var config = {
// apiKey: "AIzaSyDCY3lAwOFJn9QaR83WlUOOK1AauG_ezWY",
// authDomain: "buddy-3f375.firebaseapp.com",
// databaseURL: "https://buddy-3f375.firebaseio.com",
// projectId: "buddy-3f375",
// storageBucket: "buddy-3f375.appspot.com",
// messagingSenderId: "501948672835"
// };
// firebase.initializeApp(config);
// var database = firebase.database();
// var postRef = database.ref('events');
// var usersRef = database.ref('users');
// var storage = firebase.storage();
// var storageRef = firebase.storage().ref();
// var provider = new firebase.auth.GoogleAuthProvider();
// var user = [];
// var Profilep = document.getElementById("ProfilePic");
// var Welom = document.getElementById("Welcome");
// function writeUserData(userId, name, email) {
// firebase.database().ref('users/' + userId).set({
// username: name,
// email: email,
// });
// }
// function LoginFaceBook(x) {
// if (x) {
// var provider = new firebase.auth.FacebookAuthProvider();
// firebase.auth().signInWithPopup(provider).then(function(result) {
// // This gives you a Facebook Access Token. You can use it to access the Facebook API.
// var token = result.credential.accessToken;
// // The signed-in user info.
// user = result.user;
// console.log(user);
// // ...
// writeUserData(user.uid, user.displayName, user.email);
// x.style.display = 'none';
// Profilep.style.display = 'inline';
// Profilep.src = user.photoURL;
// Welom.innerHTML = ('Welcome, ' + user.displayName).bold();
// }).catch(function(error) {
// // Handle Errors here.
// var errorCode = error.code;
// var errorMessage = error.message;
// // The email of the user's account used.
// var email = error.email;
// // The firebase.auth.AuthCredential type that was used.
// var credential = error.credential;
// // ...
// });
// }
// }
|
var assert = require('chai').assert;
var combine = require(`${__dirname}/../../../../src/steps/combine`);
describe('#remove', function () {
it('should remove one key', function () {
var schema = {
for: 'result',
each: [
['add', {byKey: 'id', fromObject: 'users', to: 'user'}],
['remove', ['test']]
],
to: 'test'
};
var data = {
result: [
{id: 1, test: 1},
{id: 2, test: 2}
],
users: {
1: {login: 1},
2: {login: 2}
}
};
var result = {};
combine(schema, data, result);
var valid = {
test: [
{id: 1, user: {login: 1}},
{id: 2, user: {login: 2}}
]
};
assert.deepEqual(valid, result);
});
it('should remove many keys', function () {
var schema = {
for: 'result',
each: [
['add', {byKey: 'id', fromObject: 'users', to: 'user'}],
['remove', ['test', 'shit']]
],
to: 'test'
};
var data = {
result: [
{id: 1, test: 1, shit: [1,2,3]},
{id: 2, test: 2, shit: [1,2,3]}
],
users: {
1: {login: 1},
2: {login: 2}
}
};
var result = {};
combine(schema, data, result);
var valid = {
test: [
{id: 1, user: {login: 1}},
{id: 2, user: {login: 2}}
]
};
assert.deepEqual(valid, result);
});
it('should do nothing on empty data', function () {
var schema = {
for: 'result',
each: [
['add', {byKey: 'id', fromObject: 'users', to: 'user'}],
['remove', []]
],
to: 'test'
};
var data = {
result: [
{id: 1, test: 1, shit: [1,2,3]},
{id: 2, test: 2, shit: [1,2,3]}
],
users: {
1: {login: 1},
2: {login: 2}
}
};
var result = {};
combine(schema, data, result);
var valid = {
test: [
{id: 1, user: {login: 1}, test: 1, shit: [1,2,3]},
{id: 2, user: {login: 2}, test: 2, shit: [1,2,3]}
]
};
assert.deepEqual(valid, result);
});
it('should error on invalid remove step config', function () {
var schema = {
for: 'result',
each: [
['remove', null]
],
to: 'test'
};
var data = {
result: [
{id: 1, test: 1},
{id: 2, test: 2}
],
users: {
1: {login: 1},
2: {login: 2}
}
};
assert.throws(x => combine(schema, data, {}), Error, 'invalid config for combine step "remove"');
});
});
|
//= wrapped
/**
* Created by shardik on 21/01/18.
*/
angular.module('streama.translations').config(function ($translateProvider) {
$translateProvider.translations('ru', {
LOGIN: {
TITLE: 'Пожалуйста, авторизуйтесь',
USERNAME: 'Логин',
PASSWORD: 'Пароль',
FIRST_TIME_HINT: 'Впервые? Используйте \'admin\' в качестве логина и пароля для входа.',
SUBMIT: 'Войти',
SESSION_EXPIRED: 'Ваша сессия истекла. Пожалуйста, войдите снова.'
},
DASHBOARD: {
HOME: 'Домашняя страница',
TV_SHOWS: 'ТВ шоу',
MOVIES: 'Фильмы',
MY_LIST:'Мой список',
TITLE: 'Главная',
RECOMMENDATIONS: 'Рекомендовано для вас',
NEW_RELEASES: 'Новое на сайте',
CONTINUE_WATCHING: 'Продолжить просмотр',
DISCOVER_SHOWS: 'Обзор тв-шоу',
DISCOVER_MOVIES: 'Обзор кино',
DISCOVER_OTHER_VIDEOS: 'Обзор остального видео',
SORT: 'Сортировать по:',
SEARCH_BY_NAME: 'имени...',
FILTER_BY_TAG: 'тегу...',
BROWSE_GENRES: 'Обзор',
LOOKING_AT_GENRE: 'Вы смотрите по жанру:',
MARK_COMPLETED: 'Уже просмотрено!',
NO_TVSHOWS_FOUND: 'ТВ-шоу пока недоступно',
NO_MOVIES_FOUND: 'Кино пока недоступно',
WATCHLIST: 'Посмотреть позже'
},
VIDEO: {
RELEASED: 'Дата выхода',
IMDB: 'IMDB',
RATING: 'Рейтинг',
VOTES: 'Голосов',
OVERVIEW: 'Описание',
GENRE: 'Жанр',
TRAILER: 'Трейлер',
SEASON: 'Сезон',
NO_SUBTITLE: 'без субтитров'
},
MESSAGES: {
SHARE_SOCKET: 'Создавая новую сессию, вы будете перенаправлены обратно на этот плеер, но на этот раз у вас будет уникальный идентификатор сессии в URL-адресе. Поделитесь этим видео с друзьями, чтобы синхронизировать их с ними!',
FILE_MISSING: 'Существует проблема с этим контентом. Кажется, вы удалили из него связанный видеофайл.',
CODEC_PROBLEM: 'Кажется, что проблема связана с добавлением видеофайла в плеер. Это, скорее всего, связано с проблемой кодека. Попробуйте преобразовать его в совместимый кодек HTML5, удалите прикрепленный файл и снова добавьте его. Если кодеки в порядке, проверьте данные об ошибках сервера и базового URL в настройках.',
WRONG_BASEPATH: 'Вы пытаетесь просмотреть видео с использованием неправильного базового пути, но просматриваете страницу через переменную «{{basePath}}». Убедитесь, что вы установили правильный базовый путь в настройках и используете его для просмотра приложения.',
FILE_IN_FS_NOT_FOUND: 'Ваше видео не может быть найдено ни в одном из мест, доступных для приложения. Проверьте свои настройки и файловую систему, чтобы убедиться, что файлы доступны для приложения.'
},
MANAGE_CONTENT: 'Управление',
MANAGE_SUB_PROFILES: 'Управление профилями',
WHOS_WATCHING: 'Кто будет смотреть?',
ADD_SUB_PROFILE: 'Добавить профайл',
EDIT_BTN: 'Изменить',
DONE_BTN: 'Сделано',
SAVE_BTN: 'Сохранить',
CREATE_BTN: 'Создать',
CANCEL_BTN: 'Отменить',
DELETE_BTN: 'Удалить',
ENTER_NAME: 'Введите имя',
EDIT_PROFILE: 'Редактировать профиль',
CREATE_PROFILE: 'Создать профиль',
ADMIN: 'Админка',
HELP: 'Помощь',
HELP_FAQ: 'ПОМОЩЬ / ЧаВО',
PROFILE_SETTINGS: 'Настройки',
LOGOUT: 'Выйти',
CHANGE_PASSWORD: 'Изменить пароль',
LANGUAGE_en: 'English/английский',
LANGUAGE_cn: 'Chinese/中文',
LANGUAGE_ru: 'Русский',
LANGUAGE_de: 'Deutsch/Немецкий',
LANGUAGE_fr: 'Français/Французский',
LANGUAGE_es: 'Español/испанский',
LANGUAGE_kr: '한국어/корейский язык',
LANGUAGE_nl: 'Nederlands/Голландский',
LANGUAGE_pt: 'Português/португальский',
LANGUAGE_ja: '日本語/японский язык',
LANGUAGE_it: 'Italiano/итальянский',
LANGUAGE_da: 'Dansk/датский',
LANGUAGE_ar: 'عربى/арабский',
LANGUAGE_hu: 'Magyar/венгерский',
PROFIlE: {
USERNAME: 'Логин',
FULL_NAME: 'Имя',
LANGUAGE: 'Язык',
PAUSE_ON_CLICK: 'Поставить на паузу при клике',
FAVORITE_GENRES: 'Любимые жанры',
AMOUNT_OF_MEDIA_ENTRIES: 'Количество видео на главной странице (до ссылки «Загрузить больше»)',
SAVE: 'Сохранить профиль',
PASS: 'Пароль',
OLD_PASS: 'Старый пароль',
NEW_PASS: 'Новый пароль',
NEW_PASS_PLACEHOLDER: 'Новый пароль (минимум 6 символов)',
REPEAT_PASS: 'Повоторите пароль',
PASS_ERROR_EMPTY: 'Пароль не должен быть пустым',
PASS_ERROR_LENGTH: 'Пароль должен быть не менее 6 символов',
PASS_ERROR_REPEAT: 'Пароли не совпадают',
SAVE_PASS: 'Установить новый пароль'
},
SORT_OPTIONS: {
AZ: 'A-Z',
ZA: 'Z-A',
NEWEST_ADDED: 'Самые последние',
OLDEST_ADDED: 'Самые новые',
NEWEST_RELEASED: 'Последние поступления',
OLDEST_RELEASED: 'Старые поступления',
NEWEST_AIRED: 'Самые новые',
OLDEST_AIRED: 'Самые старые',
NEWEST_REPORTED: 'Самые последние сообщения',
OLDEST_REPORTED: 'Старое сообщение',
NEWEST_UPDATED: 'Самые последние обновления',
OLDEST_UPDATED: 'Последнее обновление'
},
FAQ: {
UPLOAD_VIDEO: {
TITLE: 'Как я могу загрузить видео?',
TEXT: "Вы можете загружать видео, перейдя в меню «Управление». Выберите, что вы хотите загрузить: фильм, телешоу или другое видео. Выберите соответствующее подменю "+
"в левой части экрана. Вы можете загрузить видео, нажав кнопку «Создать новый фильм / ТВ-шоу / другое видео или набрав" +
"название видео, которое вы хотите загрузить в панель поиска, и выбрать соответствующий фильм из результатов поиска. После этого вы можете выбрать, как удобно добавить видео:" +
"вводя всю информацию вручную, либо загружая свою информацию из базы TheMovieDB (автоматически), после чего вы можете загрузить видео и файлы субтитров, нажав кнопку «Управление»."
},
DELETE_VIDEO: {
TITLE: 'Как мне удалить видео?',
TEXT: "Вы можете удалить видео, перейдя на страницу информации о видео и нажав «Управление файлами» и выбрав красную иконку со значком мусорной корзины. Нажав «Изменить фильм» и выбрав "+
"Удалить фильм - это еще один способ сделать так. Вы также можете использовать Диспетчер файлов, который находится в меню «Управление». Вы можете увидеть все файлы, которые вы там загрузили. Нажмите" +
"красную иконку со значком мусорной корзины, чтобы удалить файл."
},
VIDEO_FORMATS: {
TITLE: 'Какие форматы видео поддерживаются?',
TEXT: "Streama поддерживает в настоящее время только те форматы видеофайлов, поддерживаемые проигрывателем стандарта HTML5. Вы можете проверить, совместим ли ваш видеофайл с HTML5-плеером,"+
" перетащив ваш файл на пустую закладку в вашем браузере. Если видео откроется и начнет воспроизводиться, значит формат поддерживается."
},
SUBTITLES: {
TITLE: 'Как добавить субтитры к видео?',
TEXT: "Вы можете добавить субтитры к видео, нажав кнопку «Управление», которая находится на странице информации о видео. Вы можете перетащить туда файлы субтитров. "+
"Раньше вам приходилось вручную преобразовывать их в совместимый формат файла (WebVTT), мучаясь с перекодированием! Теперь приложение обрабатывает за вас весь рутинный процесс."
},
INVITE_USERS: {
TITLE: 'Как я могу пригласить друзей посмотреть мои размещенные видео?',
TEXT:"Вы можете поделиться своими видео с друзьями, предложив им просмотр на размещенном вами сайте с использованием Streama. Перейдите в меню «Пользователи» и нажмите «Пригласить пользователя». Заполните форму приглашения и "+
"выберите роль приглашенного пользователя. Пользователи с ролью Admin могут редактировать пункт «Пользователи и настройки». Пользователи с ролью Content Manager могут редактировать контент. Ваш друг будет извещен о" +
"приглашении по электронной почте. Вы также можете обмениваться видеосессиями с друзьями, нажав кнопку «Поделиться» видеопроигрывателя, связав URL-адрес сессии с ними."
},
BASE_URL: {
TITLE: "Какой базовый URL-адрес Streama и как его настроить?",
TEXT: "Базовый URL-адрес используется для воспроизведения видео и ссылки в приглашении по электронной почте."
},
NOTIFICATIONS: {
TITLE: "Что такое уведомления?",
TEXT: "Вы можете уведомить своих приглашенных друзей о новых загруженных видео, отправив им уведомления. Вы можете отправить их, добавляя в очередь уведомлений, нажав на кнопку "+
"«Добавить уведомлениe», которая находится на странице информации вашего видео, и перейти в меню «Уведомления», нажав кнопку «Отправить в очередь»."
},
VIDEO_PLAYER_SHORTCUTS: {
TITLE: "Имеет ли видеоплеер сочетания клавиш?",
TEXT: "Да. Пауза/Воспроизведение: пробел. Управление звуком: клавиши со стрелками вверх и вниз. Промотать видео вперед/назад: клавиши со стрелками влево и вправо. Длинная промотка:" +
" Клавиша Ctrl + клавиши со стрелками влево и вправо. Выключение/выключение полноэкранного режима: Клавиши Alt + Enter. Включение/выключение субтитров: клавиша S(«Ы»), Приглушение звука: M(«Ь»), Вернуться" +
" к предыдущему экрану: клавиши Delete или Backspace."
},
FAVORITE_GENRES: {
TITLE: "Как любимые жанры пользователя влияют на потоки?",
TEXT: "В процессе..."
},
USEFUL_LINKS: {
TITLE: "Полезные ссылки",
TEXT: "Тоже в процессе..."
}
}
});
});
|
/**
* angular-strap
* @version v2.3.2 - 2015-12-15
* @link http://mgcrea.github.io/angular-strap
* @author Olivier Louvignes <olivier@mg-crea.com> (https://github.com/mgcrea)
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
'use strict';
angular.module('mgcrea.ngStrap.aside').run([ '$templateCache', function($templateCache) {
$templateCache.put('aside/aside.tpl.html', '<div class="aside" tabindex="-1" role="dialog"><div class="aside-dialog"><div class="aside-content"><div class="aside-header" ng-show="title"><button type="button" class="close" ng-click="$hide()">×</button><h4 class="aside-title" ng-bind="title"></h4></div><div class="aside-body" ng-bind="content"></div><div class="aside-footer"><button type="button" class="btn btn-default" ng-click="$hide()">Close</button></div></div></div></div>');
} ]); |
'use strict';
var ScriptBase = require('../script-base.js');
var Generator = module.exports = ScriptBase;
Generator.prototype.typename = function() {
return 'utility';
};
Generator.prototype.typepath = function() {
return 'object/utility';
};
|
'use strict';
// Controller naming conventions should start with an uppercase letter
function HomeViewCtrl($scope) {
$scope.testVar = 'We are up and running!';
$scope.clientFeatures=[];
$scope.clientFeatures.push('AngularJs');
$scope.clientFeatures.push('Bootstrap');
$scope.clientFeatures.push('Angular-ui-router');
$scope.clientFeatures.push('Browserify');
$scope.serverFeatures=[];
$scope.serverFeatures.push('Node');
$scope.serverFeatures.push('Express.js');
$scope.serverFeatures.push('MongoDB');
$scope.serverFeatures.push('jsonwebtoken');
}
// $inject is necessary for minification. See http://bit.ly/1lNICde for explanation.
HomeViewCtrl.$inject = ['$scope'];
module.exports = HomeViewCtrl; |
var expect = require('chai').expect,
objectAssign = require('object-assign'),
_ = require('lodash'),
generate = require('../../../lib/data-generator.js'),
EventEmitter = require('events').EventEmitter;
var input = require('./data/input.js'),
output = require('./data/output.js');
/**
* Generates a natural positive number
*
* @returns {Number}
*/
function getRandomNumber() {
return _.random(0, 100);
}
/**
* Generates an array of random numbers
*
* @param {Number} n - The length of the array
*
* @returns {Array.<Number>}
*/
function generateArrayOfRandomNumbers(n) {
return _.times(n, function() { return getRandomNumber(); });
}
/**
* Generates suites (Mocha's describe)
*
* @param {Number} n - Number of suites
* @param {String} type - Nested or global
*
* @returns {Array.<Suite>}
*/
function generateSuites(n, type) {
var suites = [output.rootSuite];
for (var i = 0; i < n; i++) {
if (type === 'nested') {
suites.push(objectAssign({}, output.suite, {indent: i + 1},
{tests: []}));
} else {
suites.push(objectAssign({}, output.suite, {tests: []}));
}
}
return suites;
}
/**
* Generates tests (Mocha's it)
*
* @param {Number} n - Number of tests
* @param {String} type - Passed or failed
*
* @returns {Array.<Test>}
*/
function generateTests(n, type) {
var tests = [];
for (var i = 0; i < n; i++) {
if (type === 'passed') {
tests.push(objectAssign({}, output.passTest));
} else {
tests.push(objectAssign({}, output.failTest));
}
}
return tests;
}
describe('Data generator', function() {
var suiteProps = ['title', 'indent', 'tests'],
passTestProps = ['title', 'state', 'result', 'duration'],
failTestProps = ['title', 'state', 'result', 'error', 'duration'],
runner;
beforeEach(function() {
runner = new EventEmitter();
});
it('should work with files without tests', function(done) {
generate(runner, function(data) {
expect(data).to.be.deep.equal([output.rootSuite]);
done();
});
runner.emit('suite', input.rootSuite);
runner.emit('suite end', input.rootSuite);
runner.emit('end');
});
it('should generate a Test for each of Mocha\'s passed it', function(done) {
var randomNumber = getRandomNumber();
generate(runner, function(data) {
var tests = generateTests(randomNumber, 'passed'),
expected = [objectAssign({}, output.rootSuite, {tests: tests})];
expect(data).to.have.length(expected.length);
done();
});
runner.emit('suite', input.rootSuite);
for (var i = 0; i < randomNumber; i++) {
runner.emit('test end', input.passTest);
}
runner.emit('suite end', input.rootSuite);
runner.emit('end');
});
it('should generate a Test for each of Mocha\'s failed it', function(done) {
var randomNumber = getRandomNumber();
generate(runner, function(data) {
var tests = generateTests(randomNumber, 'failed'),
expected = [objectAssign({}, output.rootSuite, {tests: tests})];
expect(data).to.have.length(expected.length);
done();
});
runner.emit('suite', input.rootSuite);
for (var i = 0; i < randomNumber; i++) {
runner.emit('test end', input.failTest);
}
runner.emit('suite end', input.rootSuite);
runner.emit('end');
});
it('should generate a Suite for each of Mocha\'s describe', function(done) {
var randomNumber = getRandomNumber();
generate(runner, function(data) {
var expected = generateSuites(randomNumber, 'global');
expect(data).to.have.length(expected.length);
done();
});
runner.emit('suite', input.rootSuite);
for (var i = 0; i < randomNumber; i++) {
runner.emit('suite', input.suite);
runner.emit('suite end', input.suite);
}
runner.emit('suite end', input.rootSuite);
runner.emit('end');
});
suiteProps.forEach(function(prop) {
it('should contain the Suite "' + prop + '" property', function(done) {
generate(runner, function(data) {
expect(data[0][prop]).to.deep.equal(output.rootSuite[prop]);
done();
});
runner.emit('suite', input.rootSuite);
runner.emit('suite end', input.rootSuite);
runner.emit('end');
});
});
passTestProps.forEach(function(prop) {
it('should contain the pass Test "' + prop + '" property', function(done) {
generate(runner, function(data) {
expect(data[0].tests[0][prop]).to.be.deep.equal(output.passTest[prop]);
done();
});
runner.emit('suite', input.rootSuite);
runner.emit('test end', input.passTest);
runner.emit('suite end', input.rootSuite);
runner.emit('end');
});
});
failTestProps.forEach(function(prop) {
it('should contain the fail Test "' + prop + '" property', function(done) {
generate(runner, function(data) {
expect(data[0].tests[0][prop]).to.be.deep.equal(output.failTest[prop]);
done();
});
runner.emit('suite', input.rootSuite);
runner.emit('test end', input.failTest);
runner.emit('suite end', input.rootSuite);
runner.emit('end');
});
});
it('should indent nested suites properly', function(done) {
var randomNumber = getRandomNumber();
generate(runner, function(data) {
var expected = generateSuites(randomNumber, 'nested');
for (var i = 0; i <= randomNumber; i++) {
expect(data[i].indent).to.be.equal(expected[i].indent);
}
done();
});
runner.emit('suite', input.rootSuite);
for (var i = 0; i < randomNumber; i++) {
runner.emit('suite', input.suite);
}
for (var i = 0; i < randomNumber; i++) {
runner.emit('suite end', input.suite);
}
runner.emit('suite end', input.rootSuite);
runner.emit('end');
});
it('should maintain the order in which the tests are executed',
function(done) {
var n = getRandomNumber(),
// Each value is the number of tests of the suite i.
randomNumbers = generateArrayOfRandomNumbers(n + 1);
generate(runner, function(data) {
var expected = generateSuites(n, 'global');
for (var i = 0; i <= n; i++) {
expected[i].tests = generateTests(randomNumbers[i], 'passed');
// We are adding in the title an id only for testing purposes.
for (var j = 0; j < expected[i].tests.length; j++) {
expected[i].tests[j].title += j;
}
}
for (var i = 0; i <= n; i++) {
for (var j = 0; j < randomNumbers[i]; j++) {
expect(data[i].tests[j].title).to.be
.equal(expected[i].tests[j].title);
}
}
done();
});
runner.emit('suite', input.rootSuite);
for (var i = 0; i < randomNumbers[0]; i++) {
var test = objectAssign({}, input.passTest);
test.title += i;
runner.emit('test end', test);
}
for (var i = 1; i <= n; i++) {
runner.emit('suite', input.suite);
for (var j = 0; j < randomNumbers[i]; j++) {
var test = objectAssign({}, input.passTest);
test.title += j;
runner.emit('test end', test);
}
runner.emit('suite end');
}
runner.emit('suite end', input.rootSuite);
runner.emit('end');
});
});
|
// @flow
export { default as resolver } from './resolver';
export { default as defaultContext } from './resolverContext';
|
var pets = ['cat', 'dog', 'rat'];
for(var i = 0; i < pets.length; i++) {
pets[i] = pets[i] + 's';
}
console.log(pets);
|
var redis = require('redis');
var q = require('q');
var db = redis.createClient();
var dbPrefix = global.dbPrefix; // Set what Redis db prefix to use, based on environment (dev or production)
var userPrefix = dbPrefix + ':user:';
var timerPrefix = dbPrefix + ':timer:';
var idPrefix = dbPrefix + ':id_counter';
var user = module.exports = {};
user.newId = function() {
var deferred = q.defer();
db.incr(idPrefix, function(err, reply) {
if (err) deferred.reject(err);
else deferred.resolve(reply);
});
return deferred.promise;
};
user.exists = function(id) {
var userKey = userPrefix + id;
var deferred = q.defer();
db.exists(userKey, function(err, reply) {
if (err) deferred.reject(err);
else deferred.resolve(reply);
});
return deferred.promise;
};
user.get = function(id) {
var userKey = userPrefix + id;
var deferred = q.defer();
db.hgetall(userKey, function(err, reply) {
if (err) deferred.reject(err);
else deferred.resolve(reply);
});
return deferred.promise;
};
user.store = function(id, userObj) {
var userKey = userPrefix + id;
db.hmset(userKey, userObj);
};
user.delete = function(id) {
var userKey = userPrefix + id;
db.del(userKey);
};
user.checkTimer = function(id) {
var timerKey = timerPrefix + id;
var deferred = q.defer();
db.get(timerKey, function(err, reply) {
if (err) deferred.reject(err);
else deferred.resolve(reply);
});
return deferred.promise;
};
user.setTimer = function(id) {
var timerKey = timerPrefix + id;
var deferred = q.defer();
db.setex(timerKey, 900, 1, function(err, reply) {
if (err) deferred.reject(err);
else deferred.resolve(reply);
});
return deferred.promise;
}; |
module.exports = function (phoneBook, htmlRenderer, queryStringParser) {
return function (req, res) {
var query = queryStringParser.parse(req.url);
var sendPhoneBook = function () {
phoneBook.getAll(function (err, items) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(htmlRenderer.renderItems(items));
});
};
if (query.name && query.number) {
phoneBook.put(query.name, query.number, function () {
sendPhoneBook();
});
} else {
sendPhoneBook();
}
};
};
|
'use strict';
var port = process.env.PORT || 8000;
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var swaggerize = require('swaggerize-express');
var swaggerUi = require('swaggerize-ui'); // change one
var path = require('path');
var app = express();
var server = http.createServer(app);
app.use(bodyParser.json());
app.use(swaggerize({
api: path.resolve('./config/api.json'), // change two
handlers: path.resolve('./handlers'),
docspath: '/swagger/docs/v1' // change three
}));
// change four
app.use('/swagger', swaggerUi({
docs: '/swagger/docs/v1'
}));
server.listen(port, function () {
app.setHost(undefined); // change five
}); |
require('./panelGroup.component');
require('./panel.component');
require('./pagination.component');
require('./panelHeading.component');
require('./objectPanelBody.component');
require('./arrayPanelBody.component');
require('./mapPanelBody.component');
|
version https://git-lfs.github.com/spec/v1
oid sha256:fabf4c1efa49300a95ad0362e90bb6f4161e3c7b283e1c2dfc51b179a36463b2
size 562
|
var normalize = require("../lib/normalize");
var yaml = require("../lib/yaml");
var Plugins = require("../lib/plugins");
var async = require("async");
var fs = require("fs");
var path = require("path");
var chai = require("chai");
chai.should();
chai.config.showDiff = true;
var plugins = new Plugins();
describe("Normalize", function(done) {
run_normalization_tests("scripts", done);
});
describe("Normalize logical", function(done) {
run_normalization_tests("logical", done);
});
function run_normalization_tests(dir, done) {
if(process.env.OVERWRITE_RESULTS === "true") return overwrite_normalization_results(dir, done);
async.each(fs.readdirSync(path.join(__dirname, dir)), function(filename) {
if(path.extname(filename)===".normal") {
var compare = path.basename(filename, ".normal");
it(path.join(dir, compare), function(done) {
var to_normalize = yaml.loadFile(path.join(__dirname, dir, compare));
var expected = yaml.loadFile(path.join(__dirname, dir, filename));
var normalized = normalize(to_normalize, plugins);
normalized.should.deep.equal(expected, JSON.stringify(normalized));
done();
});
}
}, done);
}
function overwrite_normalization_results(dir, done) {
async.each(fs.readdirSync(path.join(__dirname, dir)), function(filename, inner_done) {
if(path.extname(filename)===".yml") {
var to_normalize = yaml.loadFile(path.join(__dirname, dir, filename));
var normalized = normalize(to_normalize, plugins);
fs.writeFile(path.join(__dirname, dir, filename + ".normal"), yaml.dump(normalized), inner_done);
}
}, done);
}
|
var express = require('express');
var fs = require('fs');
var io = require('socket.io');
var crypto = require('crypto');
var app = express.createServer();
var staticDir = express.static;
io = io.listen(app);
var opts = {
port: 1948,
baseDir : __dirname + '/../../'
};
io.sockets.on('connection', function(socket) {
socket.on('slidechanged', function(slideData) {
if (typeof slideData.secret == 'undefined' || slideData.secret == null || slideData.secret === '') return;
if (createHash(slideData.secret) === slideData.socketId) {
slideData.secret = null;
socket.broadcast.emit(slideData.socketId, slideData);
};
});
});
app.configure(function() {
[ 'css', 'js', 'plugin', 'lib' ].forEach(function(dir) {
app.use('/' + dir, staticDir(opts.baseDir + dir));
});
});
app.get("/", function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
fs.createReadStream(opts.baseDir + '/index.html').pipe(res);
});
app.get("/token", function(req,res) {
var ts = new Date().getTime();
var rand = Math.floor(Math.random() * 9999999);
var secret = ts.toString() + rand.toString();
res.send({secret: secret, socketId: createHash(secret)});
});
var createHash = function(secret) {
var cipher = crypto.createCipher('blowfish', secret);
return(cipher.final('hex'));
};
// Actually listen
app.listen(opts.port || null);
var brown = '\033[33m',
green = '\033[32m',
reset = '\033[0m';
console.log( brown + "reveal.js:" + reset + " Multiplex running on port " + green + opts.port + reset );
|
/*
* Guerilla
* Copyright 2015, Yahoo Inc.
* Copyrights licensed under the MIT License.
*
* Provides data and functionality to be used by tasks.
*/
var path = require('path');
var callsite = require('callsite');
var Task = require('./task');
var utilities = require('./utilities');
function Context (executor, job, result, device) {
var self = this;
self.bin_dir = path.join(__rootdir, 'bin');
self.output_dir = result.output_dir;
self.working_dir = job.getWorkingDir();
if (device) {
self.device = device;
}
var servicesDir = path.join(__rootdir, 'services');
self.services = {
AndroidMemoryService: require(servicesDir + '/android-memory'),
AndroidNetworkService: require(servicesDir + '/android-network'),
AndroidScreenshotService: require(servicesDir + '/android-screenshot'),
iOSSystemLogService: require(servicesDir + '/ios-system-log'),
LogcatService: require(servicesDir + '/logcat'),
APKToPackageNameService: require(servicesDir + '/apk-to-package-name'),
AppToBundleIdentifierService: require(servicesDir + '/app-to-bundle-identifier'),
FinderService: require(servicesDir + '/finder')
};
self.log = function (string, callback) {
result.log.apply(result, ['info', string, callback]);
};
self.output = function () {
return result.data || {};
};
self.createReport = function (config) {
result.addReport(config);
};
self.require = function () {
return require.apply(self, arguments);
};
self.exists = function (v) {
return utilities.exists(v);
};
self.runTask = function (config, callback) {
var task = new Task(config);
task.params.parent_task = path.basename(callsite()[1].getFileName());
executor.executeTask(task, function (errors) {
var error;
if (errors) error = new Error('Child task failed: ' + task.params.task);
callback(error);
});
};
self.addPostJobTask = function (config) {
executor.postJobPhase.tasks.unshift(new Task(config));
};
self.previous = function (callback) {
result.previous(function (error, previousResult) {
if (error || !previousResult) return callback(new Error(error));
var previousContext = new Context(executor, job, previousResult, previousResult.device);
callback(null, previousContext)
});
};
}
module.exports = Context; |
"use strict";
// debug.ts
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
/*
* Middleware for debugging HTTP requests and responses
*/
/*
The MIT License
Copyright (c) 2014-2021 Carl Ansley
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
const debug_1 = __importDefault(require("debug"));
/* eslint-disable @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/restrict-template-expressions */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function default_1(module) {
// set up logging
const log = (0, debug_1.default)(module);
if (!log.enabled) {
// logging not enabled for this module, return do-nothing middleware
return async (_, next) => next();
}
/* istanbul ignore next */
return async (context, next) => {
const startTime = Date.now();
const { method, url } = context.request;
await next();
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
const status = parseInt(context.status, 10);
const requestBody = typeof context.request.body === 'undefined' ? context.request.body : JSON.stringify(context.request.body);
const responseBody = typeof context.body === 'undefined' ? context.body : JSON.stringify(context.body);
const time = Date.now() - startTime;
if (typeof requestBody !== 'undefined' && typeof responseBody !== 'undefined') {
log(`${method} ${url} ${requestBody} -> ${status} ${responseBody} ${time}ms`);
}
if (typeof requestBody !== 'undefined' && typeof responseBody === 'undefined') {
log(`${method} ${url} ${requestBody} -> ${status} ${time}ms`);
}
if (typeof requestBody === 'undefined' && typeof responseBody !== 'undefined') {
log(`${method} ${url} -> ${status} ${responseBody} ${time}ms`);
}
if (typeof requestBody === 'undefined' && typeof responseBody === 'undefined') {
log(`${method} ${url} -> ${status} ${time}ms`);
}
};
}
exports.default = default_1;
/* eslint-enable @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/restrict-template-expressions */
//# sourceMappingURL=debug.js.map |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.