text
stringlengths 3
1.05M
|
|---|
# Copyright (c) 2021 Qualcomm Technologies, Inc.
# All Rights Reserved.
from quantization.adaround.adaround import apply_adaround_to_layer
from quantization.adaround.utils import (
AdaRoundInitMode,
AdaRoundMode,
AdaRoundActQuantMode,
AdaRoundLossType,
AdaRoundTempDecayType,
)
|
(function(root,factory){if(typeof exports==="object"&&exports){factory(exports);}else{var mustache={};factory(mustache);if(typeof define==="function"&&define.amd){define(mustache);}else{root.Mustache=mustache;}}}(this,function(mustache){var whiteRe=/\s*/;var spaceRe=/\s+/;var nonSpaceRe=/\S/;var eqRe=/\s*=/;var curlyRe=/\s*\}/;var tagRe=/#|\^|\/|>|\{|&|=|!/;var RegExp_test=RegExp.prototype.test;function testRegExp(re,string){return RegExp_test.call(re,string);}function isWhitespace(string){return!testRegExp(nonSpaceRe,string);}var Object_toString=Object.prototype.toString;var isArray=Array.isArray||function(obj){return Object_toString.call(obj)==='[object Array]';};function escapeRegExp(string){return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&");}var entityMap={"&":"&","<":"<",">":">",'"':'"',"'":''',"/":'/'};function escapeHtml(string){return String(string).replace(/[&<>"'\/]/g,function(s){return entityMap[s];});}function Scanner(string){this.string=string;this.tail=string;this.pos=0;}Scanner.prototype.eos=function(){return this.tail==="";};Scanner.prototype.scan=function(re){var match=this.tail.match(re);if(match&&match.index===0){this.tail=this.tail.substring(match[0].length);this.pos+=match[0].length;return match[0];}return"";};Scanner.prototype.scanUntil=function(re){var match,pos=this.tail.search(re);switch(pos){case-1:match=this.tail;this.pos+=this.tail.length;this.tail="";break;case 0:match="";break;default:match=this.tail.substring(0,pos);this.tail=this.tail.substring(pos);this.pos+=pos;}return match;};function Context(view,parent){this.view=view||{};this.parent=parent;this._cache={};}Context.make=function(view){return(view instanceof Context)?view:new Context(view);};Context.prototype.push=function(view){return new Context(view,this);};Context.prototype.lookup=function(name){var value=this._cache[name];if(!value){if(name=='.'){value=this.view;}else{var context=this;while(context){if(name.indexOf('.')>0){value=context.view;var names=name.split('.'),i=0;while(value&&i<names.length){value=value[names[i++]];}}else{value=context.view[name];}if(value!=null)break;context=context.parent;}}this._cache[name]=value;}if(typeof value==='function')value=value.call(this.view);return value;};function Writer(){this.clearCache();}Writer.prototype.clearCache=function(){this._cache={};this._partialCache={};};Writer.prototype.compile=function(template,tags){var fn=this._cache[template];if(!fn){var tokens=mustache.parse(template,tags);fn=this._cache[template]=this.compileTokens(tokens,template);}return fn;};Writer.prototype.compilePartial=function(name,template,tags){var fn=this.compile(template,tags);this._partialCache[name]=fn;return fn;};Writer.prototype.getPartial=function(name){if(!(name in this._partialCache)&&this._loadPartial){this.compilePartial(name,this._loadPartial(name));}return this._partialCache[name];};Writer.prototype.compileTokens=function(tokens,template){var self=this;return function(view,partials){if(partials){if(typeof partials==='function'){self._loadPartial=partials;}else{for(var name in partials){self.compilePartial(name,partials[name]);}}}return renderTokens(tokens,self,Context.make(view),template);};};Writer.prototype.render=function(template,view,partials){return this.compile(template)(view,partials);};function renderTokens(tokens,writer,context,template){var buffer='';var token,tokenValue,value;for(var i=0,len=tokens.length;i<len;++i){token=tokens[i];tokenValue=token[1];switch(token[0]){case'#':value=context.lookup(tokenValue);if(typeof value==='object'){if(isArray(value)){for(var j=0,jlen=value.length;j<jlen;++j){buffer+=renderTokens(token[4],writer,context.push(value[j]),template);}}else if(value){buffer+=renderTokens(token[4],writer,context.push(value),template);}}else if(typeof value==='function'){var text=template==null?null:template.slice(token[3],token[5]);value=value.call(context.view,text,function(template){return writer.render(template,context);});if(value!=null)buffer+=value;}else if(value){buffer+=renderTokens(token[4],writer,context,template);}break;case'^':value=context.lookup(tokenValue);if(!value||(isArray(value)&&value.length===0)){buffer+=renderTokens(token[4],writer,context,template);}break;case'>':value=writer.getPartial(tokenValue);if(typeof value==='function')buffer+=value(context);break;case'&':value=context.lookup(tokenValue);if(value!=null)buffer+=value;break;case'name':value=context.lookup(tokenValue);if(value!=null)buffer+=mustache.escape(value);break;case'text':buffer+=tokenValue;break;}}return buffer;}function nestTokens(tokens){var tree=[];var collector=tree;var sections=[];var token;for(var i=0,len=tokens.length;i<len;++i){token=tokens[i];switch(token[0]){case'#':case'^':sections.push(token);collector.push(token);collector=token[4]=[];break;case'/':var section=sections.pop();section[5]=token[2];collector=sections.length>0?sections[sections.length-1][4]:tree;break;default:collector.push(token);}}return tree;}function squashTokens(tokens){var squashedTokens=[];var token,lastToken;for(var i=0,len=tokens.length;i<len;++i){token=tokens[i];if(token){if(token[0]==='text'&&lastToken&&lastToken[0]==='text'){lastToken[1]+=token[1];lastToken[3]=token[3];}else{lastToken=token;squashedTokens.push(token);}}}return squashedTokens;}function escapeTags(tags){return[new RegExp(escapeRegExp(tags[0])+"\\s*"),new RegExp("\\s*"+escapeRegExp(tags[1]))];}function parseTemplate(template,tags){template=template||'';tags=tags||mustache.tags;if(typeof tags==='string')tags=tags.split(spaceRe);if(tags.length!==2)throw new Error('Invalid tags: '+tags.join(', '));var tagRes=escapeTags(tags);var scanner=new Scanner(template);var sections=[];var tokens=[];var spaces=[];var hasTag=false;var nonSpace=false;function stripSpace(){if(hasTag&&!nonSpace){while(spaces.length){delete tokens[spaces.pop()];}}else{spaces=[];}hasTag=false;nonSpace=false;}var start,type,value,chr,token;while(!scanner.eos()){start=scanner.pos;value=scanner.scanUntil(tagRes[0]);if(value){for(var i=0,len=value.length;i<len;++i){chr=value.charAt(i);if(isWhitespace(chr)){spaces.push(tokens.length);}else{nonSpace=true;}tokens.push(['text',chr,start,start+1]);start+=1;if(chr=='\n')stripSpace();}}if(!scanner.scan(tagRes[0]))break;hasTag=true;type=scanner.scan(tagRe)||'name';scanner.scan(whiteRe);if(type==='='){value=scanner.scanUntil(eqRe);scanner.scan(eqRe);scanner.scanUntil(tagRes[1]);}else if(type==='{'){value=scanner.scanUntil(new RegExp('\\s*'+escapeRegExp('}'+tags[1])));scanner.scan(curlyRe);scanner.scanUntil(tagRes[1]);type='&';}else{value=scanner.scanUntil(tagRes[1]);}if(!scanner.scan(tagRes[1]))throw new Error('Unclosed tag at '+scanner.pos);token=[type,value,start,scanner.pos];tokens.push(token);if(type==='#'||type==='^'){sections.push(token);}else if(type==='/'){if(sections.length===0)throw new Error('Unopened section "'+value+'" at '+start);var openSection=sections.pop();if(openSection[1]!==value)throw new Error('Unclosed section "'+openSection[1]+'" at '+start);}else if(type==='name'||type==='{'||type==='&'){nonSpace=true;}else if(type==='='){tags=value.split(spaceRe);if(tags.length!==2)throw new Error('Invalid tags at '+start+': '+tags.join(', '));tagRes=escapeTags(tags);}}var openSection=sections.pop();if(openSection)throw new Error('Unclosed section "'+openSection[1]+'" at '+scanner.pos);tokens=squashTokens(tokens);return nestTokens(tokens);}mustache.name="mustache.js";mustache.version="0.7.2";mustache.tags=["{{","}}"];mustache.Scanner=Scanner;mustache.Context=Context;mustache.Writer=Writer;mustache.parse=parseTemplate;mustache.escape=escapeHtml;var defaultWriter=new Writer();mustache.clearCache=function(){return defaultWriter.clearCache();};mustache.compile=function(template,tags){return defaultWriter.compile(template,tags);};mustache.compilePartial=function(name,template,tags){return defaultWriter.compilePartial(name,template,tags);};mustache.compileTokens=function(tokens,template){return defaultWriter.compileTokens(tokens,template);};mustache.render=function(template,view,partials){return defaultWriter.render(template,view,partials);};mustache.to_html=function(template,view,partials,send){var result=mustache.render(template,view,partials);if(typeof send==="function"){send(result);}else{return result;}};}));
|
from typing import Dict, Optional
from sharpy.managers.combat2 import MicroStep, Action, MoveType
from sc2 import UnitTypeId, AbilityId
from sc2.ids.buff_id import BuffId
from sc2.position import Point2
from sc2.unit import Unit
from sc2.units import Units
GRAVITON_BEAM_ENERGY = 50
class MicroPhoenixes(MicroStep):
def __init__(self):
self.allow_lift = False
# These unit types should be targets for graviton beam
self.lift_priority: Dict[UnitTypeId, int] = {
# Threaholds: 10 instant priority pickup
# 5 or above: Prefer lift to shooting actual enemies
# 0 - 4: Lift only if nothing to shoot
# negative number: Never try lifting
# Terran
UnitTypeId.SIEGETANK: 8,
UnitTypeId.SIEGETANKSIEGED: 10, # sieged tanks are much higher priority than unsieged
UnitTypeId.MULE: 6, # Would be nice to check it's remaining duration
UnitTypeId.SCV: 4,
UnitTypeId.WIDOWMINEBURROWED: 10,
UnitTypeId.WIDOWMINE: 8,
UnitTypeId.GHOST: 10,
UnitTypeId.REAPER: 4,
UnitTypeId.MARAUDER: 4,
UnitTypeId.MARINE: 3,
UnitTypeId.CYCLONE: 30,
UnitTypeId.BANSHEE: 30,
UnitTypeId.HELLION: 2,
UnitTypeId.HELLIONTANK: 1,
UnitTypeId.THOR: -1,
# Zerg
UnitTypeId.QUEEN: 3,
UnitTypeId.DRONE: 4,
UnitTypeId.HYDRALISK: 7,
UnitTypeId.BANELING: 6,
UnitTypeId.LURKERMP: 9,
UnitTypeId.LURKERMPBURROWED: 9,
UnitTypeId.INFESTOR: 10,
UnitTypeId.INFESTEDTERRAN: 1,
UnitTypeId.ROACH: 0,
UnitTypeId.LARVA: -1,
UnitTypeId.EGG: -1,
UnitTypeId.LOCUSTMP: -1,
UnitTypeId.BROODLING: -1,
UnitTypeId.ULTRALISK: -1,
# Protoss
UnitTypeId.SENTRY: 8,
UnitTypeId.PROBE: 4,
UnitTypeId.HIGHTEMPLAR: 10,
UnitTypeId.DISRUPTOR: 20,
UnitTypeId.DARKTEMPLAR: 9,
UnitTypeId.ADEPT: 4,
UnitTypeId.ZEALOT: 4,
UnitTypeId.STALKER: 2,
UnitTypeId.IMMORTAL: 15,
UnitTypeId.ARCHON: -1,
UnitTypeId.COLOSSUS: -1,
}
super().__init__()
def group_solve_combat(self, units: Units, current_command: Action) -> Action:
beaming_phoenixes = units.filter(
lambda p: p.orders and p.orders[0].ability.id == AbilityId.GRAVITONBEAM_GRAVITONBEAM
)
if beaming_phoenixes and len(beaming_phoenixes) > len(units) * 0.5:
self.allow_lift = False
else:
self.allow_lift = True
return current_command
def unit_solve_combat(self, unit: Unit, current_command: Action) -> Action:
if self.move_type == MoveType.DefensiveRetreat or self.move_type == MoveType.PanicRetreat:
if self.ready_to_shoot(unit):
closest = self.closest_units.get(unit.tag, None)
if closest:
real_range = self.unit_values.real_range(unit, closest)
if 0 < real_range < unit.distance_to(closest):
return Action(closest.position, False)
return current_command
if self.knowledge.unit_cache.own_in_range(unit.position, 10).amount >= 6:
close_enemies = self.cache.enemy_in_range(unit.position, 15).visible
has_energy = unit.energy > GRAVITON_BEAM_ENERGY
# Phoenixes are generally faster than the rest of the army
if close_enemies.filter(lambda u: u.is_flying).amount == 0:
if (self.in_danger(unit) or not has_energy) and self.group.ground_units:
# Regroup with the ground army
return self.evasive_move_to(self.group.center.position, unit)
if has_energy and self.allow_lift:
best_target: Optional[Unit] = None
best_score: float = 0
for enemy in close_enemies: # type: Unit
if enemy.is_flying or enemy.is_structure or enemy.has_buff(BuffId.GRAVITONBEAM):
continue
if self.move_type != MoveType.Harass and enemy.type_id in self.unit_values.worker_types:
# If we are not doing any harass, don't lift low priority workers up.
# We need to prioritize energy to actual combat units
continue
pos: Point2 = enemy.position
score = self.lift_priority.get(enemy.type_id, -1) + (1 - pos.distance_to(unit) / 10)
if score > best_score:
best_target = enemy
best_score = score
if best_target:
if best_score > 5 or not close_enemies.flying.exists:
self.print(
f"Phoenix at {unit.position} lifting {best_target.type_id} at {best_target.position}")
if unit.distance_to(best_target) > 8:
destination = self.knowledge.pathing_manager.find_influence_air_path(
unit.position, best_target.position
)
return Action(destination, False)
return Action(best_target, False, AbilityId.GRAVITONBEAM_GRAVITONBEAM)
if unit.energy > GRAVITON_BEAM_ENERGY * 3 and best_target:
if best_score > 3 or not close_enemies.flying.exists:
self.print(
f"Phoenix at {unit.position} lifting {best_target.type_id} at {best_target.position}")
if unit.distance_to(best_target) > 8:
destination = self.knowledge.pathing_manager.find_influence_air_path(
unit.position, best_target.position
)
return Action(destination, False)
return Action(best_target, False, AbilityId.GRAVITONBEAM_GRAVITONBEAM)
targets = self.enemies_near_by.flying.filter(lambda u: u.is_light)
if targets:
closest = targets.closest_to(unit)
if self.ready_to_shoot(unit):
return Action(closest, False)
else:
self.evasive_move_to(closest, unit)
targets = self.enemies_near_by.flying
if targets:
closest = targets.closest_to(unit)
if self.ready_to_shoot(unit):
return Action(closest, False)
else:
self.evasive_move_to(closest, unit)
if self.engage_ratio < 0.25 and self.can_engage_ratio < 0.25:
# Not in combat
return current_command
return current_command
def print(self, msg):
self.knowledge.print(f"[MicroPhoenixes] {msg}")
def in_danger(self, unit: Unit):
enemy_anti_air_units = self.knowledge.unit_cache.enemy_in_range(unit.position3d, 11) \
.filter(lambda u: u.can_attack_air).visible
for AA in enemy_anti_air_units:
if AA.position.distance_to(unit) < AA.air_range + 3 and unit.shield_health_percentage <= 0.4:
return True
return False
def evasive_move_to(self, position_to, unit: Unit):
enemy_anti_air_units = self.knowledge.unit_cache.enemy_in_range(unit.position3d, 11) \
.filter(lambda u: u.can_attack_air).visible
if enemy_anti_air_units.exists:
position = unit.position3d
for aa in enemy_anti_air_units:
distance = unit.distance_to(aa.position3d)
amount_of_evade = 15 - distance
if distance > 0:
position = position.towards(aa, - amount_of_evade)
# after the for loop, position is the best vector away from enemy
distance_to_best_evade_point = unit.distance_to(position)
should_go = position.towards(position_to, distance_to_best_evade_point)
return Action(should_go, False)
else:
return Action(position_to, False)
|
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h("path", {
d: "M20 18v-1c1.1 0 1.99-.9 1.99-2L22 5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2v1H0v2h24v-2h-4zM4 5h16v10H4V5z"
}), 'LaptopWindows');
|
import { ErrorFactory, contains, deepExtend, createSubscribe, isBrowser } from '@firebase/util';
import { __assign } from 'tslib';
import { Component } from '@firebase/component';
import * as modularAPIs from '@firebase/app';
import { deleteApp, _addComponent, _addOrOverwriteComponent, _DEFAULT_ENTRY_NAME, registerVersion } from '@firebase/app';
import { Logger } from '@firebase/logger';
/**
* @license
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Global context object for a collection of services using
* a shared authentication state.
*
* marked as internal because it references internal types exported from @firebase/app
* @internal
*/
var FirebaseAppImpl = /** @class */ (function () {
function FirebaseAppImpl(_delegate, firebase) {
var _this = this;
this._delegate = _delegate;
this.firebase = firebase;
// add itself to container
_addComponent(_delegate, new Component('app-compat', function () { return _this; }, "PUBLIC" /* PUBLIC */));
this.container = _delegate.container;
}
Object.defineProperty(FirebaseAppImpl.prototype, "automaticDataCollectionEnabled", {
get: function () {
return this._delegate.automaticDataCollectionEnabled;
},
set: function (val) {
this._delegate.automaticDataCollectionEnabled = val;
},
enumerable: false,
configurable: true
});
Object.defineProperty(FirebaseAppImpl.prototype, "name", {
get: function () {
return this._delegate.name;
},
enumerable: false,
configurable: true
});
Object.defineProperty(FirebaseAppImpl.prototype, "options", {
get: function () {
return this._delegate.options;
},
enumerable: false,
configurable: true
});
FirebaseAppImpl.prototype.delete = function () {
var _this = this;
return new Promise(function (resolve) {
_this._delegate.checkDestroyed();
resolve();
}).then(function () {
_this.firebase.INTERNAL.removeApp(_this.name);
return deleteApp(_this._delegate);
});
};
/**
* Return a service instance associated with this app (creating it
* on demand), identified by the passed instanceIdentifier.
*
* NOTE: Currently storage and functions are the only ones that are leveraging this
* functionality. They invoke it by calling:
*
* ```javascript
* firebase.app().storage('STORAGE BUCKET ID')
* ```
*
* The service name is passed to this already
* @internal
*/
FirebaseAppImpl.prototype._getService = function (name, instanceIdentifier) {
var _a;
if (instanceIdentifier === void 0) { instanceIdentifier = _DEFAULT_ENTRY_NAME; }
this._delegate.checkDestroyed();
// Initialize instance if InstatiationMode is `EXPLICIT`.
var provider = this._delegate.container.getProvider(name);
if (!provider.isInitialized() &&
((_a = provider.getComponent()) === null || _a === void 0 ? void 0 : _a.instantiationMode) === "EXPLICIT" /* EXPLICIT */) {
provider.initialize();
}
// getImmediate will always succeed because _getService is only called for registered components.
return provider.getImmediate({
identifier: instanceIdentifier
});
};
/**
* Remove a service instance from the cache, so we will create a new instance for this service
* when people try to get it again.
*
* NOTE: currently only firestore uses this functionality to support firestore shutdown.
*
* @param name The service name
* @param instanceIdentifier instance identifier in case multiple instances are allowed
* @internal
*/
FirebaseAppImpl.prototype._removeServiceInstance = function (name, instanceIdentifier) {
if (instanceIdentifier === void 0) { instanceIdentifier = _DEFAULT_ENTRY_NAME; }
this._delegate.container
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.getProvider(name)
.clearInstance(instanceIdentifier);
};
/**
* @param component the component being added to this app's container
* @internal
*/
FirebaseAppImpl.prototype._addComponent = function (component) {
_addComponent(this._delegate, component);
};
FirebaseAppImpl.prototype._addOrOverwriteComponent = function (component) {
_addOrOverwriteComponent(this._delegate, component);
};
FirebaseAppImpl.prototype.toJSON = function () {
return {
name: this.name,
automaticDataCollectionEnabled: this.automaticDataCollectionEnabled,
options: this.options
};
};
return FirebaseAppImpl;
}());
// TODO: investigate why the following needs to be commented out
// Prevent dead-code elimination of these methods w/o invalid property
// copying.
// (FirebaseAppImpl.prototype.name && FirebaseAppImpl.prototype.options) ||
// FirebaseAppImpl.prototype.delete ||
// console.log('dc');
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var _a;
var ERRORS = (_a = {},
_a["no-app" /* NO_APP */] = "No Firebase App '{$appName}' has been created - " +
'call Firebase App.initializeApp()',
_a["invalid-app-argument" /* INVALID_APP_ARGUMENT */] = 'firebase.{$appName}() takes either no argument or a ' +
'Firebase App instance.',
_a);
var ERROR_FACTORY = new ErrorFactory('app-compat', 'Firebase', ERRORS);
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Because auth can't share code with other components, we attach the utility functions
* in an internal namespace to share code.
* This function return a firebase namespace object without
* any utility functions, so it can be shared between the regular firebaseNamespace and
* the lite version.
*/
function createFirebaseNamespaceCore(firebaseAppImpl) {
var apps = {};
// // eslint-disable-next-line @typescript-eslint/no-explicit-any
// const components = new Map<string, Component<any>>();
// A namespace is a plain JavaScript Object.
var namespace = {
// Hack to prevent Babel from modifying the object returned
// as the firebase namespace.
// @ts-ignore
__esModule: true,
initializeApp: initializeAppCompat,
// @ts-ignore
app: app,
registerVersion: modularAPIs.registerVersion,
setLogLevel: modularAPIs.setLogLevel,
onLog: modularAPIs.onLog,
// @ts-ignore
apps: null,
SDK_VERSION: modularAPIs.SDK_VERSION,
INTERNAL: {
registerComponent: registerComponentCompat,
removeApp: removeApp,
useAsService: useAsService,
modularAPIs: modularAPIs
}
};
// Inject a circular default export to allow Babel users who were previously
// using:
//
// import firebase from 'firebase';
// which becomes: var firebase = require('firebase').default;
//
// instead of
//
// import * as firebase from 'firebase';
// which becomes: var firebase = require('firebase');
// eslint-disable-next-line @typescript-eslint/no-explicit-any
namespace['default'] = namespace;
// firebase.apps is a read-only getter.
Object.defineProperty(namespace, 'apps', {
get: getApps
});
/**
* Called by App.delete() - but before any services associated with the App
* are deleted.
*/
function removeApp(name) {
delete apps[name];
}
/**
* Get the App object for a given name (or DEFAULT).
*/
function app(name) {
name = name || modularAPIs._DEFAULT_ENTRY_NAME;
if (!contains(apps, name)) {
throw ERROR_FACTORY.create("no-app" /* NO_APP */, { appName: name });
}
return apps[name];
}
// @ts-ignore
app['App'] = firebaseAppImpl;
/**
* Create a new App instance (name must be unique).
*
* This function is idempotent. It can be called more than once and return the same instance using the same options and config.
*/
function initializeAppCompat(options, rawConfig) {
if (rawConfig === void 0) { rawConfig = {}; }
var app = modularAPIs.initializeApp(options, rawConfig);
if (contains(apps, app.name)) {
return apps[app.name];
}
var appCompat = new firebaseAppImpl(app, namespace);
apps[app.name] = appCompat;
return appCompat;
}
/*
* Return an array of all the non-deleted FirebaseApps.
*/
function getApps() {
// Make a copy so caller cannot mutate the apps list.
return Object.keys(apps).map(function (name) { return apps[name]; });
}
function registerComponentCompat(component) {
var componentName = component.name;
var componentNameWithoutCompat = componentName.replace('-compat', '');
if (modularAPIs._registerComponent(component) &&
component.type === "PUBLIC" /* PUBLIC */) {
// create service namespace for public components
// The Service namespace is an accessor function ...
var serviceNamespace = function (appArg) {
if (appArg === void 0) { appArg = app(); }
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (typeof appArg[componentNameWithoutCompat] !== 'function') {
// Invalid argument.
// This happens in the following case: firebase.storage('gs:/')
throw ERROR_FACTORY.create("invalid-app-argument" /* INVALID_APP_ARGUMENT */, {
appName: componentName
});
}
// Forward service instance lookup to the FirebaseApp.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return appArg[componentNameWithoutCompat]();
};
// ... and a container for service-level properties.
if (component.serviceProps !== undefined) {
deepExtend(serviceNamespace, component.serviceProps);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
namespace[componentNameWithoutCompat] = serviceNamespace;
// Patch the FirebaseAppImpl prototype
// eslint-disable-next-line @typescript-eslint/no-explicit-any
firebaseAppImpl.prototype[componentNameWithoutCompat] =
// TODO: The eslint disable can be removed and the 'ignoreRestArgs'
// option added to the no-explicit-any rule when ESlint releases it.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var serviceFxn = this._getService.bind(this, componentName);
return serviceFxn.apply(this, component.multipleInstances ? args : []);
};
}
return component.type === "PUBLIC" /* PUBLIC */
? // eslint-disable-next-line @typescript-eslint/no-explicit-any
namespace[componentNameWithoutCompat]
: null;
}
// Map the requested service to a registered service name
// (used to map auth to serverAuth service when needed).
function useAsService(app, name) {
if (name === 'serverAuth') {
return null;
}
var useService = name;
return useService;
}
return namespace;
}
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Return a firebase namespace object.
*
* In production, this will be called exactly once and the result
* assigned to the 'firebase' global. It may be called multiple times
* in unit tests.
*/
function createFirebaseNamespace() {
var namespace = createFirebaseNamespaceCore(FirebaseAppImpl);
namespace.INTERNAL = __assign(__assign({}, namespace.INTERNAL), { createFirebaseNamespace: createFirebaseNamespace,
extendNamespace: extendNamespace,
createSubscribe: createSubscribe,
ErrorFactory: ErrorFactory,
deepExtend: deepExtend });
/**
* Patch the top-level firebase namespace with additional properties.
*
* firebase.INTERNAL.extendNamespace()
*/
function extendNamespace(props) {
deepExtend(namespace, props);
}
return namespace;
}
var firebase$1 = createFirebaseNamespace();
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var logger = new Logger('@firebase/app-compat');
var name = "@firebase/app-compat";
var version = "0.1.9";
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function registerCoreComponents(variant) {
// Register `app` package.
registerVersion(name, version, variant);
}
/**
* @license
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Firebase Lite detection
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (isBrowser() && self.firebase !== undefined) {
logger.warn("\n Warning: Firebase is already defined in the global scope. Please make sure\n Firebase library is only loaded once.\n ");
// eslint-disable-next-line
var sdkVersion = self.firebase.SDK_VERSION;
if (sdkVersion && sdkVersion.indexOf('LITE') >= 0) {
logger.warn("\n Warning: You are trying to load Firebase while using Firebase Performance standalone script.\n You should load Firebase Performance with this instance of Firebase to avoid loading duplicate code.\n ");
}
}
var firebase = firebase$1;
registerCoreComponents();
export { firebase as default };
//# sourceMappingURL=index.esm5.js.map
|
/*##############################################################################
# HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
############################################################################## */
define([
"dojo/_base/declare",
"dojo/_base/lang",
"dojo/i18n",
"dojo/i18n!./nls/hpcc",
"dijit/registry",
"dgrid/OnDemandGrid",
"dgrid/Keyboard",
"dgrid/Selection",
"dgrid/editor",
"dgrid/extensions/ColumnResizer",
"dgrid/extensions/DijitRegistry",
"hpcc/GridDetailsWidget",
"hpcc/ws_access",
"hpcc/ESPUtil"
], function (declare, lang, i18n, nlsHPCC,
registry,
OnDemandGrid, Keyboard, Selection, editor, ColumnResizer, DijitRegistry,
GridDetailsWidget, WsAccess, ESPUtil) {
return declare("MemberOfWidget", [GridDetailsWidget], {
i18n: nlsHPCC,
gridTitle: nlsHPCC.title_MemberOf,
idProperty: "__hpcc_id",
// Hitched Actions ---
_onRefresh: function (args) {
this.grid.refresh();
},
// Implementation ---
init: function (params) {
if (this.inherited(arguments))
return;
this.store = WsAccess.CreateGroupsStore(params.username);
this.grid.setStore(this.store);
this._refreshActionState();
},
createGrid: function (domID) {
var retVal = new declare([OnDemandGrid, Keyboard, ColumnResizer, DijitRegistry, ESPUtil.GridHelper])({
store: this.store,
columns: {
isMember: editor({
label: "",
width: 27,
editor: "checkbox",
autoSave: true
}),
name: {
label: this.i18n.GroupName,
sortable: true
}
}
}, domID);
return retVal;
},
refreshActionState: function (selection) {
registry.byId(this.id + "Open").set("disabled", true);
}
});
});
|
(function(root) {
var toString = Function.prototype.toString;
function fnBody(fn) {
return toString.call(fn).replace(/^[^{]*{\s*/,'').replace(/\s*}[^}]*$/,'');
}
function isClass(fn) {
return (typeof fn === 'function' &&
(/^class(?:\s|{)/.test(toString.call(fn)) ||
(/^.*classCallCheck\(/.test(fnBody(fn)))) // babel.js
);
}
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = isClass;
}
exports.isClass = isClass;
} else if (typeof define === 'function' && define.amd) {
define([], function() {
return isClass;
});
} else {
root.isClass = isClass;
}
})(this);
|
/**
* @license Copyright (c) 2003-2022, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/* globals ClassicEditor, console, window, document */
import { CS_CONFIG } from '@ckeditor/ckeditor5-cloud-services/tests/_utils/cloud-services-config';
ClassicEditor
.create( document.querySelector( '#snippet-image-upload' ), {
cloudServices: CS_CONFIG,
ui: {
viewportOffset: {
top: window.getViewportTopOffsetConfig()
}
}
} )
.then( editor => {
window.editor = editor;
window.attachTourBalloon( {
target: window.findToolbarItem( editor.ui.view.toolbar,
item => item.buttonView && item.buttonView.label && item.buttonView.label === 'Insert image' ),
text: 'Click to insert an image or paste image URL directly into the editor.',
editor
} );
} )
.catch( err => {
console.error( err.stack );
} );
|
import React from "react"
import styled from "styled-components"
import { Link } from "gatsby"
const FooterContainer = styled.div`
display: flex;
align-items: center;
justify-content: center;
margin-top: 70px;
font-weight: 700;
font-size: 16px;
@media (min-width: 600px) {
height: 100px;
}
`
const InnerFooter = styled.div`
width: ${({ theme }) => theme.sizes.desktop.mainArea};
display: flex;
flex-direction: column;
align-items: center;
height: 100px;
padding: 15px 0;
@media (min-width: 1024px) {
align-items: center;
justify-content: space-between;
flex-direction: row;
}
`
const Copy = styled.div`
color: #000000;
flex: 1;
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: flex-start;
@media (min-width: 600px) {
flex-direction: row;
}
> :not(:last-child) {
margin-right: 40px;
}
a {
color: black;
text-decoration: none;
}
`
const Links = styled.div`
display: flex;
color: #000000;
flex-direction: column;
justify-content: flex-end;
@media (min-width: 600px) {
flex-direction: row;
}
> a {
color: black;
text-decoration: none;
&:first-of-type {
margin-right: 40px;
}
}
`
export const Footer = () => (
<FooterContainer>
<InnerFooter>
<Copy>
<span>2020 Planet Joy</span>
<span>
<a href="mailto:spreadonejoy@gmail.com">spreadonejoy@gmail.com</a>
</span>
<span>
built by{" "}
<a
href="https://dcrestini.me"
target="_blank"
rel="noopener noreferrer"
>
Davide Crestini
</a>
</span>
</Copy>
<Links>
<a
href="https://www.instagram.com/the_planetjoy/"
target="blank"
rel="noopener noreferrer"
>
Instagram
</a>
<Link to="/privacy-policy">Privacy Policy</Link>
</Links>
</InnerFooter>
</FooterContainer>
)
|
/*
Copyright 2019 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { at } from 'lodash';
import { SiteReasonEnum } from 'app/services/enums';
export default function makeLicense(json) {
const [reason, raw, payload, payloadExpiration, ] = at(json,
[
'reason',
'license.raw',
'license.payload',
'license.payload.expiration',
]
);
if(!payload){
return null;
}
const isValid = reason === SiteReasonEnum.INVALID_LICENSE;
return {
raw,
info: {
...payload,
signature: '',
expiration: new Date(payloadExpiration).toGMTString()
},
status: {
isActive: !isValid,
isError: isValid,
}
}
}
|
#!/usr/bin/env python
import io
import os
import sys
from setuptools import find_packages, setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
os.system('python setup.py bdist_wheel upload')
sys.exit()
readme = io.open('README.rst', 'r', encoding='utf-8').read()
setup(
name='asyncy-platform-engine',
description='The engine of the Asyncy platform',
long_description=readme,
author='Asyncy',
author_email='noreply@asyncy.com',
version='0.0.2',
packages=find_packages(),
tests_require=[
'pytest',
'pytest-cov',
'pytest-mock',
'pytest-asyncio'
],
setup_requires=['pytest-runner'],
install_requires=[
'prometheus-client==0.2.0',
'tornado==5.0.2',
'click==7.0',
'frustum==0.0.6',
'raven==6.9.0',
'storyscript==0.9.0',
'ujson==1.35',
'certifi>=2018.8.24',
'psycopg2==2.7.5',
'google-cloud-logging==1.9.0'
],
classifiers=[
'Environment :: Console',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3'
],
entry_points="""
[console_scripts]
asyncy-server=asyncy.Service:Service.main
"""
)
|
(function() { const icons = { "material/editor/format-bold": "M31.2 21.58c1.93-1.35 3.3-3.53 3.3-5.58 0-4.51-3.49-8-8-8H14v28h14.08c4.19 0 7.42-3.4 7.42-7.58 0-3.04-1.73-5.63-4.3-6.84zM20 13h6c1.66 0 3 1.34 3 3s-1.34 3-3 3h-6v-6zm7 18h-7v-6h7c1.66 0 3 1.34 3 3s-1.34 3-3 3z" };
if (JSC) {
JSC.internal.registerIcons(icons);
}
})();
|
"""
Django settings for purnkleen project.
Generated by 'django-admin startproject' using Django 1.11.7.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
from configparser import RawConfigParser
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
config = RawConfigParser()
config.read(os.path.join(BASE_DIR, 'config', 'settings_production.ini'))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config.get('key', 'SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['www.purnkleen.com', 'purnkleen.com']
EMAIL_HOST = config.get('email', 'EMAIL_HOST')
EMAIL_HOST_USER = config.get('email', 'EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = config.get('email', 'EMAIL_HOST_PASSWORD')
EMAIL_PORT = config.get('email', 'EMAIL_PORT')
EMAIL_USE_TLS = config.get('email', 'EMAIL_USE_TLS')
DEFAULT_FROM_EMAIL = config.get('email', 'DEFAULT_FROM_EMAIL')
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_countries',
'crispy_forms',
'rest_framework',
'bootstrap3',
'stdimage',
'accounts',
'employees',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'purnkleen.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'purnkleen.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': config.get('database', 'DATABASE_ENGINE'),
'NAME': config.get('database', 'DATABASE_NAME'),
'USER': config.get('database', 'DATABASE_USER'),
'PASSWORD': config.get('database', 'DATABASE_PASSWORD'),
'HOST': config.get('database', 'DATABASE_HOST'),
'PORT': config.get('database', 'DATABASE_PORT'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
# Don't do this in Production. Use a CDN.
STATICFILES_DIRS = [
# Will not be served, long-term storage.
os.path.join(BASE_DIR, "static-storage"),
]
# Will be served.
STATIC_ROOT = '/home/romri/webapps/purnkleen_static_root/'
MEDIA_ROOT = '/home/romri/webapps/purnkleen_media_root/'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# Django Registration settings
ACCOUNT_ACTIVATION_DAYS = 7
REGISTRATION_AUTO_LOGIN = True
REGISTRATION_EMAIL_HTML = False
# LOGGING
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'ERROR',
'class': 'logging.FileHandler',
'filename': os.path.join(BASE_DIR, "pnk_debug.log"),
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'ERROR',
'propagate': True,
},
},
}
|
from imutils.perspective import four_point_transform
import cv2
import numpy as np
import argparse
import imutils
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True,
help = "Path to the image to be scanned")
args = vars(ap.parse_args())
# Load image, grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread(args["image"])
ratio = image.shape[0] / 500.0
orig = image.copy()
image = imutils.resize(image, height = 500)
##(2) convert to hsv-space, then split the channels
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
h,s,v = cv2.split(hsv)
##(3) threshold the S channel using adaptive method(`THRESH_OTSU`) or fixed thresh
th, threshed = cv2.threshold(s, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
##(4) find all the external contours on the threshed S
#_, cnts, _ = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
_, cnts, _ = cv2.findContours(threshed, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
canvas = image.copy()
#cv2.drawContours(canvas, cnts, -1, (0,255,0), 1)
## sort and choose the largest contour
cnts = sorted(cnts, key = cv2.contourArea, reverse=True)
cnt = cnts[0]
## approx the contour, so the get the corner points
arclen = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.02* arclen, True)
print(approx)
cv2.drawContours(canvas, [cnt], -1, (255,0,0), 1, cv2.LINE_AA)
cv2.imshow("contour", canvas)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.drawContours(canvas, [approx], -1, (0, 0, 255), 1, cv2.LINE_AA)
cv2.imshow("approx_contour", canvas)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Calculate angles
xs = [num[0][0] for num in approx]
ys = [num[0][1] for num in approx]
angles = np.arctan([
(ys[0]-ys[1]) / (xs[0]-xs[1]),
(ys[1]-ys[2]) / (xs[1]-xs[2]),
])
# rotation angle
rotation_angle = abs(np.rad2deg(angles[0]))
print('rotation angle: ', rotation_angle)
# tilted angle
titled_angle = abs(np.rad2deg(angles[0] - angles[1]))
print('tilted angle: ', titled_angle)
# image area ratio
area = cv2.contourArea(cnt)
image_area = image.shape[0] * image.shape[1]
print(image_area)
print('area ratio: ', area / image_area)
# ## Ok, you can see the result as tag(6)
# cv2.imwrite("detected.png", canvas)
|
import Axios from 'axios';
import config from 'config';
const axios = Axios.create({
baseURL: config.api.baseURL,
timeout: config.api.timeout
});
async function wrapError(asyncFunc, ...args) {
try {
const response = await asyncFunc(...args);
// check for server success indication or collection of results
if (!response.data.success && !Array.isArray(response.data)) {
throw Error(response.data);
}
return response;
} catch (error) {
if (error.response && error.response.data.message) {
// server responded with status code different from 2xx
throw new Error(error.response.data.message);
}
throw new Error('unable to perform network request');
}
}
export function post(path, data) {
return wrapError(axios.post, path, data);
}
export function get(path, data) {
return wrapError(axios.get, path, data);
}
export function setAuthorizationHeader(token) {
if (token) {
Axios.defaults.headers.common.Authorization = `Bearer ${token}`;
} else {
delete Axios.defaults.headers.common.Authorization;
}
}
|
Meteor.startup(function () {
// code to run on server at startup
//UXLab.data.devices.insert({name: "testi-ipad", deviceid: "q3hv7gnoifyhi", live: true});
});
Meteor.methods({
createDevice:function(_deviceid){
UXLab.data.devices.insert({name: "unknown", deviceid: _deviceid, running: 0, description: "Unknown device", promote: false});
},
removeDevice:function(id){
if(Meteor.user()) {
UXLab.data.devices.remove({_id: id});
}
}
});
Meteor.publish("devices", function () {
return UXLab.data.devices.find({});
});
UXLab.data.devices.allow({
update: function(userId, doc, fieldnames){
return (Meteor.user() && fieldnames.length == 1 && (fieldnames[0] == "name" || fieldnames[0] == "promote") );
}
});
|
import tensorflow as tf
import numpy as np
from models import num_of_classes
if tf.__version__ == '1.13.1' or tf.__version__ == '1.15.0':
from keras.layers.merge import concatenate
from keras.layers import Activation
import keras.backend as K
if tf.__version__ == '2.2.0' or tf.__version__ == '2.0.0' or tf.__version__ == '2.2.0-rc2':
import tensorflow.keras.backend as K
from tensorflow.keras.layers import Activation, concatenate
import tensorflow_addons as tfa
'''
In this on the fly lossses the ground truths are converted on they fly into the categorical type and only
hybrid and tri brid losses are doing that if you wann use only one loss then convert them first
'''
#-------------------------------------------------------------Dice Loss Function-----------------------
num_class = num_of_classes()
def weighted_bce_loss(y_true, y_pred, weight):
# avoiding overflow
epsilon = 1e-7
y_pred = K.clip(y_pred, epsilon, 1. - epsilon)
logit_y_pred = K.log(y_pred / (1. - y_pred))
#logit_y_pred = y_pred
loss = (1. - y_true) * logit_y_pred + (1. + (weight - 1.) * y_true) * \
(K.log(1. + K.exp(-K.abs(logit_y_pred))) + K.maximum(-logit_y_pred, 0.))
return K.sum(loss) / K.sum(weight)
def weighted_dice_loss(y_true, y_pred, weight):
smooth = 1.
w, m1, m2 = weight * weight, y_true, y_pred
intersection = (m1 * m2)
score = (2. * K.sum(w * intersection) + smooth) / (K.sum(w * (m1**2)) + K.sum(w * (m2**2)) + smooth) # Uptill here is Dice Loss with squared
loss = 1. - K.sum(score) #Soft Dice Loss
return loss
def Weighted_BCEnDice_loss(y_true, y_pred):
if num_class < 2:
y_pred = tf.keras.activations.sigmoid(y_pred)
else:
y_pred = tf.keras.activations.softmax(y_pred, axis=-1)
y_true = y_true * 255#(num_class + 1)
y_true = K.squeeze(y_true, 3)
y_true = tf.cast(y_true, "int32")
y_true = tf.one_hot(y_true, num_class, axis=-1)
if num_class==2:
y_true = y_true[:,:,:,0:1]
y_true = K.cast(y_true, 'float32')
y_pred = K.cast(y_pred, 'float32')
# if we want to get same size of output, kernel size must be odd number
averaged_mask = K.pool2d(
y_true, pool_size=(11, 11), strides=(1, 1), padding='same', pool_mode='avg')
border = K.cast(K.greater(averaged_mask, 0.005), 'float32') * K.cast(K.less(averaged_mask, 0.995), 'float32')
weight = K.ones_like(averaged_mask)
w0 = K.sum(weight)
weight += border * 2
w1 = K.sum(weight)
weight *= (w0 / w1)
loss = weighted_dice_loss(y_true, y_pred, weight) + weighted_bce_loss(y_true, y_pred, weight)
return loss
#%%
def focal_CE(y_true, y_pred):
if num_class < 2:
y_pred = tf.keras.activations.sigmoid(y_pred)
else:
y_pred = tf.keras.activations.softmax(y_pred, axis=-1)
y_true = y_true * (num_class + 1)
y_true = K.squeeze(y_true, 3)
y_true = tf.cast(y_true, "int32")
y_true = tf.one_hot(y_true, num_class, axis=-1)
if num_class==2:
y_true = y_true[:,:,:,0:1]
y_true = K.cast(y_true, 'float32')
y_pred = K.cast(y_pred, 'float32')
loss = tfa.losses.sigmoid_focal_crossentropy(y_true = y_true, y_pred = y_pred,
alpha = 0.25, gamma = 2.0, from_logits = True)+sigmoid_cross_entropy_balanced(y_pred, y_true)
return loss
#%%
def HED_loss(y_true, y_pred):
y_true = y_true * (num_class + 1)
y_true = K.squeeze(y_true, 3)
y_true = tf.cast(y_true, "int32")
y_true = tf.one_hot(y_true, num_class, axis=-1)
if num_class==2:
y_true = y_true[:,:,:,0:1]
y_true = K.cast(y_true, 'float32')
y_pred = K.cast(y_pred, 'float32')
loss = sigmoid_cross_entropy_balanced(y_pred, y_true)
return loss
def sigmoid_cross_entropy_balanced(logits, label, name='cross_entropy_loss'):
"""
From:
https://github.com/moabitcoin/holy-edge/blob/master/hed/losses.py
Implements Equation [2] in https://arxiv.org/pdf/1504.06375.pdf
Compute edge pixels for each training sample and set as pos_weights to
tf.nn.weighted_cross_entropy_with_logits
"""
y = tf.cast(label, tf.float32)
count_neg = tf.reduce_sum(1. - y)
count_pos = tf.reduce_sum(y)
# Equation [2]
beta = count_neg / (count_neg + count_pos)
# Equation [2] divide by 1 - beta
pos_weight = beta / (1 - beta)
if tf.__version__ == '1.13.1' or tf.__version__ == '1.15.0':
cost = tf.nn.weighted_cross_entropy_with_logits(logits=logits, targets=y, pos_weight=pos_weight)
if tf.__version__ == '2.2.0' or tf.__version__ == '2.0.0' or tf.__version__ == '2.2.0-rc2':
cost = tf.nn.weighted_cross_entropy_with_logits(logits=logits, labels=y, pos_weight=pos_weight)
# Multiply by 1 - beta
cost = tf.reduce_mean(cost * (1 - beta))
# check if image has no edge pixels return 0 else return complete error function
return tf.where(tf.equal(count_pos, 0.0), 0.0, cost, name=name)
#--------------------------------------------------------------Focal Loss---------------------------------------------
gamma=2.
alpha=.25
epsilon = 1.e-9
def focal_loss(y_true, y_pred):
y_pred = tf.keras.activations.softmax(y_pred, axis=-1)
y_true = y_true * (num_class + 1)
y_true = K.squeeze(y_true, 3)
y_true = tf.cast(y_true, "int32")
y_true = tf.one_hot(y_true, num_class, axis=-1)
if num_class==2:
y_true = y_true[:,:,:,0:1]
y_true = K.cast(y_true, 'float32')
y_pred = K.cast(y_pred, 'float32')
model_out = tf.add(y_pred, epsilon)
ce = tf.multiply(y_true, -tf.log(model_out))
weight = tf.multiply(y_true, tf.pow(tf.subtract(1., model_out), gamma))
fl = tf.multiply(alpha, tf.multiply(weight, ce))
reduced_fl = tf.reduce_max(fl, axis=1)
loss = tf.reduce_mean(reduced_fl) #+ multi_iou_loss(y_true, y_pred, smooth=1)
return loss
#---------------------------------------------------multi_iou_loss----------------------------------------
def multi_iou_loss(y_true, y_pred, smooth=1):
intersection = K.sum(K.abs(y_true * y_pred), axis=[1,2])
union = K.sum(y_true,[1,2])+K.sum(y_pred,[1,2])-intersection
iou = K.mean((intersection + smooth) / (union + smooth), axis=[1,0])
loss = 1-iou
return loss
#%%
def focal_loss2(hm_pred, hm_true):
pos_mask = tf.cast(tf.equal(hm_true, 1), tf.float32)
neg_mask = tf.cast(tf.less(hm_true,1), tf.float32)
neg_weights = tf.pow(1 - hm_true, 4)
pos_loss = -tf.log(tf.clip_by_value(hm_pred, 1e-4, 1. -1e-4)) * tf.pow(1-hm_pred, 2) * pos_mask
neg_loss = -tf.log(tf.clip_by_value(1-hm_pred, 1e-4, 1. -1e-4)) * tf.pow(hm_pred, 2) * neg_weights * neg_mask
num_pos = tf.reduce_sum(pos_mask)
pos_loss = tf.reduce_sum(pos_loss)
neg_loss = tf.reduce_sum(neg_loss)
cls_loss = tf.cond(tf.greater(num_pos, 0), lambda :(pos_loss + neg_loss)/num_pos, lambda :neg_loss)
return cls_loss
def soft_dice_loss(y_true, y_pred, epsilon=1e-7):
'''
y_true: b x X x Y( x Z...) x c One hot encoding of ground truth
y_pred: b x X x Y( x Z...) x c Network output, must sum to 1 over c channel (such as after softmax)
'''
# skip the batch and class axis for calculating Dice score
axes = tuple(range(1, len(y_pred.shape)-1))
numerator = 2. * K.sum(y_pred * y_true, axes)
denominator = K.sum(K.square(y_pred) + K.square(y_true), axes)
return 1 - K.mean(numerator / (denominator + epsilon)) # average over classes and batch
from keras.losses import binary_crossentropy
def built_loss(y_true, y_pred):
y_pred = tf.keras.activations.softmax(y_pred, axis=-1)
y_true = y_true * (num_class + 1)
y_true = K.squeeze(y_true, 3)
y_true = tf.cast(y_true, "int32")
y_true = tf.one_hot(y_true, num_class, axis=-1)
if num_class==2:
y_true = y_true[:,:,:,0:1]
y_true = K.cast(y_true, 'float32')
y_pred = K.cast(y_pred, 'float32')
loss1 = binary_crossentropy(y_true, y_pred)
#loss2 = soft_dice_loss(y_true, y_pred, epsilon=1e-6)
loss = loss1# + loss2
return loss
|
import unittest
from importlib import resources
from . import data01
from .resources import util
class ContentsTests:
expected = {
'__init__.py',
'binary.file',
'subdirectory',
'utf-16.file',
'utf-8.file',
}
def test_contents(self):
with util.suppress_known_deprecation():
assert self.expected <= set(resources.contents(self.data))
class ContentsDiskTests(ContentsTests, unittest.TestCase):
def setUp(self):
self.data = data01
class ContentsZipTests(ContentsTests, util.ZipSetup, unittest.TestCase):
pass
class ContentsNamespaceTests(ContentsTests, unittest.TestCase):
expected = {
# no __init__ because of namespace design
# no subdirectory as incidental difference in fixture
'binary.file',
'utf-16.file',
'utf-8.file',
}
def setUp(self):
from . import namespacedata01
self.data = namespacedata01
|
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads_v1/proto/enums/criterion_category_channel_availability_mode.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='google/ads/googleads_v1/proto/enums/criterion_category_channel_availability_mode.proto',
package='google.ads.googleads.v1.enums',
syntax='proto3',
serialized_options=_b('\n!com.google.ads.googleads.v1.enumsB-CriterionCategoryChannelAvailabilityModeProtoP\001ZBgoogle.golang.org/genproto/googleapis/ads/googleads/v1/enums;enums\242\002\003GAA\252\002\035Google.Ads.GoogleAds.V1.Enums\312\002\035Google\\Ads\\GoogleAds\\V1\\Enums\352\002!Google::Ads::GoogleAds::V1::Enums'),
serialized_pb=_b('\nVgoogle/ads/googleads_v1/proto/enums/criterion_category_channel_availability_mode.proto\x12\x1dgoogle.ads.googleads.v1.enums\x1a\x1cgoogle/api/annotations.proto\"\xd4\x01\n,CriterionCategoryChannelAvailabilityModeEnum\"\xa3\x01\n(CriterionCategoryChannelAvailabilityMode\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0b\n\x07UNKNOWN\x10\x01\x12\x10\n\x0c\x41LL_CHANNELS\x10\x02\x12!\n\x1d\x43HANNEL_TYPE_AND_ALL_SUBTYPES\x10\x03\x12$\n CHANNEL_TYPE_AND_SUBSET_SUBTYPES\x10\x04\x42\x82\x02\n!com.google.ads.googleads.v1.enumsB-CriterionCategoryChannelAvailabilityModeProtoP\x01ZBgoogle.golang.org/genproto/googleapis/ads/googleads/v1/enums;enums\xa2\x02\x03GAA\xaa\x02\x1dGoogle.Ads.GoogleAds.V1.Enums\xca\x02\x1dGoogle\\Ads\\GoogleAds\\V1\\Enums\xea\x02!Google::Ads::GoogleAds::V1::Enumsb\x06proto3')
,
dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,])
_CRITERIONCATEGORYCHANNELAVAILABILITYMODEENUM_CRITERIONCATEGORYCHANNELAVAILABILITYMODE = _descriptor.EnumDescriptor(
name='CriterionCategoryChannelAvailabilityMode',
full_name='google.ads.googleads.v1.enums.CriterionCategoryChannelAvailabilityModeEnum.CriterionCategoryChannelAvailabilityMode',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='UNSPECIFIED', index=0, number=0,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='UNKNOWN', index=1, number=1,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='ALL_CHANNELS', index=2, number=2,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='CHANNEL_TYPE_AND_ALL_SUBTYPES', index=3, number=3,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='CHANNEL_TYPE_AND_SUBSET_SUBTYPES', index=4, number=4,
serialized_options=None,
type=None),
],
containing_type=None,
serialized_options=None,
serialized_start=201,
serialized_end=364,
)
_sym_db.RegisterEnumDescriptor(_CRITERIONCATEGORYCHANNELAVAILABILITYMODEENUM_CRITERIONCATEGORYCHANNELAVAILABILITYMODE)
_CRITERIONCATEGORYCHANNELAVAILABILITYMODEENUM = _descriptor.Descriptor(
name='CriterionCategoryChannelAvailabilityModeEnum',
full_name='google.ads.googleads.v1.enums.CriterionCategoryChannelAvailabilityModeEnum',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
],
extensions=[
],
nested_types=[],
enum_types=[
_CRITERIONCATEGORYCHANNELAVAILABILITYMODEENUM_CRITERIONCATEGORYCHANNELAVAILABILITYMODE,
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=152,
serialized_end=364,
)
_CRITERIONCATEGORYCHANNELAVAILABILITYMODEENUM_CRITERIONCATEGORYCHANNELAVAILABILITYMODE.containing_type = _CRITERIONCATEGORYCHANNELAVAILABILITYMODEENUM
DESCRIPTOR.message_types_by_name['CriterionCategoryChannelAvailabilityModeEnum'] = _CRITERIONCATEGORYCHANNELAVAILABILITYMODEENUM
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
CriterionCategoryChannelAvailabilityModeEnum = _reflection.GeneratedProtocolMessageType('CriterionCategoryChannelAvailabilityModeEnum', (_message.Message,), dict(
DESCRIPTOR = _CRITERIONCATEGORYCHANNELAVAILABILITYMODEENUM,
__module__ = 'google.ads.googleads_v1.proto.enums.criterion_category_channel_availability_mode_pb2'
,
__doc__ = """Describes channel availability mode for a criterion availability -
whether the availability is meant to include all advertising channels,
or a particular channel with all its channel subtypes, or a channel with
a certain subset of channel subtypes.
""",
# @@protoc_insertion_point(class_scope:google.ads.googleads.v1.enums.CriterionCategoryChannelAvailabilityModeEnum)
))
_sym_db.RegisterMessage(CriterionCategoryChannelAvailabilityModeEnum)
DESCRIPTOR._options = None
# @@protoc_insertion_point(module_scope)
|
import random
from sqlalchemy import exc
from sqlalchemy.sql import func
from flask import url_for, request, jsonify, Blueprint, current_app
from src import db
from src.lib import urlsafe_base64
from src.lib.auth import authenticate
from src.blueprints.errors import server_error, bad_request, \
not_found, error_response
from src.blueprints.messages.models import Notification
from src.blueprints.posts.models import Post
from src.blueprints.posts.schema import PostSchema
posts = Blueprint('posts', __name__, url_prefix='/posts')
@posts.route('/ping', methods=['GET'])
def ping():
return {'message': 'Post Route!'}
@posts.route('/featured', methods=['GET'])
def get_featured_posts():
try:
res = Post.query.filter(Post.comment_id.is_(None)).all()
posts = random.sample(res, k=5)
except Exception:
return server_error('Something went wrong, please try again.')
return jsonify(PostSchema(
many=True, only=('id', 'body', 'author.profile')).dump(posts))
@posts.route('/<int:post_id>', methods=['GET'])
@authenticate
def get_post(user, post_id):
try:
post = Post.find_by_id(post_id)
if not post:
return not_found('Post not found')
except Exception:
return server_error('Something went wrong, please try again.')
else:
post_dict = post.to_dict(user)
post_dict['isLiked'] = post.is_liked_by(user)
if user.id != post.author.id:
post_dict['author']['isFollowing'] = user.is_following(post.author)
return jsonify(post_dict)
@posts.route('/explore', methods=['GET'])
@authenticate
def get_posts(user):
feed = request.args.get('feed')
cursor = request.args.get('cursor')
items_per_page = current_app.config['ITEMS_PER_PAGE']
nextCursor = None
query = ''
try:
sorted_posts = Post.get_by_reactions().subquery()
top_posts = db.session.query(Post, sorted_posts.c.sequence).join(
sorted_posts, sorted_posts.c.id == Post.id).order_by(
sorted_posts.c.sequence.desc())
latest_posts = Post.query.filter(
Post.comment_id.is_(None)).order_by(Post.created_on.desc())
except Exception as e:
db.session.rollback()
print(e)
return server_error('An unexpected error occured, please try again.')
if cursor == '0' and feed == 'latest':
query = latest_posts.limit(items_per_page + 1).all()
elif cursor == '0' and feed == 'top':
query = top_posts.limit(items_per_page + 1).all()
else:
if feed == 'latest':
cursor = urlsafe_base64(cursor, from_base64=True)
query = latest_posts.filter(
Post.created_on < cursor).limit(items_per_page + 1).all()
else:
cursor = urlsafe_base64(cursor, from_base64=True)
query = top_posts.filter(sorted_posts.c.sequence < cursor).limit(
items_per_page + 1).all()
if len(query) > items_per_page:
nextCursor = urlsafe_base64(
query[items_per_page - 1].created_on.isoformat()) \
if feed == 'latest' else urlsafe_base64(
str(query[items_per_page - 1][1]))
posts = [post.to_dict(user) for post in query[:items_per_page]] \
if feed == 'latest' else \
[post[0].to_dict(user) for post in query[:items_per_page]]
return {
'data': posts,
'nextCursor': nextCursor
}
@posts.route('', methods=['GET'])
@authenticate
def posts_feed(user):
latest = request.args.get('latest')
top = request.args.get('top')
cursor = request.args.get('cursor')
items_per_page = current_app.config['ITEMS_PER_PAGE']
nextCursor = None
query = ''
try:
followed_posts = user.get_followed_posts().subquery()
posts_reactions = Post.get_reactions().subquery()
top_followed_posts = db.session.query(
followed_posts, func.row_number().over(
order_by=posts_reactions.c.reactions).label(
'sequence')).outerjoin(posts_reactions,
followed_posts.c.posts_id ==
posts_reactions.c.id).subquery()
top_posts = db.session.query(Post, top_followed_posts.c.sequence).join(
Post, top_followed_posts.c.posts_id == Post.id).order_by(
top_followed_posts.c.sequence.desc())
latest_posts = db.session.query(Post, followed_posts.c.posts_id).join(
Post, Post.id == followed_posts.c.posts_id).order_by(
Post.created_on.desc())
except Exception as e:
db.session.rollback()
print(e)
return server_error('An unexpected error occured, please try again.')
if cursor == '0' and latest:
query = latest_posts.limit(items_per_page + 1).all()
elif cursor == '0' and top:
query = top_posts.limit(items_per_page + 1).all()
else:
if latest:
cursor = urlsafe_base64(cursor, from_base64=True)
query = latest_posts.filter(
Post.created_on < cursor).limit(items_per_page + 1).all()
else:
cursor = urlsafe_base64(cursor, from_base64=True)
query = top_posts.filter(
top_followed_posts.c.sequence < cursor).limit(
items_per_page + 1).all()
if len(query) > items_per_page:
nextCursor = urlsafe_base64(
query[items_per_page - 1][0].created_on.isoformat()) \
if latest else urlsafe_base64(
str(query[items_per_page - 1][1]))
return {
'data': [post[0].to_dict(user) for post in query[:items_per_page]],
'nextCursor': nextCursor
}
@posts.route('/<int:post_id>/comments', methods=['POST'])
@posts.route('', methods=['POST'])
@authenticate
def create_post(user, post_id=None):
req_data = request.get_json()
if not req_data:
return bad_request("No request data provided")
post = Post()
post.body = req_data.get('post')
post.user_id = user.id
db.session.add(post)
if post_id:
post.comment_id = post_id
parent = Post.find_by_id(post_id)
db.session.add(user.add_notification(subject='comment',
item_id=post.id, id=parent.author.id, post_id=parent.id))
else:
post_notifs = []
for u in user.followers.all():
post_notifs.append(user.add_notification(
subject='post', item_id=post.id, id=u.id, post_id=post.id))
db.session.add_all(post_notifs)
try:
post.save()
except (exc.IntegrityError, ValueError):
db.session.rollback()
return server_error('Something went wrong, please try again.')
else:
response = jsonify(post.to_dict(user))
response.status_code = 201
response.headers['Location'] = url_for(
'posts.get_post', post_id=post.id)
return response
@posts.route('/<int:post_id>', methods=['DELETE'])
@authenticate
def delete_post(user, post_id):
post = Post.find_by_id(post_id)
if not post:
return not_found('Post not found.')
if post.user_id != user.id:
return error_response(401, "You cannot delete someone else's post.")
post_notif = Notification.find_by_attr(subject='post', item_id=post.id)
comment_notif = Notification.find_by_attr(
subject='comment', item_id=post.id)
[db.session.delete(notif) for notif in post_notif] if post_notif \
else db.session.delete(comment_notif)
try:
post.delete()
except (exc.IntegrityError, ValueError):
db.session.rollback()
return server_error('Something went wrong, please try again.')
else:
return {'message': 'Post was successfuly deleted.'}
@posts.route('/<int:post_id>/likes', methods=['POST'])
@authenticate
def update_like(user, post_id):
post = Post.find_by_id(post_id)
if not post:
return not_found('Post not found')
try:
if post.is_liked_by(user):
post.likes.remove(user)
db.session.delete(
Notification.find_by_attr(subject='like', item_id=post.id))
else:
post.likes.append(user)
db.session.add(user.add_notification(
'like', item_id=post.id, id=post.author.id, post_id=post.id))
post.save()
except (exc.IntegrityError, ValueError):
db.session.rollback()
return server_error('Something went wrong, please try again.')
else:
return jsonify(post.to_dict(user))
@posts.route('/<int:post_id>/comments', methods=['GET'])
@authenticate
def get_post_comments(user, post_id):
post = Post.find_by_id(post_id)
if not post:
return not_found('Post not found.')
cursor = request.args.get('cursor')
items_per_page = current_app.config['ITEMS_PER_PAGE']
nextCursor = None
query = ''
if cursor == '0':
query = post.comments.order_by(
Post.created_on.desc()).limit(items_per_page + 1).all()
else:
cursor = urlsafe_base64(cursor, from_base64=True)
query = post.comments.order_by(
Post.created_on.desc()).filter(
Post.created_on < cursor).limit(items_per_page + 1).all()
if len(query) > items_per_page:
nextCursor = urlsafe_base64(
query[items_per_page - 1].created_on.isoformat())
comments = []
for c in query[:items_per_page]:
comment = c.to_dict(user)
comment['parent'] = PostSchema(
only=('id', 'body', 'author',)).dump(c.parent)
comments.append(comment)
return {
'data': comments,
'nextCursor': nextCursor
}
|
const model = require('../../models-modular/categories/categories.js');
const supergoose = require('../supergoose.js');
describe('Categories Model (Modular)', () => {
// How will you handle both the happy path and edge cases in these tests?
it('can create() a new category', () => {
let test = { name : 'test1 name', description : 'test1 description' };
return model.create( test )
.then( obj => {
Object.keys( test ).forEach( key => {
expect( obj[key] === test[key] ).toEqual(true);
});
});
});
it('can get() a category', () => {
let test = { name : 'test2 name', description : 'test2 description' };
return model.create( test )
.then( obj => {
return model.get( obj._id );
})
.then( obj => {
Object.keys( test ).forEach( key => {
expect( obj[key] === test[key] ).toEqual(true);
});
});
});
it('can get() all categories', () => {
let test1 = { name : 'test1 name', description : 'test1 description' };
let test2 = { name : 'test2 name', description : 'test2 description' };
let test3 = { name : 3, description : 3 };
return model.create( test1 )
.then( () => {
return model.create( test2 )
})
.then( () => {
return model.create( test3 )
})
.then( () => {
return model.get();
})
.then( response => {
expect(response.count === 5).toEqual(true);
})
});
it('can update() a category', () => {
let test = { name : 'test3 name', description : 'test3 description' };
return model.get()
.then( list => {
let id = list.results[4]._id;
return model.update( id, test );
})
.then( updated => {
Object.keys( test ).forEach( key => {
expect(updated[key] === test[key]).toEqual(true);
});
return model.get()
})
.then( updatedList => {
Object.keys( test ).forEach( key => {
expect( updatedList.results[4][key] === test[key] ).toEqual(true);
})
});
});
it('can delete() a category', () => {
let test = { name : 'deleteme', description : 'i exist to be deleted :(' };
return model.create( test )
.then( obj => {
return model.get( obj._id )
})
.then( obj => {
return model.delete( obj._id )
})
.then( () => {
return model.get();
})
.then( allResults => {
allResults.results.forEach( obj => {
Object.keys( test ).forEach( key => {
expect(obj[key] === test[key]).toEqual(false);
});
});
});
});
});
|
import {NameModel} from "../name.model.js";
class ShipSeasonalCgTypeModel {
constructor({time, name, id} = {time: {}}) {
this.id = id;
this.name = NameModel.build(name);
this.time = {};
if (time) {
this.time.ja_jp = time.ja_jp || '';
this.time.en_us = time.en_us || '';
this.time.zh_cn = time.zh_cn || '';
} else {
this.time = {ja_jp: '', en_us: '', zh_cn: ''};
}
}
static build(cgType = {}) {
return new ShipSeasonalCgTypeModel(cgType);
}
}
export {ShipSeasonalCgTypeModel};
|
import _ from 'underscore';
import doctrine from 'doctrine-standalone';
import replaceSynonyms from './synonymService';
/**
* Parse the JSDoc and turn them into pretty object, if received a "final-form" object - we will just pass it
* @param {Object} libraryDocs mapping between component name
*/
export function parseDocumentation(libraryDocs) {
let docs = {};
const componentsNames = _.keys(libraryDocs);
for (let i = 0, l = componentsNames.length; i < l; i++) {
const name = componentsNames[i];
let doc = libraryDocs[name];
let parsedDoc;
if (typeof doc === 'string') {
let ast = doctrine.parse(doc, {unwrap: true, recoverable: true, sloppy: true});
parsedDoc = replaceSynonyms(prettifyAst(ast));
} else {
parsedDoc = doc; // already an object
}
docs[name] = parsedDoc;
}
return docs;
}
function prettifyAst({tags}) {
let doc = {};
for (let i in tags) {
let tag = tags[i];
doc[tag.title] = doc[tag.title] || [];
doc[tag.title].push(tag);
}
return doc;
}
|
/**
* Originally copied from https://github.com/cucumber/bool/tree/master/javascript
* and modified for this project needs.
*
* A node visitor to traverse and process AST. This is mainly used to test
* validity of expressions and TOKEN_VARs visited.
*/
if(typeof LForms === 'undefined') {
window.LForms = {};
}
(function (LForms) {
LForms.Evaluator = function () {
"use strict";
var self = this;
/**
* Process the node. Tests tree traversal with the list of valid nodes to visit,
* and evaluates the expression. Any unlisted nodes visited evaluates to false.
* @param node - Node in context
* @param vars - Array of valid TOKEN_VARs to visit. Any unlisted nodes
* are invalid.
* @returns {boolean}
*/
this.visit = function (node, vars) {
var ret = false;
switch (node.token.type) {
case 'TOKEN_STR':
ret = vars.indexOf(node.token.value) != -1;
break;
case 'TOKEN_AND':
ret = self.evaluate(node.left, vars) && self.evaluate(node.right, vars);
break;
case 'TOKEN_OR':
ret = self.evaluate(node.left, vars) || self.evaluate(node.right, vars);
break;
case 'comparisonOp':
ret = self.evaluate(node.left, vars) && self.evaluate(node.right, vars);
switch (node.token.value) {
case '=':
ret = ret ? (node.left.token.value === node.right.token.value ? true : false) : ret;
break;
case '<':
ret = ret ? (node.left.token.value < node.right.token.value ? true : false) : ret;
break;
case '>':
ret = ret ? (node.left.token.value > node.right.token.value ? true : false) : ret;
break;
case '>=':
ret = ret ? (node.left.token.value >= node.right.token.value ? true : false) : ret;
break;
case '<=':
ret = ret ? (node.left.token.value <= node.right.token.value ? true : false) : ret;
break;
}
break;
case 'TOKEN_NOT':
ret = !self.evaluate(node.operand, vars);
break;
}
return ret;
};
/**
* Evaluate and traverse the node further down the tree
* @param node - Node in context
* @param vars - Array of possible variables under this node.
* Mainly for testing the extracted variables.
* @returns {boolean}
*/
this.evaluate = function(node, vars) {
return node.accept(self, vars);
};
}
})(LForms);
|
#!/usr/bin/env python
"""The setup script."""
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = []
test_requirements = ['pytest>=3']
{%- set license_classifiers = {
'MIT license': 'License :: OSI Approved :: MIT License',
'BSD license': 'License :: OSI Approved :: BSD License',
'ISC license': 'License :: OSI Approved :: ISC License (ISCL)',
'Apache Software License 2.0': 'License :: OSI Approved :: Apache Software License',
'GNU General Public License v3': 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)'
} %}
setup(
author="{{ cookiecutter.full_name.replace('\"', '\\\"') }}",
author_email='{{ cookiecutter.email }}',
python_requires='>=3.6',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
{%- if cookiecutter.open_source_license in license_classifiers %}
'{{ license_classifiers[cookiecutter.open_source_license] }}',
{%- endif %}
'Natural Language :: English',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
description="{{ cookiecutter.project_short_description }}",
{%- if 'no' not in cookiecutter.command_line_interface|lower %}
entry_points={
'console_scripts': [
'{{ cookiecutter.project_slug }}={{ cookiecutter.project_slug }}.cli:main',
],
},
{%- endif %}
install_requires=requirements,
{%- if cookiecutter.open_source_license in license_classifiers %}
license="{{ cookiecutter.open_source_license }}",
{%- endif %}
long_description=readme + '\n\n' + history,
include_package_data=True,
keywords='{{ cookiecutter.project_slug }}',
name='{{ cookiecutter.project_slug }}',
packages=find_packages(include=['{{ cookiecutter.project_slug }}', '{{ cookiecutter.project_slug }}.*']),
test_suite='tests',
tests_require=test_requirements,
url='https://github.com/{{ cookiecutter.github_username }}/{{ cookiecutter.project_slug }}',
version='{{ cookiecutter.version }}',
zip_safe=False,
)
|
import React from "react"
// import '../assets/scss/components/product-hero.module.scss'
import { graphql } from 'gatsby';
import Layout from "../components/layout"
import SearchResult from "../components/search-results"
import SEO from '../components/seo';
const products = ({ data, nodeType }) => (
<Layout menuType = "relative" nodeType={nodeType}>
<SEO title="Search Results" description="Search Results" />
<SearchResult/>
</Layout>
)
export default products
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""A class representing a window for displaying one or more stimuli"""
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2021 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
from __future__ import absolute_import, division, print_function
import ctypes
import os
import sys
import weakref
import atexit
from itertools import product
# from builtins import map
from builtins import object
from builtins import range
from builtins import str
from past.builtins import basestring
from collections import deque
from psychopy.contrib.lazy_import import lazy_import
from psychopy import colors, event
import math
# from psychopy.clock import monotonicClock
# try to find avbin (we'll overload pyglet's load_library tool and then
# add some paths)
from ..colors import Color, colorSpaces
haveAvbin = False
# on windows try to load avbin now (other libs can interfere)
if sys.platform == 'win32':
# make sure we also check in SysWOW64 if on 64-bit windows
if 'C:\\Windows\\SysWOW64' not in os.environ['PATH']:
os.environ['PATH'] += ';C:\\Windows\\SysWOW64'
try:
from pyglet.media import avbin
haveAvbin = True
except ImportError:
haveAvbin = False
# either avbin isn't installed or scipy.stats has been imported
# (prevents avbin loading)
except AttributeError:
# avbin is not found, causing exception in pyglet 1.2??
# (running psychopy 1.81 standalone on windows 7):
#
# File "C:\Program Files (x86)\PsychoPy2\lib\site-packages\
# pyglet\media\avbin.py", line 158, in <module>
# av.avbin_get_version.restype = ctypes.c_int
# AttributeError: 'NoneType' object has no attribute
# 'avbin_get_version'
haveAvbin = False
except Exception:
# WindowsError on some systems
# AttributeError if using avbin5 from pyglet 1.2?
haveAvbin = False
# for pyglet 1.3
if not haveAvbin:
try:
from pyglet.media.sources import avbin
haveAvbin = True
except ImportError:
haveAvbin = False
except AttributeError:
haveAvbin = False
except Exception:
haveAvbin = False
import psychopy # so we can get the __path__
from psychopy import core, platform_specific, logging, prefs, monitors
import psychopy.event
from . import backends
# tools must only be imported *after* event or MovieStim breaks on win32
# (JWP has no idea why!)
from psychopy.tools.attributetools import attributeSetter, setAttribute
from psychopy.tools.arraytools import val2array
from psychopy.tools.monitorunittools import convertToPix
import psychopy.tools.viewtools as viewtools
import psychopy.tools.gltools as gltools
from .text import TextStim
from .grating import GratingStim
from .helpers import setColor
from . import globalVars
try:
from PIL import Image
except ImportError:
import Image
import numpy
from psychopy.core import rush
reportNDroppedFrames = 5 # stop raising warning after this
# import pyglet.gl, pyglet.window, pyglet.image, pyglet.font, pyglet.event
from . import shaders as _shaders
try:
from pyglet import media
havePygletMedia = True
except Exception:
havePygletMedia = False
# lazy_import puts pygame into the namespace but delays import until needed
lazy_import(globals(), "import pygame")
DEBUG = False
IOHUB_ACTIVE = False
retinaContext = None # only needed for retina-ready displays
class OpenWinList(list):
"""Class to keep keep track of windows that have been opened.
Uses a list of weak references so that we don't stop the window
being deleted.
"""
def append(self, item):
list.append(self, weakref.ref(item))
def remove(self, item):
for ref in self:
obj = ref()
if obj is None or item == obj:
list.remove(self, ref)
openWindows = core.openWindows = OpenWinList() # core needs this for wait()
class Window(object):
"""Used to set up a context in which to draw objects,
using either `pyglet <http://www.pyglet.org>`_,
`pygame <http://www.pygame.org>`_, or `glfw <https://www.glfw.org>`_.
The pyglet backend allows multiple windows to be created, allows the user
to specify which screen to use (if more than one is available, duh!) and
allows movies to be rendered.
The GLFW backend is a new addition which provides most of the same features
as pyglet, but provides greater flexibility for complex display
configurations.
Pygame may still work for you but it's officially deprecated in this
project (we won't be fixing pygame-specific bugs).
"""
def __init__(self,
size=(800, 600),
pos=None,
color=(0, 0, 0),
colorSpace='rgb',
rgb=None,
dkl=None,
lms=None,
fullscr=None,
allowGUI=None,
monitor=None,
bitsMode=None,
winType=None,
units=None,
gamma=None,
blendMode='avg',
screen=0,
viewScale=None,
viewPos=None,
viewOri=0.0,
waitBlanking=True,
allowStencil=False,
multiSample=False,
numSamples=2,
stereo=False,
name='window1',
checkTiming=True,
useFBO=False,
useRetina=True,
autoLog=True,
gammaErrorPolicy='raise',
bpc=(8, 8, 8),
depthBits=8,
stencilBits=8,
backendConf=None):
"""
These attributes can only be set at initialization. See further down
for a list of attributes which can be changed after initialization
of the Window, e.g. color, colorSpace, gamma etc.
Parameters
----------
size : array-like of int
Size of the window in pixels [x, y].
pos : array-like of int
Location of the top-left corner of the window on the screen [x, y].
color : `rray-like of float
Color of background as [r, g, b] list or single value. Each gun can
take values between -1.0 and 1.0.
fullscr : bool or None
Create a window in 'full-screen' mode. Better timing can be achieved
in full-screen mode.
allowGUI : bool or None
If set to False, window will be drawn with no frame and no buttons
to close etc., use `None` for value from preferences.
winType : str or None
Set the window type or back-end to use. If `None` then PsychoPy will
revert to user/site preferences.
monitor : :class:`~psychopy.monitors.Monitor` or None
The monitor to be used during the experiment. If `None` a default
monitor profile will be used.
units : str or None
Defines the default units of stimuli drawn in the window (can be
overridden by each stimulus). Values can be *None*, 'height' (of the
window), 'norm' (normalised), 'deg', 'cm', 'pix'. See :ref:`units`
for explanation of options.
screen : int
Specifies the physical screen that stimuli will appear on ('pyglet'
and 'glfw' `winType` only). Values can be >0 if more than one screen
is present.
viewScale : array-like of float or None
Scaling factors [x, y] to apply custom scaling to the current units
of the :class:`~psychopy.visual.Window` instance.
viewPos : array-like of float or None
If not `None`, redefines the origin within the window, in the units
of the window. Values outside the borders will be clamped to lie on
the border.
viewOri : float
A single value determining the orientation of the view in degrees.
waitBlanking : bool or None
After a call to :py:attr:`~Window.flip()` should we wait for the
blank before the script continues.
bitsMode : bool
DEPRECATED in 1.80.02. Use BitsSharp class from pycrsltd
instead.
checkTiming : bool
Whether to calculate frame duration on initialization. Estimated
duration is saved in :py:attr:`~Window.monitorFramePeriod`.
allowStencil : bool
When set to `True`, this allows operations that use the OpenGL
stencil buffer (notably, allowing the
:class:`~psychopy.visual.Aperture` to be used).
multiSample : bool
If `True` and your graphics driver supports multisample buffers,
multiple color samples will be taken per-pixel, providing an
anti-aliased image through spatial filtering. This setting cannot
be changed after opening a window. Only works with 'pyglet' and
'glfw' `winTypes`, and `useFBO` is `False`.
numSamples : int
A single value specifying the number of samples per pixel if
multisample is enabled. The higher the number, the better the
image quality, but can delay frame flipping. The largest number of
samples is determined by ``GL_MAX_SAMPLES``, usually 16 or 32 on
newer hardware, will crash if number is invalid.
stereo : bool
If `True` and your graphics card supports quad buffers then
this will be enabled. You can switch between left and right-eye
scenes for drawing operations using
:py:attr:`~psychopy.visual.Window.setBuffer()`.
useRetina : bool
In PsychoPy >1.85.3 this should always be `True` as pyglet
(or Apple) no longer allows us to create a non-retina display.
NB when you use Retina display the initial win size
request will be in the larger pixels but subsequent use of
``units='pix'`` should refer to the tiny Retina pixels. Window.size
will give the actual size of the screen in Retina pixels.
gammaErrorPolicy: str
If `raise`, an error is raised if the gamma table is unable to be
retrieved or set. If `warn`, a warning is raised instead. If
`ignore`, neither an error nor a warning are raised.
bpc : array_like or int
Bits per color (BPC) for the back buffer as a tuple to specify
bit depths for each color channel separately (red, green, blue), or
a single value to set all of them to the same value. Valid values
depend on the output color depth of the display (screen) the window
is set to use and the system graphics configuration. By default, it
is assumed the display has 8-bits per color (8, 8, 8). Behaviour may
be undefined for non-fullscreen windows, or if multiple screens are
attached with varying color output depths.
depthBits : int
Back buffer depth bits. Default is 8, but can be set higher (eg. 24)
if drawing 3D stimuli to minimize artifacts such a 'Z-fighting'.
stencilBits : int
Back buffer stencil bits. Default is 8.
backendConf : dict or None
Additional options to pass to the backend specified by `winType`.
Each backend may provide unique functionality which may not be
available across all of them. This allows you to pass special
configuration options to a specific backend to configure the
feature.
Notes
-----
* Some parameters (e.g. units) can now be given default values in the
user/site preferences and these will be used if `None` is given here.
If you do specify a value here it will take precedence over
preferences.
Attributes
----------
size : array-like (float)
Dimensions of the window's drawing area/buffer in pixels [w, h].
monitorFramePeriod : float
Refresh rate of the display if ``checkTiming=True`` on window
instantiation.
"""
# what local vars are defined (these are the init params) for use by
# __repr__
self._initParams = dir()
self._closed = False
self.backend = None # this will be set later
for unecess in ['self', 'checkTiming', 'rgb', 'dkl', ]:
self._initParams.remove(unecess)
# Check autoLog value
if autoLog not in (True, False):
raise ValueError(
'autoLog must be either True or False for visual.Window')
self.autoLog = False # to suppress log msg during init
self.name = name
self.clientSize = numpy.array(size, int) # size of window, not buffer
self.pos = pos
# this will get overridden once the window is created
self.winHandle = None
self.useFBO = useFBO
self.useRetina = useRetina and sys.platform == 'darwin'
if gammaErrorPolicy not in ['raise', 'warn', 'ignore']:
raise ValueError('Unexpected `gammaErrorPolicy`')
self.gammaErrorPolicy = gammaErrorPolicy
self._toLog = []
self._toCall = []
# settings for the monitor: local settings (if available) override
# monitor
# if we have a monitors.Monitor object (psychopy 0.54 onwards)
# convert to a Monitor object
if not monitor:
self.monitor = monitors.Monitor('__blank__', autoLog=autoLog)
elif isinstance(monitor, basestring):
self.monitor = monitors.Monitor(monitor, autoLog=autoLog)
elif hasattr(monitor, 'keys'):
# convert into a monitor object
self.monitor = monitors.Monitor('temp', currentCalib=monitor,
verbose=False, autoLog=autoLog)
else:
self.monitor = monitor
# otherwise monitor will just be a dict
self.scrWidthCM = self.monitor.getWidth()
self.scrDistCM = self.monitor.getDistance()
scrSize = self.monitor.getSizePix()
if scrSize is None:
self.scrWidthPIX = None
else:
self.scrWidthPIX = scrSize[0]
if fullscr is None:
fullscr = prefs.general['fullscr']
self._isFullScr = fullscr
if units is None:
units = prefs.general['units']
self.units = units
if allowGUI is None:
allowGUI = prefs.general['allowGUI']
self.allowGUI = allowGUI
self.screen = screen
self.stereo = stereo # use quad buffer if requested (and if possible)
# enable multisampling
self.multiSample = multiSample
self.numSamples = numSamples
# load color conversion matrices
self.dkl_rgb = self.monitor.getDKL_RGB()
self.lms_rgb = self.monitor.getLMS_RGB()
# Projection and view matrices, these can be lists if multiple views are
# being used.
# NB - attribute checks needed for Rift compatibility
if not hasattr(self, '_viewMatrix'):
self._viewMatrix = numpy.identity(4, dtype=numpy.float32)
if not hasattr(self, '_projectionMatrix'):
self._projectionMatrix = viewtools.orthoProjectionMatrix(
-1, 1, -1, 1, -1, 1, dtype=numpy.float32)
# set screen color
self.__dict__['colorSpace'] = colorSpace
if rgb is not None:
logging.warning("Use of rgb arguments to stimuli are deprecated. "
"Please use color and colorSpace args instead")
color = rgb
colorSpace = 'rgb'
elif dkl is not None:
logging.warning("Use of dkl arguments to stimuli are deprecated. "
"Please use color and colorSpace args instead")
color = dkl
colorSpace = 'dkl'
elif lms is not None:
logging.warning("Use of lms arguments to stimuli are deprecated. "
"Please use color and colorSpace args instead")
color = lms
colorSpace = 'lms'
self.setColor(color, colorSpace=colorSpace, log=False)
self.allowStencil = allowStencil
# check whether FBOs are supported
if blendMode == 'add' and not self.useFBO:
logging.warning('User requested a blendmode of "add" but '
'window requires useFBO=True')
# resort to the simpler blending without float rendering
self.__dict__['blendMode'] = 'avg'
else:
self.__dict__['blendMode'] = blendMode
# then set up gl context and then call self.setBlendMode
# setup context and openGL()
if winType is None: # choose the default windowing
winType = prefs.general['winType']
self.winType = winType
# setup the context
# backend specific options are passed as a dictionary
backendConf = backendConf if backendConf is not None else {}
# Here we make sure all the open windows use the same `winType` and have
# context sharing enabled. The context to share is passed as an option
# to `backendConf`.
if openWindows:
primaryWindow = openWindows[0]() # resolve ref
if primaryWindow.winType != self.winType:
raise ValueError(
"Only one kind of `winType` can be used per session.")
# Allow for context sharing, only used by the GLFW backend, Pyglet
# uses `shadow_window` by default here so we don't need to worry
# about it.
backendConf['share'] = self
if not isinstance(backendConf, dict): # type check on options
raise TypeError(
'Object passed to `backendConf` must be type `dict`.')
# augment settings with dedicated attributes
backendConf['bpc'] = bpc
backendConf['depthBits'] = depthBits
backendConf['stencilBits'] = stencilBits
# get the backend, pass the options to it
self.backend = backends.getBackend(win=self, backendConf=backendConf)
self.winHandle = self.backend.winHandle
global GL
GL = self.backend.GL
# check whether shaders are supported
# also will need to check for ARB_float extension,
# but that should be done after context is created
self._haveShaders = self.backend.shadersSupported
self._setupGL()
self.blendMode = self.blendMode
# parameters for transforming the overall view
self.viewScale = val2array(viewScale)
if self.viewPos is not None and self.units is None:
raise ValueError('You must define the window units to use viewPos')
self.viewPos = val2array(viewPos, withScalar=False)
self.viewOri = float(viewOri)
if self.viewOri != 0. and self.viewPos is not None:
msg = "Window: viewPos & viewOri are currently incompatible"
raise NotImplementedError(msg)
# scaling factor for HiDPI displays, `None` until initialized
self._contentScaleFactor = None
# Code to allow iohub to know id of any psychopy windows created
# so kb and mouse event filtering by window id can be supported.
#
# If an iohubConnection is active, give this window os handle to
# to the ioHub server. If windows were already created before the
# iohub was active, also send them to iohub.
#
if IOHUB_ACTIVE:
from psychopy.iohub.client import ioHubConnection
if ioHubConnection.ACTIVE_CONNECTION:
winhwnds = []
for w in openWindows:
winhwnds.append(w()._hw_handle)
if self.winHandle not in winhwnds:
winhwnds.append(self._hw_handle)
conn = ioHubConnection.ACTIVE_CONNECTION
conn.registerWindowHandles(*winhwnds)
# near and far clipping planes
self._nearClip = 0.1
self._farClip = 100.0
# 3D rendering related attributes
self.frontFace = 'ccw'
self.depthFunc = 'less'
self.depthMask = False
self.cullFace = False
self.cullFaceMode = 'back'
self.draw3d = False
# scene light sources
self._lights = []
self._useLights = False
self._nLights = 0
self._ambientLight = numpy.array([0.0, 0.0, 0.0, 1.0],
dtype=numpy.float32)
# stereo rendering settings, set later by the user
self._eyeOffset = 0.0
self._convergeOffset = 0.0
# gamma
self.bits = None # this may change in a few lines time!
self.__dict__['gamma'] = gamma
self._setupGamma(gamma)
# setup bits++ if needed. NB The new preferred method is for this
# to be handled by the bits class instead. (we pass the Window to
# bits not passing bits to the window)
if bitsMode is not None:
logging.warn("Use of Window(bitsMode=******) is deprecated. See "
"the Coder>Demos>Hardware demo for new methods")
self.bitsMode = bitsMode # could be [None, 'fast', 'slow']
logging.warn("calling Window(...,bitsMode='fast') is deprecated."
" XXX provide further info")
from psychopy.hardware.crs.bits import BitsPlusPlus
self.bits = self.interface = BitsPlusPlus(self)
self.haveBits = True
if (hasattr(self.monitor, 'linearizeLums') or
hasattr(self.monitor, 'lineariseLums')):
# rather than a gamma value we could use bits++ and provide a
# complete linearised lookup table using
# monitor.linearizeLums(lumLevels)
self.__dict__['gamma'] = None
self.frameClock = core.Clock() # from psycho/core
self.frames = 0 # frames since last fps calc
self.movieFrames = [] # list of captured frames (Image objects)
self.recordFrameIntervals = False
# Be able to omit the long timegap that follows each time turn it off
self.recordFrameIntervalsJustTurnedOn = False
self.nDroppedFrames = 0
self.frameIntervals = []
self._frameTimes = deque(maxlen=1000) # 1000 keeps overhead low
self._toDraw = []
self._toDrawDepths = []
self._eventDispatchers = []
self.lastFrameT = core.getTime()
self.waitBlanking = waitBlanking
# set the swap interval if using GLFW
if self.winType == 'glfw':
self.backend.setSwapInterval(int(waitBlanking))
self.refreshThreshold = 1.0 # initial val needed by flip()
self._editableChildren = []
self._currentEditableRef = None
# over several frames with no drawing
self._monitorFrameRate = None
# for testing when to stop drawing a stim:
self.monitorFramePeriod = 0.0
if checkTiming:
self._monitorFrameRate = self.getActualFrameRate()
if self._monitorFrameRate is not None:
self.monitorFramePeriod = 1.0 / self._monitorFrameRate
else:
self.monitorFramePeriod = 1.0 / 60 # assume a flat panel?
self.refreshThreshold = self.monitorFramePeriod * 1.2
openWindows.append(self)
self.autoLog = autoLog
if self.autoLog:
logging.exp("Created %s = %s" % (self.name, str(self)))
# Make sure this window's close method is called when exiting, even in
# the event of an error we should be able to restore the original gamma
# table. Note that a reference to this window object will live in this
# function, preventing it from being garbage collected.
def close_on_exit():
if self._closed is False:
self.close()
atexit.register(close_on_exit)
self._mouse = event.Mouse(win=self)
def __del__(self):
if self._closed is False:
self.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
if not self._closed:
self.close()
def __str__(self):
className = 'Window'
paramStrings = []
for param in self._initParams:
if hasattr(self, param):
paramStrings.append("%s=%s" %
(param, repr(getattr(self, param))))
else:
paramStrings.append("%s=UNKNOWN" % (param))
# paramStrings = ["%s=%s" %(param, getattr(self, param))
# for param in self._initParams]
params = ", ".join(paramStrings)
s = "%s(%s)" % (className, params)
return s
@attributeSetter
def units(self, value):
"""*None*, 'height' (of the window), 'norm', 'deg', 'cm', 'pix'
Defines the default units of stimuli initialized in the window.
I.e. if you change units, already initialized stimuli won't change
their units.
Can be overridden by each stimulus, if units is specified on
initialization.
See :ref:`units` for explanation of options.
"""
self.__dict__['units'] = value
def setUnits(self, value, log=True):
setAttribute(self, 'units', value, log=log)
@attributeSetter
def viewPos(self, value):
"""The origin of the window onto which stimulus-objects are drawn.
The value should be given in the units defined for the window. NB:
Never change a single component (x or y) of the origin, instead replace
the viewPos-attribute in one shot, e.g.::
win.viewPos = [new_xval, new_yval] # This is the way to do it
win.viewPos[0] = new_xval # DO NOT DO THIS! Errors will result.
"""
self.__dict__['viewPos'] = value
if value is not None:
# let setter take care of normalisation
setattr(self, '_viewPosNorm', value)
@attributeSetter
def _viewPosNorm(self, value):
"""Normalised value of viewPos, hidden from user view."""
# first convert to pixels, then normalise to window units
viewPos_pix = convertToPix([0, 0], list(value),
units=self.units, win=self)[:2]
viewPos_norm = viewPos_pix / (self.size / 2.0)
# Clip to +/- 1; should going out-of-window raise an exception?
viewPos_norm = numpy.clip(viewPos_norm, a_min=-1., a_max=1.)
self.__dict__['_viewPosNorm'] = viewPos_norm
def setViewPos(self, value, log=True):
setAttribute(self, 'viewPos', value, log=log)
@attributeSetter
def fullscr(self, value):
"""Set whether fullscreen mode is `True` or `False` (not all backends
can toggle an open window).
"""
self.backend.setFullScr(value)
self.__dict__['fullscr'] = value
self._isFullScr = value
@attributeSetter
def waitBlanking(self, value):
"""After a call to :py:attr:`~Window.flip()` should we wait for the
blank before the script continues.
"""
self.__dict__['waitBlanking'] = value
@attributeSetter
def recordFrameIntervals(self, value):
"""Record time elapsed per frame.
Provides accurate measures of frame intervals to determine
whether frames are being dropped. The intervals are the times between
calls to :py:attr:`~Window.flip()`. Set to `True` only during the
time-critical parts of the script. Set this to `False` while the screen
is not being updated, i.e., during any slow, non-frame-time-critical
sections of your code, including inter-trial-intervals,
``event.waitkeys()``, ``core.wait()``, or ``image.setImage()``.
Examples
--------
Enable frame interval recording, successive frame intervals will be
stored::
win.recordFrameIntervals = True
Frame intervals can be saved by calling the
:py:attr:`~Window.saveFrameIntervals` method::
win.saveFrameIntervals()
"""
# was off, and now turning it on
self.recordFrameIntervalsJustTurnedOn = bool(
not self.recordFrameIntervals and value)
self.__dict__['recordFrameIntervals'] = value
self.frameClock.reset()
def setRecordFrameIntervals(self, value=True, log=None):
"""Usually you can use 'stim.attribute = value' syntax instead,
but use this method if you need to suppress the log message.
"""
setAttribute(self, 'recordFrameIntervals', value, log)
def saveFrameIntervals(self, fileName=None, clear=True):
"""Save recorded screen frame intervals to disk, as comma-separated
values.
Parameters
----------
fileName : *None* or str
*None* or the filename (including path if necessary) in which to
store the data. If None then 'lastFrameIntervals.log' will be used.
clear : bool
Clear buffer frames intervals were stored after saving. Default is
`True`.
"""
if not fileName:
fileName = 'lastFrameIntervals.log'
if len(self.frameIntervals):
intervalStr = str(self.frameIntervals)[1:-1]
f = open(fileName, 'w')
f.write(intervalStr)
f.close()
if clear:
self.frameIntervals = []
self.frameClock.reset()
def _setCurrent(self):
"""Make this window's OpenGL context current.
If called on a window whose context is current, the function will return
immediately. This reduces the number of redundant calls if no context
switch is required. If ``useFBO=True``, the framebuffer is bound after
the context switch.
"""
# don't configure if we haven't changed context
if not self.backend.setCurrent():
return
# if we are using an FBO, bind it
if hasattr(self, 'frameBuffer'):
GL.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT,
self.frameBuffer)
GL.glReadBuffer(GL.GL_COLOR_ATTACHMENT0_EXT)
GL.glDrawBuffer(GL.GL_COLOR_ATTACHMENT0_EXT)
# NB - check if we need these
GL.glActiveTexture(GL.GL_TEXTURE0)
GL.glBindTexture(GL.GL_TEXTURE_2D, 0)
# set these to match the current window or buffer's settings
fbw, fbh = self.frameBufferSize
self.viewport = self.scissor = [0, 0, fbw, fbh]
self.scissorTest = True
# apply the view transforms for this window
#self.applyEyeTransform()
def onResize(self, width, height):
"""A default resize event handler.
This default handler updates the GL viewport to cover the entire
window and sets the ``GL_PROJECTION`` matrix to be orthogonal in
window space. The bottom-left corner is (0, 0) and the top-right
corner is the width and height of the :class:`~psychopy.visual.Window`
in pixels.
Override this event handler with your own to create another
projection, for example in perspective.
"""
# this has to be external so that pyglet can use it too without
# circular referencing
self.backend.onResize(width, height)
def logOnFlip(self, msg, level, obj=None):
"""Send a log message that should be time-stamped at the next
:py:attr:`~Window.flip()` command.
Parameters
----------
msg : str
The message to be logged.
level : int
The level of importance for the message.
obj : object, optional
The python object that might be associated with this message if
desired.
"""
self._toLog.append({'msg': msg, 'level': level, 'obj': repr(obj)})
def callOnFlip(self, function, *args, **kwargs):
"""Call a function immediately after the next :py:attr:`~Window.flip()`
command.
The first argument should be the function to call, the following args
should be used exactly as you would for your normal call to the
function (can use ordered arguments or keyword arguments as normal).
e.g. If you have a function that you would normally call like this::
pingMyDevice(portToPing, channel=2, level=0)
then you could call :py:attr:`~Window.callOnFlip()` to have the function
call synchronized with the frame flip like this::
win.callOnFlip(pingMyDevice, portToPing, channel=2, level=0)
"""
self._toCall.append({'function': function,
'args': args,
'kwargs': kwargs})
def timeOnFlip(self, obj, attrib):
"""Retrieves the time on the next flip and assigns it to the `attrib`
for this `obj`.
Parameters
----------
obj : dict or object
A mutable object (usually a dict of class instance).
attrib : str
Key or attribute of `obj` to assign the flip time to.
Examples
--------
Assign time on flip to the ``tStartRefresh`` key of ``myTimingDict``::
win.getTimeOnFlip(myTimingDict, 'tStartRefresh')
"""
self.callOnFlip(self._assignFlipTime, obj, attrib)
def getFutureFlipTime(self, targetTime=0, clock=None):
"""The expected time of the next screen refresh. This is currently
calculated as win._lastFrameTime + refreshInterval
Parameters
-----------
targetTime: float
The delay *from now* for which you want the flip time. 0 will give the
because that the earliest we can achieve. 0.15 will give the schedule
flip time that gets as close to 150 ms as possible
clock : None, 'ptb', 'now' or any Clock object
If True then the time returned is compatible with ptb.GetSecs()
verbose: bool
Set to True to view the calculations along the way
"""
baseClock = logging.defaultClock
if not self.monitorFramePeriod:
raise AttributeError("Cannot calculate nextFlipTime due to unknown "
"monitorFramePeriod")
lastFlip = self._frameTimes[-1] # unlike win.lastFrameTime this is always on
timeNext = lastFlip + self.monitorFramePeriod
now = baseClock.getTime()
if (now + targetTime) > timeNext: # target is more than 1 frame in future
extraFrames = math.ceil((now + targetTime - timeNext)/self.monitorFramePeriod)
thisT = timeNext + extraFrames*self.monitorFramePeriod
else:
thisT = timeNext
# convert back to target clock timebase
if clock=='ptb': # add back the lastResetTime (that's the clock difference)
output = thisT + baseClock.getLastResetTime()
elif clock=='now': # time from now is easy!
output = thisT - now
elif clock:
output = thisT + baseClock.getLastResetTime() - clock.getLastResetTime()
else:
output = thisT
return output
def _assignFlipTime(self, obj, attrib):
"""Helper function to assign the time of last flip to the obj.attrib
Parameters
----------
obj : dict or object
A mutable object (usually a dict of class instance).
attrib : str
Key or attribute of ``obj`` to assign the flip time to.
"""
if hasattr(obj, attrib):
setattr(obj, attrib, self._frameTime)
elif isinstance(obj, dict):
obj[attrib] = self._frameTime
else:
raise TypeError("Window.getTimeOnFlip() should be called with an "
"object and its attribute or a dict and its key. "
"In this case it was called with obj={}"
.format(repr(obj)))
def _cleanEditables(self):
"""
Make sure there are no dead refs in the editables list
"""
for ref in self._editableChildren:
obj = ref()
if obj is None:
self._editableChildren.remove(ref)
@property
def currentEditable(self):
"""The editable (Text?) object that currently has key focus"""
if self._currentEditableRef:
return self._currentEditableRef()
@currentEditable.setter
def currentEditable(self, editable):
"""Keeps the current editable stored as a weak ref"""
# Ensure that item is added to editables list
self.addEditable(editable)
# Set the editable as the current editable stim in the window
eRef = None
for ref in weakref.getweakrefs(editable):
if ref in self._editableChildren:
eRef = ref
break
if eRef:
self._currentEditableRef = eRef
def addEditable(self, editable):
"""Adds an editable element to the screen (something to which
characters can be sent with meaning from the keyboard).
The current editable object receiving chars is Window.currentEditable
:param editable:
:return:
"""
# Ignore if object is not editable
if not hasattr(editable, "editable"):
return
if not editable.editable:
return
# If editable is already present do nothing
eRef = False
for ref in weakref.getweakrefs(editable):
if ref in self._editableChildren:
eRef = ref
break
if eRef is False:
eRef = weakref.ref(editable)
# If editable is not already present, add it to the editables list
self._editableChildren.append(eRef)
# If this is the first editable obj then make it the current
if len(self._editableChildren) == 1:
self._currentEditableRef = eRef
# Clean editables list
self._cleanEditables()
def removeEditable(self, editable):
# If editable is present, remove it from editables list
for ref in weakref.getweakrefs(editable):
if ref in self._editableChildren:
# If editable was current, move on to next current
if self.currentEditable == editable:
self.nextEditable()
self._editableChildren.remove(ref)
return True
else:
logging.warning(f"Request to remove editable object {editable} could not be completed as weakref "
f"to this object could not be found in window.")
# Clean editables list
self._cleanEditables()
return False
def nextEditable(self):
"""Moves focus of the cursor to the next editable window"""
# Clean editables list
self._cleanEditables()
# Progress
if self.currentEditable is None:
if len(self._editableChildren):
self._currentEditableRef = self._editableChildren[0]
else:
for ref in weakref.getweakrefs(self.currentEditable):
if ref in self._editableChildren:
cei = self._editableChildren.index(ref)
nei = cei+1
if nei >= len(self._editableChildren):
nei=0
self._currentEditableRef = self._editableChildren[nei]
return self.currentEditable
@classmethod
def dispatchAllWindowEvents(cls):
"""
Dispatches events for all pyglet windows. Used by iohub 2.0
psychopy kb event integration.
"""
Window.backend.dispatchEvents()
def flip(self, clearBuffer=True):
"""Flip the front and back buffers after drawing everything for your
frame. (This replaces the :py:attr:`~Window.update()` method, better
reflecting what is happening underneath).
Parameters
----------
clearBuffer : bool, optional
Clear the draw buffer after flipping. Default is `True`.
Returns
-------
float or None
Wall-clock time in seconds the flip completed. Returns `None` if
:py:attr:`~Window.waitBlanking` is `False`.
Notes
-----
* The time returned when :py:attr:`~Window.waitBlanking` is `True`
corresponds to when the graphics driver releases the draw buffer to
accept draw commands again. This time is usually close to the vertical
sync signal of the display.
Examples
--------
Results in a clear screen after flipping::
win.flip(clearBuffer=True)
The screen is not cleared (so represent the previous screen)::
win.flip(clearBuffer=False)
"""
if self._toDraw:
for thisStim in self._toDraw:
thisStim.draw()
else:
self.backend.setCurrent()
# set these to match the current window or buffer's settings
self.viewport = self.scissor = \
(0, 0, self.frameBufferSize[0], self.frameBufferSize[1])
if not self.scissorTest:
self.scissorTest = True
# clear the projection and modelview matrix for FBO blit
GL.glMatrixMode(GL.GL_PROJECTION)
GL.glLoadIdentity()
GL.glOrtho(-1, 1, -1, 1, -1, 1)
GL.glMatrixMode(GL.GL_MODELVIEW)
GL.glLoadIdentity()
# disable lighting
self.useLights = False
# Check for mouse clicks on editables
if hasattr(self, '_editableChildren'):
# Make sure _editableChildren has actually been created
editablesOnScreen = []
for thisObj in self._editableChildren:
# Iterate through editables and decide which one should have focus
if isinstance(thisObj, weakref.ref):
# Solidify weakref if necessary
thisObj = thisObj()
if thisObj is None:
continue
if isinstance(thisObj.autoDraw, (bool, int, float)):
# Store whether this editable is on screen
editablesOnScreen.append(thisObj.autoDraw)
else:
editablesOnScreen.append(False)
if self._mouse.isPressedIn(thisObj):
# If editable was clicked on, give it focus
self.currentEditable = thisObj
# If there is only one editable on screen, make sure it starts off with focus
if sum(editablesOnScreen) == 1:
self.currentEditable = self._editableChildren[editablesOnScreen.index(True)]()
flipThisFrame = self._startOfFlip()
if self.useFBO and flipThisFrame:
self.draw3d = False # disable 3d drawing
self._prepareFBOrender()
# need blit the framebuffer object to the actual back buffer
# unbind the framebuffer as the render target
GL.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, 0)
GL.glDisable(GL.GL_BLEND)
stencilOn = self.stencilTest
self.stencilTest = False
if self.bits is not None:
self.bits._prepareFBOrender()
# before flipping need to copy the renderBuffer to the
# frameBuffer
GL.glActiveTexture(GL.GL_TEXTURE0)
GL.glEnable(GL.GL_TEXTURE_2D)
GL.glBindTexture(GL.GL_TEXTURE_2D, self.frameTexture)
GL.glColor3f(1.0, 1.0, 1.0) # glColor multiplies with texture
GL.glColorMask(True, True, True, True)
self._renderFBO()
GL.glEnable(GL.GL_BLEND)
self._finishFBOrender()
# call this before flip() whether FBO was used or not
self._afterFBOrender()
self.backend.swapBuffers(flipThisFrame)
if self.useFBO and flipThisFrame:
# set rendering back to the framebuffer object
GL.glBindFramebufferEXT(
GL.GL_FRAMEBUFFER_EXT, self.frameBuffer)
GL.glReadBuffer(GL.GL_COLOR_ATTACHMENT0_EXT)
GL.glDrawBuffer(GL.GL_COLOR_ATTACHMENT0_EXT)
# set to no active rendering texture
GL.glActiveTexture(GL.GL_TEXTURE0)
GL.glBindTexture(GL.GL_TEXTURE_2D, 0)
if stencilOn:
self.stencilTest = True
# rescale, reposition, & rotate
GL.glMatrixMode(GL.GL_MODELVIEW)
GL.glLoadIdentity()
if self.viewScale is not None:
GL.glScalef(self.viewScale[0], self.viewScale[1], 1)
absScaleX = abs(self.viewScale[0])
absScaleY = abs(self.viewScale[1])
else:
absScaleX, absScaleY = 1, 1
if self.viewPos is not None:
# here we must use normalised units in _viewPosNorm,
# see the corresponding attributeSetter above
normRfPosX = self._viewPosNorm[0] / absScaleX
normRfPosY = self._viewPosNorm[1] / absScaleY
GL.glTranslatef(normRfPosX, normRfPosY, 0.0)
if self.viewOri: # float
# the logic below for flip is partially correct, but does not
# handle a nonzero viewPos
flip = 1
if self.viewScale is not None:
_f = self.viewScale[0] * self.viewScale[1]
if _f < 0:
flip = -1
GL.glRotatef(flip * self.viewOri, 0.0, 0.0, -1.0)
# reset returned buffer for next frame
self._endOfFlip(clearBuffer)
# waitBlanking
if self.waitBlanking and flipThisFrame:
GL.glBegin(GL.GL_POINTS)
GL.glColor4f(0, 0, 0, 0)
if sys.platform == 'win32' and self.glVendor.startswith('ati'):
pass
else:
# this corrupts text rendering on win with some ATI cards :-(
GL.glVertex2i(10, 10)
GL.glEnd()
GL.glFinish()
# get timestamp
self._frameTime = now = logging.defaultClock.getTime()
self._frameTimes.append(self._frameTime)
# run other functions immediately after flip completes
for callEntry in self._toCall:
callEntry['function'](*callEntry['args'], **callEntry['kwargs'])
del self._toCall[:]
# do bookkeeping
if self.recordFrameIntervals:
self.frames += 1
deltaT = now - self.lastFrameT
self.lastFrameT = now
if self.recordFrameIntervalsJustTurnedOn: # don't do anything
self.recordFrameIntervalsJustTurnedOn = False
else: # past the first frame since turned on
self.frameIntervals.append(deltaT)
if deltaT > self.refreshThreshold:
self.nDroppedFrames += 1
if self.nDroppedFrames < reportNDroppedFrames:
txt = 't of last frame was %.2fms (=1/%i)'
msg = txt % (deltaT * 1000, 1 / deltaT)
logging.warning(msg, t=now)
elif self.nDroppedFrames == reportNDroppedFrames:
logging.warning("Multiple dropped frames have "
"occurred - I'll stop bothering you "
"about them!")
# log events
for logEntry in self._toLog:
# {'msg':msg, 'level':level, 'obj':copy.copy(obj)}
logging.log(msg=logEntry['msg'],
level=logEntry['level'],
t=now,
obj=logEntry['obj'])
del self._toLog[:]
# keep the system awake (prevent screen-saver or sleep)
platform_specific.sendStayAwake()
# If self.waitBlanking is True, then return the time that
# GL.glFinish() returned, set as the 'now' variable. Otherwise
# return None as before
#
if self.waitBlanking is True:
return now
def update(self):
"""Deprecated: use Window.flip() instead
"""
# clearBuffer was the original behaviour for win.update()
self.flip(clearBuffer=True)
def multiFlip(self, flips=1, clearBuffer=True):
"""Flip multiple times while maintaining the display constant.
Use this method for precise timing.
**WARNING:** This function should not be used. See the `Notes` section
for details.
Parameters
----------
flips : int, optional
The number of monitor frames to flip. Floats will be
rounded to integers, and a warning will be emitted.
``Window.multiFlip(flips=1)`` is equivalent to ``Window.flip()``.
Defaults to `1`.
clearBuffer : bool, optional
Whether to clear the screen after the last flip.
Defaults to `True`.
Notes
-----
- This function can behave unpredictably, and the PsychoPy authors
recommend against using it. See
https://github.com/psychopy/psychopy/issues/867 for more information.
Examples
--------
Example of using ``multiFlip``::
# Draws myStim1 to buffer
myStim1.draw()
# Show stimulus for 4 frames (90 ms at 60Hz)
myWin.multiFlip(clearBuffer=False, flips=6)
# Draw myStim2 "on top of" myStim1
# (because buffer was not cleared above)
myStim2.draw()
# Show this for 2 frames (30 ms at 60Hz)
myWin.multiFlip(flips=2)
# Show blank screen for 3 frames (buffer was cleared above)
myWin.multiFlip(flips=3)
"""
if flips < 1:
logging.error("flips argument for multiFlip should be "
"a positive integer")
if flips != int(flips):
flips = int(round(flips))
logging.warning("Number of flips was not an integer; "
"rounding to the next integer. Will flip "
"%i times." % flips)
if flips > 1 and not self.waitBlanking:
logging.warning("Call to Window.multiFlip() with flips > 1 is "
"unnecessary because Window.waitBlanking=False")
# Do the flipping with last flip as special case
for _ in range(flips - 1):
self.flip(clearBuffer=False)
self.flip(clearBuffer=clearBuffer)
def setBuffer(self, buffer, clear=True):
"""Choose which buffer to draw to ('left' or 'right').
Requires the Window to be initialised with stereo=True and requires a
graphics card that supports quad buffering (e,g nVidia Quadro series)
PsychoPy always draws to the back buffers, so 'left' will use
``GL_BACK_LEFT`` This then needs to be flipped once both eye's buffers
have been rendered.
Parameters
----------
buffer : str
Buffer to draw to. Can either be 'left' or 'right'.
clear : bool, optional
Clear the buffer before drawing. Default is ``True``.
Examples
--------
Stereoscopic rendering example using quad-buffers::
win = visual.Window(...., stereo=True)
while True:
# clear may not actually be needed
win.setBuffer('left', clear=True)
# do drawing for left eye
win.setBuffer('right', clear=True)
# do drawing for right eye
win.flip()
"""
if buffer == 'left':
GL.glDrawBuffer(GL.GL_BACK_LEFT)
elif buffer == 'right':
GL.glDrawBuffer(GL.GL_BACK_RIGHT)
else:
raise "Unknown buffer '%s' requested in Window.setBuffer" % buffer
if clear:
self.clearBuffer()
def clearBuffer(self, color=True, depth=False, stencil=False):
"""Clear the present buffer (to which you are currently drawing) without
flipping the window.
Useful if you want to generate movie sequences from the back buffer
without actually taking the time to flip the window.
Set `color` prior to clearing to set the color to clear the color buffer
to. By default, the depth buffer is cleared to a value of 1.0.
Parameters
----------
color, depth, stencil : bool
Buffers to clear.
Examples
--------
Clear the color buffer to a specified color::
win.color = (1, 0, 0)
win.clearBuffer(color=True)
Clear only the depth buffer, `depthMask` must be `True` or else this
will have no effect. Depth mask is usually `True` by default, but
may change::
win.depthMask = True
win.clearBuffer(color=False, depth=True, stencil=False)
"""
clearBufferBits = GL.GL_NONE
if color:
clearBufferBits |= GL.GL_COLOR_BUFFER_BIT
if depth:
clearBufferBits |= GL.GL_DEPTH_BUFFER_BIT
if stencil:
clearBufferBits |= GL.GL_STENCIL_BUFFER_BIT
# reset returned buffer for next frame
GL.glClear(clearBufferBits)
@property
def size(self):
"""Size of the drawable area in pixels (w, h)."""
# report clientSize until we get framebuffer size from
# the backend, needs to be done properly in the future
if self.backend is not None:
return self.viewport[2:]
else:
return self.clientSize
@property
def frameBufferSize(self):
"""Size of the framebuffer in pixels (w, h)."""
# Dimensions should match window size unless using a retina display
return self.backend.frameBufferSize
def getContentScaleFactor(self):
"""Get the scaling factor required for scaling correctly on high-DPI
displays.
If the returned value is 1.0, no scaling needs to be applied to objects
drawn on the backbuffer. A value >1.0 indicates that the backbuffer is
larger than the reported client area, requiring points to be scaled to
maintain constant size across similarly sized displays. In other words,
the scaling required to convert framebuffer to client coordinates.
Returns
-------
float
Scaling factor to be applied along both horizontal and vertical
dimensions.
Examples
--------
Get the size of the client area::
clientSize = win.frameBufferSize / win.getContentScaleFactor()
Get the framebuffer size from the client size::
frameBufferSize = win.clientSize * win.getContentScaleFactor()
Convert client (window) to framebuffer pixel coordinates (eg., a mouse
coordinate, vertices, etc.)::
# `mousePosXY` is an array ...
frameBufferXY = mousePosXY * win.getContentScaleFactor()
# you can also use the attribute ...
frameBufferXY = mousePosXY * win.contentScaleFactor
Notes
-----
* This value is only valid after the window has been fully realized.
"""
# this might be accessed at lots of points, probably shouldn't compute
# this all the time
if self._contentScaleFactor is not None:
return self._contentScaleFactor
sx = self.frameBufferSize[0] / float(self.clientSize[0])
sy = self.frameBufferSize[1] / float(self.clientSize[1])
if sx != sy: # messed up DPI settings return 1.0 and show warning
self._contentScaleFactor = 1.0
else:
self._contentScaleFactor = sx
return self._contentScaleFactor
@property
def contentScaleFactor(self):
"""Scaling factor (`float`) to use when drawing to the backbuffer to
convert framebuffer to client coordinates.
See Also
--------
getContentScaleFactor
"""
return self.getContentScaleFactor()
@property
def aspect(self):
"""Aspect ratio of the current viewport (width / height)."""
return self._viewport[2] / float(self._viewport[3])
@property
def ambientLight(self):
"""Ambient light color for the scene [r, g, b, a]. Values range from 0.0
to 1.0. Only applicable if `useLights` is `True`.
Examples
--------
Setting the ambient light color::
win.ambientLight = [0.5, 0.5, 0.5]
# don't do this!!!
win.ambientLight[0] = 0.5
win.ambientLight[1] = 0.5
win.ambientLight[2] = 0.5
"""
# TODO - use signed color and colorspace instead
return self._ambientLight[:3]
@ambientLight.setter
def ambientLight(self, value):
self._ambientLight[:3] = value
GL.glLightModelfv(GL.GL_LIGHT_MODEL_AMBIENT,
numpy.ctypeslib.as_ctypes(self._ambientLight))
@property
def lights(self):
"""Scene lights.
This is specified as an array of `~psychopy.visual.LightSource`
objects. If a single value is given, it will be converted to a `list`
before setting. Set `useLights` to `True` before rendering to enable
lighting/shading on subsequent objects. If `lights` is `None` or an
empty `list`, no lights will be enabled if `useLights=True`, however,
the scene ambient light set with `ambientLight` will be still be used.
Examples
--------
Create a directional light source and add it to scene lights::
dirLight = gltools.LightSource((0., 1., 0.), lightType='directional')
win.lights = dirLight # `win.lights` will be a list when accessed!
Multiple lights can be specified by passing values as a list::
myLights = [gltools.LightSource((0., 5., 0.)),
gltools.LightSource((-2., -2., 0.))
win.lights = myLights
"""
return self._lights
@lights.setter
def lights(self, value):
# if None or empty list, disable all lights
if value is None or not value:
for index in range(self._nLights):
GL.glDisable(GL.GL_LIGHT0 + index)
self._nLights = 0 # set number of lights to zero
self._lights = value
return
# set the lights and make sure it's a list if a single value was passed
self._lights = value if isinstance(value, (list, tuple,)) else [value]
# disable excess lights if less lights were specified this time
oldNumLights = self._nLights
self._nLights = len(self._lights) # number of lights enabled
if oldNumLights > self._nLights:
for index in range(self._nLights, oldNumLights):
GL.glDisable(GL.GL_LIGHT0 + index)
# Setup legacy lights, new spec shader programs should access the
# `lights` attribute directly to setup lighting uniforms.
# The index of the lights is defined by the order it appears in
# `self._lights`.
for index, light in enumerate(self._lights):
enumLight = GL.GL_LIGHT0 + index
# convert data in light class to ctypes
#pos = numpy.ctypeslib.as_ctypes(light.pos)
diffuse = numpy.ctypeslib.as_ctypes(light._diffuseRGB)
specular = numpy.ctypeslib.as_ctypes(light._specularRGB)
ambient = numpy.ctypeslib.as_ctypes(light._ambientRGB)
# pass values to OpenGL
#GL.glLightfv(enumLight, GL.GL_POSITION, pos)
GL.glLightfv(enumLight, GL.GL_DIFFUSE, diffuse)
GL.glLightfv(enumLight, GL.GL_SPECULAR, specular)
GL.glLightfv(enumLight, GL.GL_AMBIENT, ambient)
constant, linear, quadratic = light._kAttenuation
GL.glLightf(enumLight, GL.GL_CONSTANT_ATTENUATION, constant)
GL.glLightf(enumLight, GL.GL_LINEAR_ATTENUATION, linear)
GL.glLightf(enumLight, GL.GL_QUADRATIC_ATTENUATION, quadratic)
# enable the light
GL.glEnable(enumLight)
@property
def useLights(self):
"""Enable scene lighting.
Lights will be enabled if using legacy OpenGL lighting. Stimuli using
shaders for lighting should check if `useLights` is `True` since this
will have no effect on them, and disable or use a no lighting shader
instead. Lights will be transformed to the current view matrix upon
setting to `True`.
Lights are transformed by the present `GL_MODELVIEW` matrix. Setting
`useLights` will result in their positions being transformed by it.
If you want lights to appear at the specified positions in world space,
make sure the current matrix defines the view/eye transformation when
setting `useLights=True`.
This flag is reset to `False` at the beginning of each frame. Should be
`False` if rendering 2D stimuli or else the colors will be incorrect.
"""
return self._useLights
@useLights.setter
def useLights(self, value):
self._useLights = value
# Setup legacy lights, new spec shader programs should access the
# `lights` attribute directly to setup lighting uniforms.
if self._useLights and self._lights:
GL.glEnable(GL.GL_LIGHTING)
# make sure specular lights are computed relative to eye position,
# this is more realistic than the default. Does not affect shaders.
GL.glLightModeli(GL.GL_LIGHT_MODEL_LOCAL_VIEWER, GL.GL_TRUE)
# update light positions for current model matrix
for index, light in enumerate(self._lights):
enumLight = GL.GL_LIGHT0 + index
pos = numpy.ctypeslib.as_ctypes(light.pos)
GL.glLightfv(enumLight, GL.GL_POSITION, pos)
else:
# disable lights
GL.glDisable(GL.GL_LIGHTING)
def updateLights(self, index=None):
"""Explicitly update scene lights if they were modified.
This is required if modifications to objects referenced in `lights` have
been changed since assignment. If you removed or added items of `lights`
you must refresh all of them.
Parameters
----------
index : int, optional
Index of light source in `lights` to update. If `None`, all lights
will be refreshed.
Examples
--------
Call `updateLights` if you modified lights directly like this::
win.lights[1].diffuseColor = [1., 0., 0.]
win.updateLights(1)
"""
if self._lights is None:
return # nop if there are no lights
if index is None:
self.lights = self._lights
else:
if index > len(self._lights) - 1:
raise IndexError('Invalid index for `lights`.')
enumLight = GL.GL_LIGHT0 + index
# light object to modify
light = self._lights[index]
# convert data in light class to ctypes
# pos = numpy.ctypeslib.as_ctypes(light.pos)
diffuse = numpy.ctypeslib.as_ctypes(light.diffuse)
specular = numpy.ctypeslib.as_ctypes(light.specular)
ambient = numpy.ctypeslib.as_ctypes(light.ambient)
# pass values to OpenGL
# GL.glLightfv(enumLight, GL.GL_POSITION, pos)
GL.glLightfv(enumLight, GL.GL_DIFFUSE, diffuse)
GL.glLightfv(enumLight, GL.GL_SPECULAR, specular)
GL.glLightfv(enumLight, GL.GL_AMBIENT, ambient)
def resetViewport(self):
"""Reset the viewport to cover the whole framebuffer.
Set the viewport to match the dimensions of the back buffer or
framebuffer (if `useFBO=True`). The scissor rectangle is also set to
match the dimensions of the viewport.
"""
self.scissor = self.viewport = self.frameBufferSize
@property
def viewport(self):
"""Viewport rectangle (x, y, w, h) for the current draw buffer.
Values `x` and `y` define the origin, and `w` and `h` the size of the
rectangle in pixels.
This is typically set to cover the whole buffer, however it can be
changed for applications like multi-view rendering. Stimuli will draw
according to the new shape of the viewport, for instance and stimulus
with position (0, 0) will be drawn at the center of the viewport, not
the window.
Examples
--------
Constrain drawing to the left and right halves of the screen, where
stimuli will be drawn centered on the new rectangle. Note that you need
to set both the `viewport` and the `scissor` rectangle::
x, y, w, h = win.frameBufferSize # size of the framebuffer
win.viewport = win.scissor = [x, y, w / 2.0, h]
# draw left stimuli ...
win.viewport = win.scissor = [x + (w / 2.0), y, w / 2.0, h]
# draw right stimuli ...
# restore drawing to the whole screen
win.viewport = win.scissor = [x, y, w, h]
"""
return self._viewport
@viewport.setter
def viewport(self, value):
self._viewport = numpy.array(value, int)
GL.glViewport(*self._viewport)
@property
def scissor(self):
"""Scissor rectangle (x, y, w, h) for the current draw buffer.
Values `x` and `y` define the origin, and `w` and `h` the size
of the rectangle in pixels. The scissor operation is only active
if `scissorTest=True`.
Usually, the scissor and viewport are set to the same rectangle
to prevent drawing operations from `spilling` into other regions
of the screen. For instance, calling `clearBuffer` will only
clear within the scissor rectangle.
Setting the scissor rectangle but not the viewport will restrict
drawing within the defined region (like a rectangular aperture),
not changing the positions of stimuli.
"""
return self._scissor
@scissor.setter
def scissor(self, value):
self._scissor = numpy.array(value, int)
GL.glScissor(*self._scissor)
@property
def scissorTest(self):
"""`True` if scissor testing is enabled."""
return self._scissorTest
@scissorTest.setter
def scissorTest(self, value):
if value is True:
GL.glEnable(GL.GL_SCISSOR_TEST)
elif value is False:
GL.glDisable(GL.GL_SCISSOR_TEST)
else:
raise TypeError("Value must be boolean.")
self._scissorTest = value
@property
def stencilTest(self):
"""`True` if stencil testing is enabled."""
return self._stencilTest
@stencilTest.setter
def stencilTest(self, value):
if value is True:
GL.glEnable(GL.GL_STENCIL_TEST)
elif value is False:
GL.glDisable(GL.GL_STENCIL_TEST)
else:
raise TypeError("Value must be boolean.")
self._stencilTest = value
@property
def nearClip(self):
"""Distance to the near clipping plane in meters."""
return self._nearClip
@nearClip.setter
def nearClip(self, value):
self._nearClip = value
@property
def farClip(self):
"""Distance to the far clipping plane in meters."""
return self._farClip
@farClip.setter
def farClip(self, value):
self._farClip = value
@property
def projectionMatrix(self):
"""Projection matrix defined as a 4x4 numpy array."""
return self._projectionMatrix
@projectionMatrix.setter
def projectionMatrix(self, value):
self._projectionMatrix = numpy.asarray(value, numpy.float32)
assert self._projectionMatrix.shape == (4, 4)
@property
def viewMatrix(self):
"""View matrix defined as a 4x4 numpy array."""
return self._viewMatrix
@viewMatrix.setter
def viewMatrix(self, value):
self._viewMatrix = numpy.asarray(value, numpy.float32)
assert self._viewMatrix.shape == (4, 4)
@property
def eyeOffset(self):
"""Eye offset in centimeters.
This value is used by `setPerspectiveView` to apply a lateral
offset to the view, therefore it must be set prior to calling it. Use a
positive offset for the right eye, and a negative one for the left.
Offsets should be the distance to from the middle of the face to the
center of the eye, or half the inter-ocular distance.
"""
return self._eyeOffset * 100.0
@eyeOffset.setter
def eyeOffset(self, value):
self._eyeOffset = value / 100.0
@property
def convergeOffset(self):
"""Convergence offset from monitor in centimeters.
This is value corresponds to the offset from screen plane to set the
convergence plane (or point for `toe-in` projections). Positive offsets
move the plane farther away from the viewer, while negative offsets
nearer. This value is used by `setPerspectiveView` and should be set
before calling it to take effect.
Notes
-----
* This value is only applicable for `setToeIn` and `setOffAxisView`.
"""
return self._convergeOffset * 100.0
@convergeOffset.setter
def convergeOffset(self, value):
self._convergeOffset = value / 100.0
def setOffAxisView(self, applyTransform=True, clearDepth=True):
"""Set an off-axis projection.
Create an off-axis projection for subsequent rendering calls. Sets the
`viewMatrix` and `projectionMatrix` accordingly so the scene origin is
on the screen plane. If `eyeOffset` is correct and the view distance and
screen size is defined in the monitor configuration, the resulting view
will approximate `ortho-stereo` viewing.
The convergence plane can be adjusted by setting `convergeOffset`. By
default, the convergence plane is set to the screen plane. Any points
on the screen plane will have zero disparity.
Parameters
----------
applyTransform : bool
Apply transformations after computing them in immediate mode. Same
as calling :py:attr:`~Window.applyEyeTransform()` afterwards.
clearDepth : bool, optional
Clear the depth buffer.
"""
scrDistM = 0.5 if self.scrDistCM is None else self.scrDistCM / 100.0
scrWidthM = 0.5 if self.scrWidthCM is None else self.scrWidthCM / 100.0
# Not in full screen mode? Need to compute the dimensions of the display
# area to ensure disparities are correct even when in windowed-mode.
aspect = self.size[0] / self.size[1]
if not self._isFullScr:
scrWidthM = (self.size[0] / self.scrWidthPIX) * scrWidthM
frustum = viewtools.computeFrustum(
scrWidthM, # width of screen
aspect, # aspect ratio
scrDistM, # distance to screen
eyeOffset=self._eyeOffset,
convergeOffset=self._convergeOffset,
nearClip=self._nearClip,
farClip=self._farClip)
self._projectionMatrix = viewtools.perspectiveProjectionMatrix(*frustum)
# translate away from screen
self._viewMatrix = numpy.identity(4, dtype=numpy.float32)
self._viewMatrix[0, 3] = -self._eyeOffset # apply eye offset
self._viewMatrix[2, 3] = -scrDistM # displace scene away from viewer
if applyTransform:
self.applyEyeTransform(clearDepth=clearDepth)
def setToeInView(self, applyTransform=True, clearDepth=True):
"""Set toe-in projection.
Create a toe-in projection for subsequent rendering calls. Sets the
`viewMatrix` and `projectionMatrix` accordingly so the scene origin is
on the screen plane. The value of `convergeOffset` will define the
convergence point of the view, which is offset perpendicular to the
center of the screen plane. Points falling on a vertical line at the
convergence point will have zero disparity.
Parameters
----------
applyTransform : bool
Apply transformations after computing them in immediate mode. Same
as calling :py:attr:`~Window.applyEyeTransform()` afterwards.
clearDepth : bool, optional
Clear the depth buffer.
Notes
-----
* This projection mode is only 'correct' if the viewer's eyes are
converged at the convergence point. Due to perspective, this
projection introduces vertical disparities which increase in magnitude
with eccentricity. Use `setOffAxisView` if you want to display
something the viewer can look around the screen comfortably.
"""
scrDistM = 0.5 if self.scrDistCM is None else self.scrDistCM / 100.0
scrWidthM = 0.5 if self.scrWidthCM is None else self.scrWidthCM / 100.0
# Not in full screen mode? Need to compute the dimensions of the display
# area to ensure disparities are correct even when in windowed-mode.
aspect = self.size[0] / self.size[1]
if not self._isFullScr:
scrWidthM = (self.size[0] / self.scrWidthPIX) * scrWidthM
frustum = viewtools.computeFrustum(
scrWidthM, # width of screen
aspect, # aspect ratio
scrDistM, # distance to screen
nearClip=self._nearClip,
farClip=self._farClip)
self._projectionMatrix = viewtools.perspectiveProjectionMatrix(*frustum)
# translate away from screen
eyePos = (self._eyeOffset, 0.0, scrDistM)
convergePoint = (0.0, 0.0, self.convergeOffset)
self._viewMatrix = viewtools.lookAt(eyePos, convergePoint)
if applyTransform:
self.applyEyeTransform(clearDepth=clearDepth)
def setPerspectiveView(self, applyTransform=True, clearDepth=True):
"""Set the projection and view matrix to render with perspective.
Matrices are computed using values specified in the monitor
configuration with the scene origin on the screen plane. Calculations
assume units are in meters. If `eyeOffset != 0`, the view will be
transformed laterally, however the frustum shape will remain the
same.
Note that the values of :py:attr:`~Window.projectionMatrix` and
:py:attr:`~Window.viewMatrix` will be replaced when calling this
function.
Parameters
----------
applyTransform : bool
Apply transformations after computing them in immediate mode. Same
as calling :py:attr:`~Window.applyEyeTransform()` afterwards if
`False`.
clearDepth : bool, optional
Clear the depth buffer.
"""
# NB - we should eventually compute these matrices lazily since they may
# not change over the course of an experiment under most circumstances.
#
scrDistM = 0.5 if self.scrDistCM is None else self.scrDistCM / 100.0
scrWidthM = 0.5 if self.scrWidthCM is None else self.scrWidthCM / 100.0
# Not in full screen mode? Need to compute the dimensions of the display
# area to ensure disparities are correct even when in windowed-mode.
aspect = self.size[0] / self.size[1]
if not self._isFullScr:
scrWidthM = (self.size[0] / self.scrWidthPIX) * scrWidthM
frustum = viewtools.computeFrustum(
scrWidthM, # width of screen
aspect, # aspect ratio
scrDistM, # distance to screen
nearClip=self._nearClip,
farClip=self._farClip)
self._projectionMatrix = \
viewtools.perspectiveProjectionMatrix(*frustum, dtype=numpy.float32)
# translate away from screen
self._viewMatrix = numpy.identity(4, dtype=numpy.float32)
self._viewMatrix[0, 3] = -self._eyeOffset # apply eye offset
self._viewMatrix[2, 3] = -scrDistM # displace scene away from viewer
if applyTransform:
self.applyEyeTransform(clearDepth=clearDepth)
def applyEyeTransform(self, clearDepth=True):
"""Apply the current view and projection matrices.
Matrices specified by attributes :py:attr:`~Window.viewMatrix` and
:py:attr:`~Window.projectionMatrix` are applied using 'immediate mode'
OpenGL functions. Subsequent drawing operations will be affected until
:py:attr:`~Window.flip()` is called.
All transformations in ``GL_PROJECTION`` and ``GL_MODELVIEW`` matrix
stacks will be cleared (set to identity) prior to applying.
Parameters
----------
clearDepth : bool
Clear the depth buffer. This may be required prior to rendering 3D
objects.
Examples
--------
Using a custom view and projection matrix::
# Must be called every frame since these values are reset after
# `flip()` is called!
win.viewMatrix = viewtools.lookAt( ... )
win.projectionMatrix = viewtools.perspectiveProjectionMatrix( ... )
win.applyEyeTransform()
# draw 3D objects here ...
"""
# apply the projection and view transformations
if hasattr(self, '_projectionMatrix'):
GL.glMatrixMode(GL.GL_PROJECTION)
GL.glLoadIdentity()
projMat = self._projectionMatrix.ctypes.data_as(
ctypes.POINTER(ctypes.c_float))
GL.glMultTransposeMatrixf(projMat)
if hasattr(self, '_viewMatrix'):
GL.glMatrixMode(GL.GL_MODELVIEW)
GL.glLoadIdentity()
viewMat = self._viewMatrix.ctypes.data_as(
ctypes.POINTER(ctypes.c_float))
GL.glMultTransposeMatrixf(viewMat)
oldDepthMask = self.depthMask
if clearDepth:
GL.glDepthMask(GL.GL_TRUE)
GL.glClear(GL.GL_DEPTH_BUFFER_BIT)
if oldDepthMask is False: # return to old state if needed
GL.glDepthMask(GL.GL_FALSE)
def resetEyeTransform(self, clearDepth=True):
"""Restore the default projection and view settings to PsychoPy
defaults. Call this prior to drawing 2D stimuli objects (i.e.
GratingStim, ImageStim, Rect, etc.) if any eye transformations were
applied for the stimuli to be drawn correctly.
Parameters
----------
clearDepth : bool
Clear the depth buffer upon reset. This ensures successive draw
commands are not affected by previous data written to the depth
buffer. Default is `True`.
Notes
-----
* Calling :py:attr:`~Window.flip()` automatically resets the view and
projection to defaults. So you don't need to call this unless you are
mixing 3D and 2D stimuli.
Examples
--------
Going between 3D and 2D stimuli::
# 2D stimuli can be drawn before setting a perspective projection
win.setPerspectiveView()
# draw 3D stimuli here ...
win.resetEyeTransform()
# 2D stimuli can be drawn here again ...
win.flip()
"""
# should eventually have the same effect as calling _onResize(), so we
# need to add the retina mode stuff eventually
if hasattr(self, '_viewMatrix'):
self._viewMatrix = numpy.identity(4, dtype=numpy.float32)
if hasattr(self, '_projectionMatrix'):
self._projectionMatrix = viewtools.orthoProjectionMatrix(
-1, 1, -1, 1, -1, 1, dtype=numpy.float32)
self.applyEyeTransform(clearDepth)
def coordToRay(self, screenXY):
"""Convert a screen coordinate to a direction vector.
Takes a screen/window coordinate and computes a vector which projects
a ray from the viewpoint through it (line-of-sight). Any 3D point
touching the ray will appear at the screen coordinate.
Uses the current `viewport` and `projectionMatrix` to calculate the
vector. The vector is in eye-space, where the origin of the scene is
centered at the viewpoint and the forward direction aligned with the -Z
axis. A ray of (0, 0, -1) results from a point at the very center of the
screen assuming symmetric frustums.
Note that if you are using a flipped/mirrored view, you must invert your
supplied screen coordinates (`screenXY`) prior to passing them to this
function.
Parameters
----------
screenXY : array_like
X, Y screen coordinate. Must be in units of the window.
Returns
-------
ndarray
Normalized direction vector [x, y, z].
Examples
--------
Getting the direction vector between the mouse cursor and the eye::
mx, my = mouse.getPos()
dir = win.coordToRay((mx, my))
Set the position of a 3D stimulus object using the mouse, constrained to
a plane. The object origin will always be at the screen coordinate of
the mouse cursor::
# the eye position in the scene is defined by a rigid body pose
win.viewMatrix = camera.getViewMatrix()
win.applyEyeTransform()
# get the mouse location and calculate the intercept
mx, my = mouse.getPos()
ray = win.coordToRay([mx, my])
result = intersectRayPlane( # from mathtools
orig=camera.pos,
dir=camera.transformNormal(ray),
planeOrig=(0, 0, -10),
planeNormal=(0, 1, 0))
# if result is `None`, there is no intercept
if result is not None:
pos, dist = result
objModel.thePose.pos = pos
else:
objModel.thePose.pos = (0, 0, -10) # plane origin
If you don't define the position of the viewer with a `RigidBodyPose`,
you can obtain the appropriate eye position and rotate the ray by doing
the following::
pos = numpy.linalg.inv(win.viewMatrix)[:3, 3]
ray = win.coordToRay([mx, my]).dot(win.viewMatrix[:3, :3])
# then ...
result = intersectRayPlane(
orig=pos,
dir=ray,
planeOrig=(0, 0, -10),
planeNormal=(0, 1, 0))
"""
# put in units of pixels
if self.units == 'pix':
scrX, scrY = numpy.asarray(screenXY, numpy.float32)
else:
scrX, scrY = convertToPix(numpy.asarray([0, 0]),
numpy.asarray(screenXY),
units=self.units,
win=self)[:2]
# transform psychopy mouse coordinates to viewport coordinates
scrX = scrX + (self.size[0] / 2.)
scrY = scrY + (self.size[1] / 2.)
# get the NDC coordinates of the
projX = 2. * (scrX - self.viewport[0]) / self.viewport[2] - 1.
projY = 2. * (scrY - self.viewport[1]) / self.viewport[3] - 1.
vecNear = numpy.array((projX, projY, 0., 1.), dtype=numpy.float32)
vecFar = numpy.array((projX, projY, 1., 1.), dtype=numpy.float32)
# compute the inverse projection matrix
invPM = numpy.linalg.inv(self.projectionMatrix)
vecNear[:] = vecNear.dot(invPM.T)
vecFar[:] = vecFar.dot(invPM.T)
vecNear /= vecNear[3]
vecFar /= vecFar[3]
# direction vector, get rid of `w`
dirVec = vecFar[:3] - vecNear[:3]
return dirVec / numpy.linalg.norm(dirVec)
def getMovieFrame(self, buffer='front'):
"""Capture the current Window as an image.
Saves to stack for :py:attr:`~Window.saveMovieFrames()`. As of v1.81.00
this also returns the frame as a PIL image
This can be done at any time (usually after a :py:attr:`~Window.flip()`
command).
Frames are stored in memory until a :py:attr:`~Window.saveMovieFrames()`
command is issued. You can issue :py:attr:`~Window.getMovieFrame()` as
often as you like and then save them all in one go when finished.
The back buffer will return the frame that hasn't yet been 'flipped'
to be visible on screen but has the advantage that the mouse and any
other overlapping windows won't get in the way.
The default front buffer is to be called immediately after a
:py:attr:`~Window.flip()` and gives a complete copy of the screen at the
window's coordinates.
Parameters
----------
buffer : str, optional
Buffer to capture.
Returns
-------
Image
Buffer pixel contents as a PIL/Pillow image object.
"""
im = self._getFrame(buffer=buffer)
self.movieFrames.append(im)
return im
def _getFrame(self, rect=None, buffer='front'):
"""Return the current Window as an image.
"""
# GL.glLoadIdentity()
# do the reading of the pixels
if buffer == 'back' and self.useFBO:
GL.glReadBuffer(GL.GL_COLOR_ATTACHMENT0_EXT)
elif buffer == 'back':
GL.glReadBuffer(GL.GL_BACK)
elif buffer == 'front':
if self.useFBO:
GL.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, 0)
GL.glReadBuffer(GL.GL_FRONT)
else:
raise ValueError("Requested read from buffer '{}' but should be "
"'front' or 'back'".format(buffer))
if rect:
x, y = self.size # of window, not image
imType = 'RGBA' # not tested with anything else
# box corners in pix
left = int((rect[0] / 2. + 0.5) * x)
bottom = int((rect[3] / 2. + 0.5) * y)
w = int((rect[2] / 2. + 0.5) * x) - left
h = int((rect[1] / 2. + 0.5) * y) - bottom
else:
left = bottom = 0
w, h = self.size
# http://www.opengl.org/sdk/docs/man/xhtml/glGetTexImage.xml
bufferDat = (GL.GLubyte * (4 * w * h))()
GL.glReadPixels(left, bottom, w, h,
GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, bufferDat)
try:
im = Image.fromstring(mode='RGBA', size=(w, h),
data=bufferDat)
except Exception:
im = Image.frombytes(mode='RGBA', size=(w, h),
data=bufferDat)
im = im.transpose(Image.FLIP_TOP_BOTTOM)
im = im.convert('RGB')
if self.useFBO and buffer == 'front':
GL.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, self.frameBuffer)
return im
@property
def screenshot(self):
return self._getFrame()
def saveMovieFrames(self, fileName, codec='libx264',
fps=30, clearFrames=True):
"""Writes any captured frames to disk.
Will write any format that is understood by PIL (tif, jpg, png, ...)
Parameters
----------
filename : str
Name of file, including path. The extension at the end of the file
determines the type of file(s) created. If an image type (e.g. .png)
is given, then multiple static frames are created. If it is .gif
then an animated GIF image is created (although you will get higher
quality GIF by saving PNG files and then combining them in dedicated
image manipulation software, such as GIMP). On Windows and Linux
`.mpeg` files can be created if `pymedia` is installed. On macOS
`.mov` files can be created if the pyobjc-frameworks-QTKit is
installed. Unfortunately the libs used for movie generation can be
flaky and poor quality. As for animated GIFs, better results can be
achieved by saving as individual .png frames and then combining them
into a movie using software like ffmpeg.
codec : str, optional
The codec to be used **by moviepy** for mp4/mpg/mov files. If
`None` then the default will depend on file extension. Can be
one of ``libx264``, ``mpeg4`` for mp4/mov files. Can be
``rawvideo``, ``png`` for avi files (not recommended). Can be
``libvorbis`` for ogv files. Default is ``libx264``.
fps : int, optional
The frame rate to be used throughout the movie. **Only for
quicktime (.mov) movies.**. Default is `30`.
clearFrames : bool, optional
Set this to `False` if you want the frames to be kept for
additional calls to ``saveMovieFrames``. Default is `True`.
Examples
--------
Writes a series of static frames as frame001.tif, frame002.tif etc.::
myWin.saveMovieFrames('frame.tif')
As of PsychoPy 1.84.1 the following are written with moviepy::
myWin.saveMovieFrames('stimuli.mp4') # codec = 'libx264' or 'mpeg4'
myWin.saveMovieFrames('stimuli.mov')
myWin.saveMovieFrames('stimuli.gif')
"""
fileRoot, fileExt = os.path.splitext(fileName)
fileExt = fileExt.lower() # easier than testing both later
if len(self.movieFrames) == 0:
logging.error('no frames to write - did you forget to update '
'your window or call win.getMovieFrame()?')
return
else:
logging.info('Writing %i frames to %s' % (len(self.movieFrames),
fileName))
if fileExt in ['.gif', '.mpg', '.mpeg', '.mp4', '.mov']:
# lazy loading of moviepy.editor (rarely needed)
from moviepy.editor import ImageSequenceClip
# save variety of movies with moviepy
numpyFrames = []
for frame in self.movieFrames:
numpyFrames.append(numpy.array(frame))
clip = ImageSequenceClip(numpyFrames, fps=fps)
if fileExt == '.gif':
clip.write_gif(fileName, fps=fps, fuzz=0, opt='nq')
else:
clip.write_videofile(fileName, codec=codec)
elif len(self.movieFrames) == 1:
# save an image using pillow
self.movieFrames[0].save(fileName)
else:
frmc = numpy.ceil(numpy.log10(len(self.movieFrames) + 1))
frame_name_format = "%s%%0%dd%s" % (fileRoot, frmc, fileExt)
for frameN, thisFrame in enumerate(self.movieFrames):
thisFileName = frame_name_format % (frameN + 1,)
thisFrame.save(thisFileName)
if clearFrames:
self.movieFrames = []
def _getRegionOfFrame(self, rect=(-1, 1, 1, -1), buffer='front',
power2=False, squarePower2=False):
"""Deprecated function, here for historical reasons. You may now use
`:py:attr:`~Window._getFrame()` and specify a rect to get a sub-region,
just as used here.
power2 can be useful with older OpenGL versions to avoid interpolation
in :py:attr:`PatchStim`. If power2 or squarePower2, it will expand rect
dimensions up to next power of two. squarePower2 uses the max
dimensions. You need to check what your hardware & OpenGL supports,
and call :py:attr:`~Window._getRegionOfFrame()` as appropriate.
"""
# Ideally: rewrite using GL frame buffer object; glReadPixels == slow
region = self._getFrame(rect=rect, buffer=buffer)
if power2 or squarePower2: # use to avoid interpolation in PatchStim
if squarePower2:
maxsize = max(region.size)
xPowerOf2 = int(2**numpy.ceil(numpy.log2(maxsize)))
yPowerOf2 = xPowerOf2
else:
xPowerOf2 = int(2**numpy.ceil(numpy.log2(region.size[0])))
yPowerOf2 = int(2**numpy.ceil(numpy.log2(region.size[1])))
imP2 = Image.new('RGBA', (xPowerOf2, yPowerOf2))
# paste centered
imP2.paste(region, (int(xPowerOf2 / 2. - region.size[0] / 2.),
int(yPowerOf2 / 2.) - region.size[1] / 2))
region = imP2
return region
def close(self):
"""Close the window (and reset the Bits++ if necess).
"""
self._closed = True
self.backend.close() # moved here, dereferencing the window prevents
# backend specific actions to take place
try:
openWindows.remove(self)
except Exception:
pass
try:
self.mouseVisible = True
except Exception:
# can cause unimportant "'NoneType' object is not callable"
pass
try:
if self.bits is not None:
self.bits.reset()
except Exception:
pass
try:
logging.flush()
except Exception:
pass
def fps(self):
"""Report the frames per second since the last call to this function
(or since the window was created if this is first call)"""
fps = self.frames / self.frameClock.getTime()
self.frameClock.reset()
self.frames = 0
return fps
@property
def depthTest(self):
"""`True` if depth testing is enabled."""
return self._depthTest
@depthTest.setter
def depthTest(self, value):
if value is True:
GL.glEnable(GL.GL_DEPTH_TEST)
elif value is False:
GL.glDisable(GL.GL_DEPTH_TEST)
else:
raise TypeError("Value must be boolean.")
self._depthTest = value
@property
def depthFunc(self):
"""Depth test comparison function for rendering."""
return self._depthFunc
@depthFunc.setter
def depthFunc(self, value):
depthFuncs = {'never': GL.GL_NEVER, 'less': GL.GL_LESS,
'equal': GL.GL_EQUAL, 'lequal': GL.GL_LEQUAL,
'greater': GL.GL_GREATER, 'notequal': GL.GL_NOTEQUAL,
'gequal': GL.GL_GEQUAL, 'always': GL.GL_ALWAYS}
GL.glDepthFunc(depthFuncs[value])
self._depthFunc = value
@property
def depthMask(self):
"""`True` if depth masking is enabled. Writing to the depth buffer will
be disabled.
"""
return self._depthMask
@depthMask.setter
def depthMask(self, value):
if value is True:
GL.glDepthMask(GL.GL_TRUE)
elif value is False:
GL.glDepthMask(GL.GL_FALSE)
else:
raise TypeError("Value must be boolean.")
self._depthMask = value
@property
def cullFaceMode(self):
"""Face culling mode, either `back`, `front` or `both`."""
return self._cullFaceMode
@cullFaceMode.setter
def cullFaceMode(self, value):
if value == 'back':
GL.glCullFace(GL.GL_BACK)
elif value == 'front':
GL.glCullFace(GL.GL_FRONT)
elif value == 'both':
GL.glCullFace(GL.GL_FRONT_AND_BACK)
else:
raise ValueError('Invalid face cull mode.')
self._cullFaceMode = value
@property
def cullFace(self):
"""`True` if face culling is enabled.`"""
return self._cullFace
@cullFace.setter
def cullFace(self, value):
if value is True:
GL.glEnable(GL.GL_CULL_FACE)
elif value is False:
GL.glDisable(GL.GL_CULL_FACE)
else:
raise TypeError('Value must be type `bool`.')
self._cullFace = value
@property
def frontFace(self):
"""Face winding order to define front, either `ccw` or `cw`."""
return self._frontFace
@frontFace.setter
def frontFace(self, value):
if value == 'ccw':
GL.glFrontFace(GL.GL_CCW)
elif value == 'cw':
GL.glFrontFace(GL.GL_CW)
else:
raise ValueError('Invalid value, must be `ccw` or `cw`.')
self._frontFace = value
@property
def draw3d(self):
"""`True` if 3D drawing is enabled on this window."""
return self._draw3d
@draw3d.setter
def draw3d(self, value):
if value is True:
if self.depthMask is False:
self.depthMask = True
if self.depthTest is False:
self.depthTest = True
if self.cullFace is False:
self.cullFace = True
elif value is False:
if self.depthMask is True:
self.depthMask = False
if self.depthTest is True:
self.depthTest = False
if self.cullFace is True:
self.cullFace = False
else:
raise TypeError('Value must be type `bool`.')
self._draw3d = value
@attributeSetter
def blendMode(self, blendMode):
"""Blend mode to use."""
self.__dict__['blendMode'] = blendMode
if blendMode == 'avg':
GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA)
if hasattr(self, '_shaders'):
self._progSignedFrag = self._shaders['signedColor']
self._progSignedTex = self._shaders['signedTex']
self._progSignedTexMask = self._shaders['signedTexMask']
self._progSignedTexMask1D = self._shaders['signedTexMask1D']
self._progImageStim = self._shaders['imageStim']
elif blendMode == 'add':
GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE)
if hasattr(self, '_shaders'):
self._progSignedFrag = self._shaders['signedColor_adding']
self._progSignedTex = self._shaders['signedTex_adding']
self._progSignedTexMask = self._shaders['signedTexMask_adding']
tmp = self._shaders['signedTexMask1D_adding']
self._progSignedTexMask1D = tmp
self._progImageStim = self._shaders['imageStim_adding']
else:
raise ValueError("Window blendMode should be set to 'avg' or 'add'"
" but we received the value {}"
.format(repr(blendMode)))
def setBlendMode(self, blendMode, log=None):
"""Usually you can use 'stim.attribute = value' syntax instead,
but use this method if you need to suppress the log message.
"""
setAttribute(self, 'blendMode', blendMode, log)
@property
def colorSpace(self):
"""The name of the color space currently being used
Value should be: a string or None
For strings and hex values this is not needed.
If None the default colorSpace for the stimulus is
used (defined during initialisation).
Please note that changing colorSpace does not change stimulus
parameters. Thus you usually want to specify colorSpace before
setting the color. Example::
# A light green text
stim = visual.TextStim(win, 'Color me!',
color=(0, 1, 0), colorSpace='rgb')
# An almost-black text
stim.colorSpace = 'rgb255'
# Make it light green again
stim.color = (128, 255, 128)
"""
if hasattr(self, '_colorSpace'):
return self._colorSpace
else:
return 'rgb'
@colorSpace.setter
def colorSpace(self, value):
if value in colorSpaces:
self._colorSpace = value
else:
logging.error(f"'{value}' is not a valid color space")
@property
def color(self):
"""Set the color of the window.
This command sets the color that the blank screen will have on the
next clear operation. As a result it effectively takes TWO
:py:attr:`~Window.flip()` operations to become visible (the first uses
the color to create the new screen, the second presents that screen to
the viewer). For this reason, if you want to changed background color of
the window "on the fly", it might be a better idea to draw a
:py:attr:`Rect` that fills the whole window with the desired
:py:attr:`Rect.fillColor` attribute. That'll show up on first flip.
See other stimuli (e.g. :py:attr:`GratingStim.color`)
for more info on the color attribute which essentially works the same on
all PsychoPy stimuli.
See :ref:`colorspaces` for further information about the ways to
specify colors and their various implications.
"""
if hasattr(self, '_color'):
return getattr(self._color, self.colorSpace)
@color.setter
def color(self, value):
if isinstance(value, Color):
# If supplied with a color object, set as that
self._color = value
else:
# Otherwise, use it to make a color object
self._color = Color(value, self.colorSpace)
if not self._color:
self._color = Color()
logging.error(f"'{value}' is not a valid {self.colorSpace} color")
# if it is None then this will be done during window setup
if self.backend is not None:
self.backend.setCurrent() # make sure this window is active
GL.glClearColor(*self._color.render('rgba1'))
def setColor(self, color, colorSpace=None, operation='', log=None):
"""Usually you can use ``stim.attribute = value`` syntax instead,
but use this method if you want to set color and colorSpace
simultaneously.
See :py:attr:`~Window.color` for documentation on colors.
"""
self.colorSpace = colorSpace
self.color = color
def setRGB(self, newRGB):
"""Deprecated: As of v1.61.00 please use `setColor()` instead
"""
self.setColor(newRGB, colorSpace="rgb")
@property
def rgb(self):
if hasattr(self, "_color"):
return self._color.render("rgb")
@rgb.setter
def rgb(self, value):
self.color = Color(value, 'rgb')
def _setupGamma(self, gammaVal):
"""A private method to work out how to handle gamma for this Window
given that the user might have specified an explicit value, or maybe
gave a Monitor.
"""
# determine which gamma value to use (or native ramp)
if gammaVal is not None:
self._checkGamma()
self.useNativeGamma = False
elif not self.monitor.gammaIsDefault():
if self.monitor.getGamma() is not None:
self.__dict__['gamma'] = self.monitor.getGamma()
self.useNativeGamma = False
else:
self.__dict__['gamma'] = None # gamma wasn't set anywhere
self.useNativeGamma = True
# then try setting it
if self.useNativeGamma:
if self.autoLog:
logging.info('Using gamma table of operating system')
else:
if self.autoLog:
logging.info('Using gamma: self.gamma' + str(self.gamma))
self.gamma = gammaVal # using either pygame or bits++
@attributeSetter
def gamma(self, gamma):
"""Set the monitor gamma for linearization.
Warnings
--------
Don't use this if using a Bits++ or Bits#, as it overrides monitor
settings.
"""
self._checkGamma(gamma)
if self.bits is not None:
msg = ("Do not use try to set the gamma of a window with "
"Bits++/Bits# enabled. It was ambiguous what should "
"happen. Use the setGamma() function of the bits box "
"instead")
raise DeprecationWarning(msg)
self.backend.gamma = self.__dict__['gamma']
def setGamma(self, gamma, log=None):
"""Usually you can use 'stim.attribute = value' syntax instead,
but use this method if you need to suppress the log message.
"""
setAttribute(self, 'gamma', gamma, log)
@attributeSetter
def gammaRamp(self, newRamp):
"""Sets the hardware CLUT using a specified 3xN array of floats ranging
between 0.0 and 1.0.
Array must have a number of rows equal to 2 ^ max(bpc).
"""
self.backend.gammaRamp = newRamp
def _checkGamma(self, gamma=None):
if gamma is None:
gamma = self.gamma
if isinstance(gamma, (float, int)):
self.__dict__['gamma'] = [gamma] * 3
elif hasattr(gamma, '__iter__'):
self.__dict__['gamma'] = gamma
else:
raise ValueError('gamma must be a numeric scalar or iterable')
def setScale(self, units, font='dummyFont', prevScale=(1.0, 1.0)):
"""DEPRECATED: this method used to be used to switch between units for
stimulus drawing but this is now handled by the stimuli themselves and
the window should always be left in units of 'pix'
"""
if self.useRetina:
retinaScale = 2.0
else:
retinaScale = 1.0
# then unit-specific changes
if units == "norm":
thisScale = numpy.array([1.0, 1.0])
elif units == "height":
thisScale = numpy.array([2.0 * self.size[1] / self.size[0], 2.0])
elif units in ["pix", "pixels"]:
thisScale = 2.0 / numpy.array(self.size) * retinaScale
elif units == "cm":
# windowPerCM = windowPerPIX / CMperPIX
# = (window/winPIX) / (scrCm/scrPIX)
if self.scrWidthCM in [0, None] or self.scrWidthPIX in [0, None]:
logging.error('you did not give the width of the screen (pixels'
' and cm). Check settings in MonitorCentre.')
core.wait(1.0)
core.quit()
thisScale = ((numpy.array([2.0, 2.0]) / self.size * retinaScale)
/ (self.scrWidthCM / self.scrWidthPIX))
elif units in ["deg", "degs"]:
# windowPerDeg = winPerCM * CMperDEG
# = winPerCM * tan(pi/180) * distance
if ((self.scrWidthCM in [0, None]) or
(self.scrWidthPIX in [0, None])):
logging.error('you did not give the width of the screen (pixels'
' and cm). Check settings in MonitorCentre.')
core.wait(1.0)
core.quit()
cmScale = ((numpy.array([2.0, 2.0]) / self.size) * retinaScale /
(self.scrWidthCM / self.scrWidthPIX))
thisScale = cmScale * 0.017455 * self.scrDistCM
elif units == "stroke_font":
lw = 2 * font.letterWidth
thisScale = numpy.array([lw, lw] / self.size * retinaScale / 38.0)
# actually set the scale as appropriate
# allows undoing of a previous scaling procedure
thisScale = thisScale / numpy.asarray(prevScale)
GL.glScalef(thisScale[0], thisScale[1], 1.0)
return thisScale
def _checkMatchingSizes(self, requested, actual):
"""Checks whether the requested and actual screen sizes differ.
If not then a warning is output and the window size is set to actual
"""
if list(requested) != list(actual):
logging.warning("User requested fullscreen with size %s, "
"but screen is actually %s. Using actual size" %
(requested, actual))
self.clientSize = numpy.array(actual)
def _setupGL(self):
"""Setup OpenGL state for this window.
"""
# setup screen color
self.color = self.color # call attributeSetter
GL.glClearDepth(1.0)
# viewport or drawable area of the framebuffer
self.viewport = self.scissor = \
(0, 0, self.frameBufferSize[0], self.frameBufferSize[1])
self.scissorTest = True
self.stencilTest = False
GL.glMatrixMode(GL.GL_PROJECTION) # Reset the projection matrix
GL.glLoadIdentity()
GL.gluOrtho2D(-1, 1, -1, 1)
GL.glMatrixMode(GL.GL_MODELVIEW) # Reset the modelview matrix
GL.glLoadIdentity()
self.depthTest = False
# GL.glEnable(GL.GL_DEPTH_TEST) # Enables Depth Testing
# GL.glDepthFunc(GL.GL_LESS) # The Type Of Depth Test To Do
GL.glEnable(GL.GL_BLEND)
GL.glShadeModel(GL.GL_SMOOTH) # Color Shading (FLAT or SMOOTH)
GL.glEnable(GL.GL_POINT_SMOOTH)
# check for GL_ARB_texture_float
# (which is needed for shaders to be useful)
# this needs to be done AFTER the context has been created
if not GL.gl_info.have_extension('GL_ARB_texture_float'):
self._haveShaders = False
GL.glClear(GL.GL_COLOR_BUFFER_BIT)
# identify gfx card vendor
self.glVendor = GL.gl_info.get_vendor().lower()
requestedFBO = self.useFBO
if self._haveShaders: # do this after setting up FrameBufferObject
self._setupShaders()
else:
self.useFBO = False
if self.useFBO:
success = self._setupFrameBuffer()
if not success:
self.useFBO = False
if requestedFBO and not self.useFBO:
logging.warning("Framebuffer object (FBO) not supported on "
"this graphics card")
if self.blendMode == 'add' and not self.useFBO:
logging.warning("Framebuffer object (FBO) is required for "
"blendMode='add'. Reverting to blendMode='avg'")
self.blendMode = 'avg'
def _setupShaders(self):
self._progSignedTexFont = _shaders.compileProgram(
_shaders.vertSimple, _shaders.fragSignedColorTexFont)
self._progFBOtoFrame = _shaders.compileProgram(
_shaders.vertSimple, _shaders.fragFBOtoFrame)
self._shaders = {}
self._shaders['signedColor'] = _shaders.compileProgram(
_shaders.vertSimple, _shaders.fragSignedColor)
self._shaders['signedColor_adding'] = _shaders.compileProgram(
_shaders.vertSimple, _shaders.fragSignedColor_adding)
self._shaders['signedTex'] = _shaders.compileProgram(
_shaders.vertSimple, _shaders.fragSignedColorTex)
self._shaders['signedTexMask'] = _shaders.compileProgram(
_shaders.vertSimple, _shaders.fragSignedColorTexMask)
self._shaders['signedTexMask1D'] = _shaders.compileProgram(
_shaders.vertSimple, _shaders.fragSignedColorTexMask1D)
self._shaders['signedTex_adding'] = _shaders.compileProgram(
_shaders.vertSimple, _shaders.fragSignedColorTex_adding)
self._shaders['signedTexMask_adding'] = _shaders.compileProgram(
_shaders.vertSimple, _shaders.fragSignedColorTexMask_adding)
self._shaders['signedTexMask1D_adding'] = _shaders.compileProgram(
_shaders.vertSimple, _shaders.fragSignedColorTexMask1D_adding)
self._shaders['imageStim'] = _shaders.compileProgram(
_shaders.vertSimple, _shaders.fragImageStim)
self._shaders['imageStim_adding'] = _shaders.compileProgram(
_shaders.vertSimple, _shaders.fragImageStim_adding)
self._shaders['stim3d_phong'] = {}
# Create shader flags, these are used as keys to pick the appropriate
# shader for the given material and lighting configuration.
shaderFlags = []
for i in range(0, 8 + 1):
for j in product((True, False), repeat=1):
shaderFlags.append((i, j[0]))
# Compile shaders based on generated flags.
for flag in shaderFlags:
# Define GLSL preprocessor values to enable code paths for specific
# material properties.
srcDefs = {'MAX_LIGHTS': flag[0]}
if flag[1]: # has diffuse texture map
srcDefs['DIFFUSE_TEXTURE'] = 1
# embed #DEFINE statements in GLSL source code
vertSrc = gltools.embedShaderSourceDefs(
_shaders.vertPhongLighting, srcDefs)
fragSrc = gltools.embedShaderSourceDefs(
_shaders.fragPhongLighting, srcDefs)
# build a shader program
prog = gltools.createProgramObjectARB()
vertexShader = gltools.compileShaderObjectARB(
vertSrc, GL.GL_VERTEX_SHADER_ARB)
fragmentShader = gltools.compileShaderObjectARB(
fragSrc, GL.GL_FRAGMENT_SHADER_ARB)
gltools.attachObjectARB(prog, vertexShader)
gltools.attachObjectARB(prog, fragmentShader)
gltools.linkProgramObjectARB(prog)
gltools.detachObjectARB(prog, vertexShader)
gltools.detachObjectARB(prog, fragmentShader)
gltools.deleteObjectARB(vertexShader)
gltools.deleteObjectARB(fragmentShader)
# set the flag
self._shaders['stim3d_phong'][flag] = prog
def _setupFrameBuffer(self):
# Setup framebuffer
self.frameBuffer = GL.GLuint()
GL.glGenFramebuffersEXT(1, ctypes.byref(self.frameBuffer))
GL.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, self.frameBuffer)
# Create texture to render to
self.frameTexture = GL.GLuint()
GL.glGenTextures(1, ctypes.byref(self.frameTexture))
GL.glBindTexture(GL.GL_TEXTURE_2D, self.frameTexture)
GL.glTexParameteri(GL.GL_TEXTURE_2D,
GL.GL_TEXTURE_MAG_FILTER,
GL.GL_LINEAR)
GL.glTexParameteri(GL.GL_TEXTURE_2D,
GL.GL_TEXTURE_MIN_FILTER,
GL.GL_LINEAR)
GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA32F_ARB,
int(self.size[0]), int(self.size[1]), 0,
GL.GL_RGBA, GL.GL_FLOAT, None)
# attach texture to the frame buffer
GL.glFramebufferTexture2DEXT(GL.GL_FRAMEBUFFER_EXT,
GL.GL_COLOR_ATTACHMENT0_EXT,
GL.GL_TEXTURE_2D, self.frameTexture, 0)
# add a stencil buffer
self._stencilTexture = GL.GLuint()
GL.glGenRenderbuffersEXT(1, ctypes.byref(
self._stencilTexture)) # like glGenTextures
GL.glBindRenderbufferEXT(GL.GL_RENDERBUFFER_EXT, self._stencilTexture)
GL.glRenderbufferStorageEXT(GL.GL_RENDERBUFFER_EXT,
GL.GL_DEPTH24_STENCIL8_EXT,
int(self.size[0]), int(self.size[1]))
GL.glFramebufferRenderbufferEXT(GL.GL_FRAMEBUFFER_EXT,
GL.GL_DEPTH_ATTACHMENT_EXT,
GL.GL_RENDERBUFFER_EXT,
self._stencilTexture)
GL.glFramebufferRenderbufferEXT(GL.GL_FRAMEBUFFER_EXT,
GL.GL_STENCIL_ATTACHMENT_EXT,
GL.GL_RENDERBUFFER_EXT,
self._stencilTexture)
status = GL.glCheckFramebufferStatusEXT(GL.GL_FRAMEBUFFER_EXT)
if status != GL.GL_FRAMEBUFFER_COMPLETE_EXT:
logging.error("Error in framebuffer activation")
# UNBIND THE FRAME BUFFER OBJECT THAT WE HAD CREATED
GL.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, 0)
return False
GL.glDisable(GL.GL_TEXTURE_2D)
# clear the buffers (otherwise the texture memory can contain
# junk from other app)
GL.glClear(GL.GL_COLOR_BUFFER_BIT)
GL.glClear(GL.GL_STENCIL_BUFFER_BIT)
GL.glClear(GL.GL_DEPTH_BUFFER_BIT)
return True
@attributeSetter
def mouseVisible(self, visibility):
"""Sets the visibility of the mouse cursor.
If Window was initialized with ``allowGUI=False`` then the mouse is
initially set to invisible, otherwise it will initially be visible.
Usage::
win.mouseVisible = False
win.mouseVisible = True
"""
self.backend.setMouseVisibility(visibility)
self.__dict__['mouseVisible'] = visibility
def setMouseVisible(self, visibility, log=None):
"""Usually you can use 'stim.attribute = value' syntax instead,
but use this method if you need to suppress the log message."""
setAttribute(self, 'mouseVisible', visibility, log)
def setMouseType(self, name='arrow'):
"""Change the appearance of the cursor for this window. Cursor types
provide contextual hints about how to interact with on-screen objects.
The graphics used 'standard cursors' provided by the operating system.
They may vary in appearance and hot spot location across platforms. The
following names are valid on most platforms:
* ``arrow`` : Default pointer.
* ``ibeam`` : Indicates text can be edited.
* ``crosshair`` : Crosshair with hot-spot at center.
* ``hand`` : A pointing hand.
* ``hresize`` : Double arrows pointing horizontally.
* ``vresize`` : Double arrows pointing vertically.
Parameters
----------
name : str
Type of standard cursor to use (see above). Default is ``arrow``.
Notes
-----
* On Windows the ``crosshair`` option is negated with the background
color. It will not be visible when placed over 50% grey fields.
"""
if hasattr(self.backend, "setMouseType"):
self.backend.setMouseType(name)
def getActualFrameRate(self, nIdentical=10, nMaxFrames=100,
nWarmUpFrames=10, threshold=1):
"""Measures the actual frames-per-second (FPS) for the screen.
This is done by waiting (for a max of `nMaxFrames`) until
`nIdentical` frames in a row have identical frame times (std dev below
`threshold` ms).
Parameters
----------
nIdentical : int, optional
The number of consecutive frames that will be evaluated.
Higher --> greater precision. Lower --> faster.
nMaxFrames : int, optional
The maximum number of frames to wait for a matching set of
nIdentical.
nWarmUpFrames : int, optional
The number of frames to display before starting the test
(this is in place to allow the system to settle after opening
the `Window` for the first time.
threshold : int, optional
The threshold for the std deviation (in ms) before the set
are considered a match.
Returns
-------
float or None
Frame rate (FPS) in seconds. If there is no such sequence of
identical frames a warning is logged and `None` will be returned.
"""
if nIdentical > nMaxFrames:
raise ValueError('nIdentical must be equal to or '
'less than nMaxFrames')
recordFrmIntsOrig = self.recordFrameIntervals
# run warm-ups
self.recordFrameIntervals = False
for frameN in range(nWarmUpFrames):
self.flip()
# run test frames
self.recordFrameIntervals = True
for frameN in range(nMaxFrames):
self.flip()
if (len(self.frameIntervals) >= nIdentical and
(numpy.std(self.frameIntervals[-nIdentical:]) <
(threshold / 1000.0))):
rate = 1.0 / numpy.mean(self.frameIntervals[-nIdentical:])
if self.screen is None:
scrStr = ""
else:
scrStr = " (%i)" % self.screen
if self.autoLog:
msg = 'Screen%s actual frame rate measured at %.2f'
logging.debug(msg % (scrStr, rate))
self.recordFrameIntervals = recordFrmIntsOrig
self.frameIntervals = []
return rate
# if we got here we reached end of maxFrames with no consistent value
msg = ("Couldn't measure a consistent frame rate.\n"
" - Is your graphics card set to sync to vertical blank?\n"
" - Are you running other processes on your computer?\n")
logging.warning(msg)
return None
def getMsPerFrame(self, nFrames=60, showVisual=False, msg='', msDelay=0.):
"""Assesses the monitor refresh rate (average, median, SD) under
current conditions, over at least 60 frames.
Records time for each refresh (frame) for n frames (at least 60),
while displaying an optional visual. The visual is just eye-candy to
show that something is happening when assessing many frames. You can
also give it text to display instead of a visual,
e.g., ``msg='(testing refresh rate...)'``; setting msg implies
``showVisual == False``.
To simulate refresh rate under cpu load, you can specify a time to
wait within the loop prior to doing the :py:attr:`~Window.flip()`.
If 0 < msDelay < 100, wait for that long in ms.
Returns timing stats (in ms) of:
- average time per frame, for all frames
- standard deviation of all frames
- median, as the average of 12 frame times around the median
(~monitor refresh rate)
:Author:
- 2010 written by Jeremy Gray
"""
# lower bound of 60 samples--need enough to estimate the SD
nFrames = max(60, nFrames)
num2avg = 12 # how many to average from around the median
if len(msg):
showVisual = False
showText = True
myMsg = TextStim(self, text=msg, italic=True,
color=(.7, .6, .5), colorSpace='rgb',
height=0.1, autoLog=False)
else:
showText = False
if showVisual:
x, y = self.size
myStim = GratingStim(self, tex='sin', mask='gauss',
size=[.6 * y / float(x), .6], sf=3.0,
opacity=.2,
autoLog=False)
clockt = [] # clock times
# end of drawing time, in clock time units,
# for testing how long myStim.draw() takes
drawt = []
if msDelay > 0 and msDelay < 100:
doWait = True
delayTime = msDelay / 1000. # sec
else:
doWait = False
winUnitsSaved = self.units
# norm is required for the visual (or text) display, as coded below
self.units = 'norm'
# accumulate secs per frame (and time-to-draw) for a bunch of frames:
rush(True)
for i in range(5): # wake everybody up
self.flip()
for i in range(nFrames): # ... and go for real this time
clockt.append(core.getTime())
if showVisual:
myStim.setPhase(1.0 / nFrames, '+', log=False)
myStim.setSF(3. / nFrames, '+', log=False)
myStim.setOri(12. / nFrames, '+', log=False)
myStim.setOpacity(.9 / nFrames, '+', log=False)
myStim.draw()
elif showText:
myMsg.draw()
if doWait:
core.wait(delayTime)
drawt.append(core.getTime())
self.flip()
rush(False)
self.units = winUnitsSaved # restore
frameTimes = [(clockt[i] - clockt[i - 1])
for i in range(1, len(clockt))]
drawTimes = [(drawt[i] - clockt[i]) for
i in range(len(clockt))] # == drawing only
freeTimes = [frameTimes[i] - drawTimes[i] for
i in range(len(frameTimes))] # == unused time
# cast to float so that the resulting type == type(0.123)
# for median
frameTimes.sort()
# median-most slice
msPFmed = 1000. * float(numpy.average(
frameTimes[((nFrames - num2avg) // 2):((nFrames + num2avg) // 2)]))
msPFavg = 1000. * float(numpy.average(frameTimes))
msPFstd = 1000. * float(numpy.std(frameTimes))
msdrawAvg = 1000. * float(numpy.average(drawTimes))
msdrawSD = 1000. * float(numpy.std(drawTimes))
msfree = 1000. * float(numpy.average(freeTimes))
return msPFavg, msPFstd, msPFmed # msdrawAvg, msdrawSD, msfree
def _startOfFlip(self):
"""Custom hardware classes may want to prevent flipping from
occurring and can override this method as needed.
Return `True` to indicate hardware flip.
"""
return True
def _renderFBO(self):
"""Perform a warp operation.
(in this case a copy operation without any warping)
"""
GL.glBegin(GL.GL_QUADS)
GL.glTexCoord2f(0.0, 0.0)
GL.glVertex2f(-1.0, -1.0)
GL.glTexCoord2f(0.0, 1.0)
GL.glVertex2f(-1.0, 1.0)
GL.glTexCoord2f(1.0, 1.0)
GL.glVertex2f(1.0, 1.0)
GL.glTexCoord2f(1.0, 0.0)
GL.glVertex2f(1.0, -1.0)
GL.glEnd()
def _prepareFBOrender(self):
GL.glUseProgram(self._progFBOtoFrame)
def _finishFBOrender(self):
GL.glUseProgram(0)
def _afterFBOrender(self):
pass
def _endOfFlip(self, clearBuffer):
"""Override end of flip with custom color channel masking if required.
"""
if clearBuffer:
GL.glClear(GL.GL_COLOR_BUFFER_BIT)
def getMsPerFrame(myWin, nFrames=60, showVisual=False, msg='', msDelay=0.):
"""
Deprecated: please use the getMsPerFrame method in the
`psychopy.visual.Window` class.
Assesses the monitor refresh rate (average, median, SD) under current
conditions, over at least 60 frames.
Records time for each refresh (frame) for n frames (at least 60), while
displaying an optional visual. The visual is just eye-candy to show that
something is happening when assessing many frames. You can also give it
text to display instead of a visual, e.g.,
msg='(testing refresh rate...)'; setting msg implies showVisual == False.
To simulate refresh rate under
cpu load, you can specify a time to wait within the loop prior to
doing the win.flip(). If 0 < msDelay < 100, wait for that long in ms.
Returns timing stats (in ms) of:
- average time per frame, for all frames
- standard deviation of all frames
- median, as the average of 12 frame times around the median
(~monitor refresh rate)
:Author:
- 2010 written by Jeremy Gray
"""
return myWin.getMsPerFrame(nFrames=60, showVisual=showVisual, msg=msg,
msDelay=0.)
|
/**
* Defines standardized shims for the intrinsic `Object`.
* @see {external:Object}
* @module montage/core/shim/object
*/
/**
* @external Object
*/
/**
* Creates a new object that inherits prototypically directly from a given
* prototype, optionally defining some properties.
* @function external:Object.create
* @param {Object} prototype the prototype to inherit, or
* `null` for no prototype, which makes "__proto__" the only
* special property name.
* @param {Object} descriptor a property descriptor
* @returns a new object inheriting from the given prototype and having
* the given property descriptor.
*/
if (!Object.create) {
Object._creator = function _ObjectCreator() {
this.__proto__ = _ObjectCreator.prototype;
};
Object.create = function(o, properties) {
this._creator.prototype = o || Object.prototype;
//Still needs to add properties....
return new this._creator;
};
Object.getPrototypeOf = function(o) {
return o.__proto__;
};
}
// These are used in montage.js to ascertain whether we can annotate
// objects with montage metadata.
// TODO documentation
if (!Object.isSealed) {
Object.defineProperty(Object, "isSealed", {
value: function() {
return false;
},
writable: true,
configurable: true
});
}
// TODO documentation
if (!Object.seal) {
Object.defineProperty(Object, "seal", {
value: function(object) {
return object;
},
writable: true,
configurable: true
});
}
|
export const handler = async () => {
return {
statusCode: 200,
headers: {
'Content-Type': 'text/html; charset=utf-8',
},
body: `<p>Hello world!</p>`,
};
};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJpbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFFQSxNQUFNLENBQUMsTUFBTSxPQUFPLEdBQUcsS0FBSyxJQUFvQyxFQUFFO0lBQzlELE9BQU87UUFDSCxVQUFVLEVBQUUsR0FBRztRQUNmLE9BQU8sRUFBRTtZQUNMLGNBQWMsRUFBRSwwQkFBMEI7U0FDN0M7UUFDRCxJQUFJLEVBQUUscUJBQXFCO0tBQzlCLENBQUE7QUFDTCxDQUFDLENBQUEifQ==
|
import React from "react";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import styled, { css } from "styled-components";
import AsideSlider from "components/AsideSlider";
import useClearTimeout from "utils/hooks/useClearTimeout";
import {
showModal,
closeModal,
closeMenu,
showChangePasswordModal
} from "actions/display";
import { clearUserState, deleteUser } from "actions/user";
import { flashSuccess, flashError } from "actions/flashMessage";
const Aside = props => {
const { dispatch } = props;
let timeout;
useClearTimeout(timeout);
const handleChangePassword = evt => {
evt.preventDefault();
dispatch(showChangePasswordModal());
dispatch(closeMenu());
};
const openAccountSettings = evt => {
evt.preventDefault();
dispatch(closeMenu());
};
const openDeleteAccount = evt => {
evt.preventDefault();
// open up challengeModal
const modal = {
onSuccess: () => {
// send action to delete account
dispatch(deleteUser())
.then(isSuccess => {
if (isSuccess) {
dispatch(clearUserState());
timeout = setTimeout(() => {
dispatch(closeModal());
dispatch(flashSuccess("User successfully deleted!"));
}, 500);
}
})
.catch(err => {
// eslint-disable-next-line
console.log({ err });
dispatch(flashError());
});
},
onCancel: () => {
// optional callback
// modal will close itself eitherway
// eslint-disable-next-line
console.log("onCancel");
},
renderPrompt: () => (
<div style={{ textAlign: "center" }}>
<p>Are you sure you want to delete this account?</p>
<p>
This action is <span style={{ color: "red" }}>PERMANENT</span>.
</p>
</div>
)
};
dispatch(closeMenu());
dispatch(showModal(true, modal));
};
return (
<AsideSlider
{...props}
renderMenu={() => (
<>
<List>
<Item>
<a onClick={handleChangePassword} href="/change-password">
Change My Password
</a>
</Item>
<Item>
<a onClick={openAccountSettings} href="/account-settings">
Account Settings
</a>
</Item>
</List>
<h3 style={{ color: "red" }}>Dangerous!</h3>
<List>
<Item>
<a onClick={openDeleteAccount} href="#!">
Delete Account
</a>
</Item>
</List>
</>
)}
/>
);
};
Aside.propTypes = {
menuIsOpen: PropTypes.bool.isRequired,
onRequestClose: PropTypes.func.isRequired,
dispatch: PropTypes.func.isRequired
};
const mapStateToProps = ({ display }) => {
const { menuIsOpen } = display;
return {
menuIsOpen
};
};
export default connect(mapStateToProps)(Aside);
const List = styled.ul`
list-style: none;
`;
const Item = styled.li`
&:hover {
a {
color: ${({ theme }) => theme.colors.Compliment};
}
}
a {
color: ${({ theme }) => theme.colors.Primary};
display: inline-block;
width: 100%;
line-height: 1.6rem;
text-decoration: none;
transition: color 0.3s;
}
`;
|
import Dropdown from '../../../../Dropdown';
const DropdownTests = [
<Dropdown title="Select your option">{['Option 1', 'Option 2', 'Option 3']}</Dropdown>,
<Dropdown defaultSelected={1}>{['Option 1', 'Option 2', 'Option 3']}</Dropdown>,
<Dropdown disabled title="Select your option">{['Option 1', 'Option 2', 'Option 3']}</Dropdown>,
// Different Widths
<Dropdown title="Select your option" width="smallest">{['Option 1', 'Option 2', 'Option 3']}</Dropdown>,
<Dropdown title="Select your option" width="small">{['Option 1', 'Option 2', 'Option 3']}</Dropdown>,
<Dropdown title="Select your option" width="large">{['Option 1', 'Option 2', 'Option 3']}</Dropdown>,
<Dropdown title="Select your option" width="x-large">{['Option 1', 'Option 2', 'Option 3']}</Dropdown>,
<Dropdown title="Select your option" width="huge">{['Option 1', 'Option 2', 'Option 3']}</Dropdown>,
// Dropdown Open
<Dropdown open title="Select your option">{['Option 1', 'Option 2', 'Option 3']}</Dropdown>,
<div style={{'height': '700px'}}>
<Dropdown direction="above" open style={{'margin-top': '300px'}} title="Select your option">{['Option 1', 'Option 2', 'Option 3']}</Dropdown>
</div>,
<Dropdown defaultSelected={1} open>{['Option 1', 'Option 2', 'Option 3']}</Dropdown>,
<Dropdown disabled open title="Select your option">{['Option 1', 'Option 2', 'Option 3']}</Dropdown>,
// long options text
<Dropdown open title="Select your option" width="smallest">{['Option 1234567890123457', 'Option 2345678902345678', 'Option 345678903456789034567890']}</Dropdown>,
// Open with different widths
<Dropdown open title="Select your option" width="small">{['Option 1', 'Option 2', 'Option 3']}</Dropdown>,
<Dropdown open title="Select your option" width="large">{['Option 1', 'Option 2', 'Option 3']}</Dropdown>,
<Dropdown open title="Select your option" width="x-large">{['Option 1', 'Option 2', 'Option 3']}</Dropdown>,
<Dropdown open title="Select your option" width="huge">{['Option 1', 'Option 2', 'Option 3']}</Dropdown>,
// RTL
{
locale: 'ar-SA',
component:<Dropdown title="Select your option">{['Option 1', 'Option 2', 'Option 3']}</Dropdown>
},
{
locale: 'ar-SA',
component:<Dropdown defaultSelected={1}>{['Option 1', 'Option 2', 'Option 3']}</Dropdown>
},
{
locale: 'ar-SA',
component:<Dropdown disabled title="Select your option">{['Option 1', 'Option 2', 'Option 3']}</Dropdown>
},
// Dropdown Open
{
locale: 'ar-SA',
component:<Dropdown open title="Select your option">{['Option 1', 'Option 2', 'Option 3']}</Dropdown>
},
{
locale: 'ar-SA',
component:<div style={{'height': '700px'}}>
<Dropdown direction="above" open style={{'margin-top': '300px'}} title="Select your option">{['Option 1', 'Option 2', 'Option 3']}</Dropdown>
</div>
},
{
locale: 'ar-SA',
component:<Dropdown defaultSelected={1} open>{['Option 1', 'Option 2', 'Option 3']}</Dropdown>
},
{
locale: 'ar-SA',
component:<Dropdown disabled open title="Select your option">{['Option 1', 'Option 2', 'Option 3']}</Dropdown>
}
];
export default DropdownTests;
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OpnizServer = void 0;
var OpnizServer_1 = require("./OpnizServer");
Object.defineProperty(exports, "OpnizServer", { enumerable: true, get: function () { return OpnizServer_1.OpnizServer; } });
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[25],{"0SW5":function(e,t,a){"use strict";var n=a("q1tI"),l=a.n(n),o=a("bHgC"),r=a.n(o);t.a=function(){var e=Object(n.useState)(""),t=e[0],a=e[1],o=Object(n.useState)(""),i=o[0],s=o[1],m=Object(n.useState)(""),u=m[0],c=m[1],d=Object(n.useState)(""),p=d[0],h=d[1];return l.a.createElement("form",{id:"myform"},l.a.createElement("div",{className:r.a.formTitle},"Leave a Reply"),l.a.createElement("div",{className:r.a.formSubtitle}," Your email address will not be published. Required fields are marked*"),l.a.createElement("div",{className:r.a.formContainer2},l.a.createElement("input",{className:r.a.input,type:"text",id:"email",value:t,onChange:function(e){return a(e.target.value)},placeholder:"Email*",required:!0}),l.a.createElement("input",{className:r.a.input,type:"text",id:"website",value:i,onChange:function(e){return s(e.target.value)},placeholder:"Website URL *",required:!0}),l.a.createElement("input",{className:r.a.input,type:"text",id:"phone",value:u,onChange:function(e){return c(e.target.value)},placeholder:"Phone *",required:!0}),l.a.createElement("input",{className:r.a.message,type:"text",id:"message",value:p,onChange:function(e){return h(e.target.value)},placeholder:"Message",required:!0}),l.a.createElement("button",{className:r.a.SubmitButtom,type:"button",onClick:function(e){e.preventDefault();var a=new XMLHttpRequest,n="https://api.hsforms.com/submissions/v3/integration/submit/1779155/9392b242-42b4-4e04-bca8-3beb56cd8c8e",l={fields:[{name:"email",value:t},{name:"url",value:n},{name:"phoneNumber",value:u},{name:"message",value:p}],context:{pageUri:"https://bizamps-b2b.netlify.app/",pageName:"B2B Account-based Marketing Consultancy | BizAmps"},legalConsentOptions:{consent:{consentToProcess:!0,text:"I agree to allow Example Company to store and process my personal data.",communications:[{value:!0,subscriptionTypeId:999,text:"I agree to receive marketing communications from Example Company."}]}}};console.log(l);var o=JSON.stringify(l);a.open("POST",n),a.setRequestHeader("Content-Type","application/json"),a.onreadystatechange=function(){(4===a.readyState&&200===a.status||4===a.readyState&&403===a.status||4===a.readyState&&404===a.status||4===a.responseText&&400===a.status)&&alert(a.responseText)},a.send(o),setTimeout((function(){document.getElementById("myform").submit()}),3e3)}}," SUBMIT")))}},"8ypT":function(e,t,a){},Bl7J:function(e,t,a){"use strict";var n=a("q1tI"),l=a.n(n),o=a("Wbzz");a("8ypT");t.a=function(e){var t=e.children;Object(o.useStaticQuery)("3649515864");return l.a.createElement(l.a.Fragment,null,l.a.createElement("main",null,t))}},bHgC:function(e,t,a){e.exports={container1:"templet-module--container1--kd8VM",container2:"templet-module--container2--wEfR3",blogMobText:"templet-module--blogMobText--2cixG",desktopText:"templet-module--desktopText--1LYWH",blogContainer:"templet-module--blogContainer--1krV6",blogContainer2:"templet-module--blogContainer2--1XrRW",QuestionBlog2:"templet-module--QuestionBlog2--1Zuwa",BlogimageContainer:"templet-module--BlogimageContainer--2LBC6",image:"templet-module--image--2mayK",imageText:"templet-module--imageText--14oio",CSimageContainer:"templet-module--CSimageContainer--FvVpY",videoContainer:"templet-module--videoContainer--2s1B9",checkoutContainer:"templet-module--checkoutContainer--2Zefm",checkoutContent:"templet-module--checkoutContent--2wKOb",checkoutGroup:"templet-module--checkoutGroup--2bGim",checkoutImage:"templet-module--checkoutImage--354fc",checkoutTitle:"templet-module--checkoutTitle--UsIlY",checkoutText:"templet-module--checkoutText--3TtBu",personContainer:"templet-module--personContainer--3qARd",box:"templet-module--box--2brHI",imageContainer:"templet-module--imageContainer--2RE1f",table:"templet-module--table--2QkN-",personAlign:"templet-module--personAlign--IHiGg",boxalign:"templet-module--boxalign--1VNLS",personTitle:"templet-module--personTitle--2ML1e",personSubtitle:"templet-module--personSubtitle--25rPj",formcontainer:"templet-module--formcontainer--yPu06",formTitle:"templet-module--formTitle--2m7LT",formSubtitle:"templet-module--formSubtitle--3NYkT",formContainer2:"templet-module--formContainer2--U3rCy",input:"templet-module--input--3jotW",message:"templet-module--message--2JcOn",SubmitButtom:"templet-module--SubmitButtom--3hJAJ",location1:"templet-module--location1--WGQlq",headingContainer:"templet-module--headingContainer--1nJer",Mobheading:"templet-module--Mobheading--1_F7C",heading:"templet-module--heading--3Pxdb"}},glye:function(e,t,a){e.exports={location:"location-module--location--3WxTy",end:"location-module--end--2IZAd"}},jTV7:function(e,t,a){"use strict";var n=a("q1tI"),l=a.n(n),o=a("bHgC"),r=a.n(o),i=a("9eSz"),s=a.n(i);t.a=function(e){return l.a.createElement(l.a.Fragment,null,l.a.createElement("div",{className:r.a.box},l.a.createElement("div",{className:r.a.imageContainer},l.a.createElement(s.a,{className:r.a.personAlign,fluid:e.person})),l.a.createElement("div",{className:r.a.boxalign},l.a.createElement("div",{className:r.a.personTitle},"Akshat Kharbanda"),l.a.createElement("div",{className:r.a.personSubtitle},"Struggled with B2B leadgen for 3.5 years. Took 1.5 years to perfect a system that throws out hot leads at the end."))))}},qLGI:function(e,t,a){"use strict";a.r(t),a.d(t,"BlogPageQuery",(function(){return y}));var n=a("q1tI"),l=a.n(n),o=a("bHgC"),r=a.n(o),i=a("1eu9"),s=a.n(i),m=a("Bl7J"),u=a("LAYS"),c=a("9eSz"),d=a.n(c),p=function(e){return l.a.createElement(l.a.Fragment,null,l.a.createElement("div",{className:r.a.blogContainer2},l.a.createElement("p",null,"God, I don’t know how many times during a sales trainer’s presentation I have heard ‘Add Value’."),l.a.createElement("p",null,"Which effectively is: Send them an article, case study, etc. (like your prospect doesn’t know how to use google) According to my experience,"),l.a.createElement("p",null,"After that, anytime anyone mentions ‘add value’ too many times without the specifics, I run away, knowing that this person doesn’t have anything to add of value."),l.a.createElement("p",null,"According to my experience,'Value' is Δ delta"),l.a.createElement("div",{className:r.a.BlogimageContainer},l.a.createElement(d.a,{className:r.a.image,fluid:e.illus1}),l.a.createElement("span",{className:r.a.imageText}," After situation – Before situation = Value ")),l.a.createElement("p",null,"For example:"),l.a.createElement("p",null,"If a girl walks up to me and says ‘I like you’, value-added to my emotional situation will be:"),l.a.createElement("p",null,"Feeling Superb (after) – Feeling Normal (before) = Superb value add."),l.a.createElement("p",null," ",l.a.createElement("b",null,"Adding value while following up")),l.a.createElement("p",null,"You need to follow up and you need a good reason to email that prospect again, Here’s a tip"),l.a.createElement("p",null,"Don’t just send an article. Share an exclusive insight! or share an experience of yours, that your prospect can’t find in an article anywhere. Most articles on the internet are non-actionable and pure speculation."),l.a.createElement("p",null,"Put your credibility on the line, behind the random articles links that you are sending, The credibility that your experience adds is pure value."),l.a.createElement("p",null,"Sales folks, more here:"),l.a.createElement("p",null,l.a.createElement("b",null," Value-adding follow up template:")),l.a.createElement("p",{style:{opacity:.8}},'"Hi [prospect] Last time we discussed you were working on A. I had few articles in my bookmarks that I think you should read. This article is wrong – Don’t do A instead do B, I have seen companies doing B are very satisfied.',l.a.createElement("br",null),' Because when you ‘A’, we have ‘X’ though process but we forget about ‘Y’ factor….. Blah blah… If you do A, you might lose 6 months to trial and error, Plus it is not sustainable."'),l.a.createElement("p",{style:{fontSize:"2rem",lineHeight:"2.3rem",fontWeight:"600",margin:"1.5rem 0.5rem",fontFamily:"Roboto"}},"Perceived Value & Why discovery meetings are important:"),l.a.createElement("p",null,"Let’s be honest, there is no guarantee that the last email we sent will get a +ve reply because we don’t know the information we added was something new or relevant to that prospect at that time. This brings us to the concept of perceived value."),l.a.createElement("p",null,"Transparency has a lot of value, only if the client has been burned before by a vendor who was not transparent because he has now seen the horror show of non-transparent vendors"),l.a.createElement("p",null,"This is why discovery calls are important, even if you sell a product or a productized service. It tells you what this prospect might find of value."),l.a.createElement("p",null,"Some clients don’t give a rat’s ass about your transparency pitch and they would just say ” I just want more leads and sales now!”"),l.a.createElement("p",{style:{fontSize:"2rem",lineHeight:"2.3rem",fontWeight:"600",margin:"1.5rem 0.5rem",fontFamily:"Roboto"}},"Relative Perceived Value & Content Marketing"),l.a.createElement("p",null,"Now, let’s bring in your competition and take this one step further."),l.a.createElement("p",null,"There are 702 pieces of videos/blogs I want to go through in my OneTab chrome extension but I prioritize some authors over others, always."),l.a.createElement("p",null,"Here’s Why: ",l.a.createElement("br",null),"I know some authors would have done the hardest work of not only ‘curating’ the facts but would have put their sweat and tears to find the secret information, the real benchmarks of real companies by individually contacting these target companies and have compiled the report as a scientific research paper, that people might refer for years to come. Real value shines through!"),l.a.createElement("p",null,"And it’s worth it because life’s too short, reputation too valuable and winners take all."),l.a.createElement("div",{className:r.a.BlogimageContainer},l.a.createElement(d.a,{className:r.a.image,fluid:e.illus2}))))},h=a("jTV7"),g=a("0SW5"),f=a("sL2v"),b=a("B1WW"),y=(t.default=function(e){return l.a.createElement(l.a.Fragment,null,l.a.createElement(m.a,null,l.a.createElement(s.a,{fluid:e.data.bg1.childImageSharp.fluid,className:r.a.container1},l.a.createElement(u.a,{logo:e.data.bizampsLogo.childImageSharp.fluid,color:"blue"})),l.a.createElement(s.a,{fluid:e.data.bg2.childImageSharp.fluid,className:r.a.container2},l.a.createElement(u.a,{logo:e.data.bizampsLogo.childImageSharp.fluid})),l.a.createElement("div",{className:r.a.blogContainer},l.a.createElement(p,{illus1:e.data.pic1.childImageSharp.fluid,illus2:e.data.pic2.childImageSharp.fluid})),l.a.createElement("div",{className:r.a.personContainer},l.a.createElement(h.a,{person:e.data.person.childImageSharp.fluid})),l.a.createElement("div",{className:r.a.formcontainer},l.a.createElement(g.a,null)),l.a.createElement("div",{className:r.a.location1},l.a.createElement(f.a,{first:"Home",second:"Expertise",third:"[Blog] Value In Sales? "})),l.a.createElement(b.a,null)))},"759605086")},sL2v:function(e,t,a){"use strict";var n=a("q1tI"),l=a.n(n),o=a("glye"),r=a.n(o);t.a=function(e){return l.a.createElement("div",{className:r.a.location},e.first," ",">>"," ",e.second," ",">>"," ",l.a.createElement("span",{className:r.a.end},e.third))}}}]);
//# sourceMappingURL=component---src-pages-templet-js-e3d138d0dd74a87d9ff9.js.map
|
/*
* HomePage Messages
*
* This contains all the text for the HomePage container.
*/
import { defineMessages } from 'react-intl';
export const scope = 'app.component.Header';
export default defineMessages({
header: {
id: `${scope}.header`,
defaultMessage: 'Demo-react',
},
home: {
id: `${scope}.home`,
defaultMessage: 'Home',
},
contact: {
id: `${scope}.contact`,
defaultMessage: 'Contact',
},
});
|
import os
import random
import string
import sys
import time
from collections import defaultdict
from contextlib import contextmanager
import pendulum
import pytest
from dagster import Any, Field, daily_partitioned_config, graph, pipeline, repository, solid
from dagster.core.definitions import Partition, PartitionSetDefinition
from dagster.core.definitions.reconstructable import ReconstructableRepository
from dagster.core.execution.backfill import BulkActionStatus, PartitionBackfill
from dagster.core.host_representation import (
ExternalRepositoryOrigin,
InProcessRepositoryLocationOrigin,
ManagedGrpcPythonEnvRepositoryLocationOrigin,
)
from dagster.core.host_representation.grpc_server_registry import ProcessGrpcServerRegistry
from dagster.core.storage.pipeline_run import PipelineRunStatus, PipelineRunsFilter
from dagster.core.storage.tags import BACKFILL_ID_TAG, PARTITION_NAME_TAG, PARTITION_SET_TAG
from dagster.core.test_utils import instance_for_test
from dagster.core.types.loadable_target_origin import LoadableTargetOrigin
from dagster.core.workspace.dynamic_workspace import DynamicWorkspace
from dagster.daemon import get_default_daemon_logger
from dagster.daemon.backfill import execute_backfill_iteration
from dagster.seven import IS_WINDOWS, get_system_temp_directory
from dagster.utils import touch_file
from dagster.utils.error import SerializableErrorInfo
def _failure_flag_file():
return os.path.join(get_system_temp_directory(), "conditionally_fail")
def _step_events(instance, run):
events_by_step = defaultdict(set)
logs = instance.all_logs(run.run_id)
for record in logs:
if not record.is_dagster_event or not record.step_key:
continue
events_by_step[record.step_key] = record.dagster_event.event_type_value
return events_by_step
@solid
def always_succeed(_):
return 1
@graph
def comp_always_succeed():
always_succeed()
@daily_partitioned_config(start_date="2021-05-05")
def my_config(_start, _end):
return {}
always_succeed_job = comp_always_succeed.to_job(config=my_config)
@solid
def conditionally_fail(_, _input):
if os.path.isfile(_failure_flag_file()):
raise Exception("blah")
return 1
@solid
def after_failure(_, _input):
return 1
@pipeline
def the_pipeline():
always_succeed()
@pipeline
def conditional_failure_pipeline():
after_failure(conditionally_fail(always_succeed()))
@pipeline
def partial_pipeline():
always_succeed.alias("step_one")()
always_succeed.alias("step_two")()
always_succeed.alias("step_three")()
@solid(config_schema=Field(Any))
def config_solid(_):
return 1
@pipeline
def config_pipeline():
config_solid()
simple_partition_set = PartitionSetDefinition(
name="simple_partition_set",
pipeline_name="the_pipeline",
partition_fn=lambda: [Partition("one"), Partition("two"), Partition("three")],
run_config_fn_for_partition=lambda _partition: {"intermediate_storage": {"filesystem": {}}},
)
conditionally_fail_partition_set = PartitionSetDefinition(
name="conditionally_fail_partition_set",
pipeline_name="conditional_failure_pipeline",
partition_fn=lambda: [Partition("one"), Partition("two"), Partition("three")],
run_config_fn_for_partition=lambda _partition: {"intermediate_storage": {"filesystem": {}}},
)
partial_partition_set = PartitionSetDefinition(
name="partial_partition_set",
pipeline_name="partial_pipeline",
partition_fn=lambda: [Partition("one"), Partition("two"), Partition("three")],
run_config_fn_for_partition=lambda _partition: {"intermediate_storage": {"filesystem": {}}},
)
def _large_partition_config(_):
REQUEST_CONFIG_COUNT = 50000
def _random_string(length):
return "".join(random.choice(string.ascii_lowercase) for x in range(length))
return {
"solids": {
"config_solid": {
"config": {
"foo": {
_random_string(10): _random_string(20) for i in range(REQUEST_CONFIG_COUNT)
}
}
}
}
}
large_partition_set = PartitionSetDefinition(
name="large_partition_set",
pipeline_name="config_pipeline",
partition_fn=lambda: [Partition("one"), Partition("two"), Partition("three")],
run_config_fn_for_partition=_large_partition_config,
)
def _unloadable_partition_set_origin():
working_directory = os.path.dirname(__file__)
recon_repo = ReconstructableRepository.for_file(__file__, "doesnt_exist", working_directory)
return ExternalRepositoryOrigin(
InProcessRepositoryLocationOrigin(recon_repo), "fake_repository"
).get_partition_set_origin("doesnt_exist")
@repository
def the_repo():
return [
the_pipeline,
conditional_failure_pipeline,
partial_pipeline,
config_pipeline,
simple_partition_set,
conditionally_fail_partition_set,
partial_partition_set,
large_partition_set,
always_succeed_job,
]
@contextmanager
def default_repo():
loadable_target_origin = LoadableTargetOrigin(
executable_path=sys.executable,
python_file=__file__,
working_directory=os.getcwd(),
)
with ManagedGrpcPythonEnvRepositoryLocationOrigin(
loadable_target_origin=loadable_target_origin,
location_name="test_location",
).create_test_location() as location:
yield location.get_repository("the_repo")
def repos():
return [default_repo]
@contextmanager
def instance_for_context(external_repo_context, overrides=None):
with instance_for_test(overrides) as instance:
with ProcessGrpcServerRegistry() as grpc_server_registry:
with DynamicWorkspace(grpc_server_registry) as workspace:
with external_repo_context() as external_repo:
yield (instance, workspace, external_repo)
def step_did_not_run(instance, run, step_name):
step_events = _step_events(instance, run)[step_name]
return len(step_events) == 0
def step_succeeded(instance, run, step_name):
step_events = _step_events(instance, run)[step_name]
return "STEP_SUCCESS" in step_events
def step_failed(instance, run, step_name):
step_events = _step_events(instance, run)[step_name]
return "STEP_FAILURE" in step_events
def wait_for_all_runs_to_start(instance, timeout=10):
start_time = time.time()
while True:
if time.time() - start_time > timeout:
raise Exception("Timed out waiting for runs to start")
time.sleep(0.5)
pending_states = [
PipelineRunStatus.NOT_STARTED,
PipelineRunStatus.STARTING,
PipelineRunStatus.STARTED,
]
pending_runs = [run for run in instance.get_runs() if run.status in pending_states]
if len(pending_runs) == 0:
break
@pytest.mark.parametrize("external_repo_context", repos())
def test_simple_backfill(external_repo_context):
with instance_for_context(external_repo_context) as (
instance,
workspace,
external_repo,
):
external_partition_set = external_repo.get_external_partition_set("simple_partition_set")
instance.add_backfill(
PartitionBackfill(
backfill_id="simple",
partition_set_origin=external_partition_set.get_external_origin(),
status=BulkActionStatus.REQUESTED,
partition_names=["one", "two", "three"],
from_failure=False,
reexecution_steps=None,
tags=None,
backfill_timestamp=pendulum.now().timestamp(),
)
)
assert instance.get_runs_count() == 0
list(
execute_backfill_iteration(
instance, workspace, get_default_daemon_logger("BackfillDaemon")
)
)
assert instance.get_runs_count() == 3
runs = instance.get_runs()
three, two, one = runs
assert one.tags[BACKFILL_ID_TAG] == "simple"
assert one.tags[PARTITION_NAME_TAG] == "one"
assert two.tags[BACKFILL_ID_TAG] == "simple"
assert two.tags[PARTITION_NAME_TAG] == "two"
assert three.tags[BACKFILL_ID_TAG] == "simple"
assert three.tags[PARTITION_NAME_TAG] == "three"
@pytest.mark.parametrize("external_repo_context", repos())
def test_failure_backfill(external_repo_context):
output_file = _failure_flag_file()
with instance_for_context(external_repo_context) as (
instance,
workspace,
external_repo,
):
external_partition_set = external_repo.get_external_partition_set(
"conditionally_fail_partition_set"
)
instance.add_backfill(
PartitionBackfill(
backfill_id="shouldfail",
partition_set_origin=external_partition_set.get_external_origin(),
status=BulkActionStatus.REQUESTED,
partition_names=["one", "two", "three"],
from_failure=False,
reexecution_steps=None,
tags=None,
backfill_timestamp=pendulum.now().timestamp(),
)
)
assert instance.get_runs_count() == 0
try:
touch_file(output_file)
list(
execute_backfill_iteration(
instance, workspace, get_default_daemon_logger("BackfillDaemon")
)
)
wait_for_all_runs_to_start(instance)
finally:
os.remove(output_file)
assert instance.get_runs_count() == 3
runs = instance.get_runs()
three, two, one = runs
assert one.tags[BACKFILL_ID_TAG] == "shouldfail"
assert one.tags[PARTITION_NAME_TAG] == "one"
assert one.status == PipelineRunStatus.FAILURE
assert step_succeeded(instance, one, "always_succeed")
assert step_failed(instance, one, "conditionally_fail")
assert step_did_not_run(instance, one, "after_failure")
assert two.tags[BACKFILL_ID_TAG] == "shouldfail"
assert two.tags[PARTITION_NAME_TAG] == "two"
assert two.status == PipelineRunStatus.FAILURE
assert step_succeeded(instance, two, "always_succeed")
assert step_failed(instance, two, "conditionally_fail")
assert step_did_not_run(instance, two, "after_failure")
assert three.tags[BACKFILL_ID_TAG] == "shouldfail"
assert three.tags[PARTITION_NAME_TAG] == "three"
assert three.status == PipelineRunStatus.FAILURE
assert step_succeeded(instance, three, "always_succeed")
assert step_failed(instance, three, "conditionally_fail")
assert step_did_not_run(instance, three, "after_failure")
instance.add_backfill(
PartitionBackfill(
backfill_id="fromfailure",
partition_set_origin=external_partition_set.get_external_origin(),
status=BulkActionStatus.REQUESTED,
partition_names=["one", "two", "three"],
from_failure=True,
reexecution_steps=None,
tags=None,
backfill_timestamp=pendulum.now().timestamp(),
)
)
assert not os.path.isfile(_failure_flag_file())
list(
execute_backfill_iteration(
instance, workspace, get_default_daemon_logger("BackfillDaemon")
)
)
wait_for_all_runs_to_start(instance)
assert instance.get_runs_count() == 6
from_failure_filter = PipelineRunsFilter(tags={BACKFILL_ID_TAG: "fromfailure"})
assert instance.get_runs_count(filters=from_failure_filter) == 3
runs = instance.get_runs(filters=from_failure_filter)
three, two, one = runs
assert one.tags[BACKFILL_ID_TAG] == "fromfailure"
assert one.tags[PARTITION_NAME_TAG] == "one"
assert one.status == PipelineRunStatus.SUCCESS
assert step_did_not_run(instance, one, "always_succeed")
assert step_succeeded(instance, one, "conditionally_fail")
assert step_succeeded(instance, one, "after_failure")
assert two.tags[BACKFILL_ID_TAG] == "fromfailure"
assert two.tags[PARTITION_NAME_TAG] == "two"
assert two.status == PipelineRunStatus.SUCCESS
assert step_did_not_run(instance, one, "always_succeed")
assert step_succeeded(instance, one, "conditionally_fail")
assert step_succeeded(instance, one, "after_failure")
assert three.tags[BACKFILL_ID_TAG] == "fromfailure"
assert three.tags[PARTITION_NAME_TAG] == "three"
assert three.status == PipelineRunStatus.SUCCESS
assert step_did_not_run(instance, one, "always_succeed")
assert step_succeeded(instance, one, "conditionally_fail")
assert step_succeeded(instance, one, "after_failure")
@pytest.mark.skipif(IS_WINDOWS, reason="flaky in windows")
@pytest.mark.parametrize("external_repo_context", repos())
def test_partial_backfill(external_repo_context):
with instance_for_context(external_repo_context) as (
instance,
workspace,
external_repo,
):
external_partition_set = external_repo.get_external_partition_set("partial_partition_set")
# create full runs, where every step is executed
instance.add_backfill(
PartitionBackfill(
backfill_id="full",
partition_set_origin=external_partition_set.get_external_origin(),
status=BulkActionStatus.REQUESTED,
partition_names=["one", "two", "three"],
from_failure=False,
reexecution_steps=None,
tags=None,
backfill_timestamp=pendulum.now().timestamp(),
)
)
assert instance.get_runs_count() == 0
list(
execute_backfill_iteration(
instance, workspace, get_default_daemon_logger("BackfillDaemon")
)
)
wait_for_all_runs_to_start(instance)
assert instance.get_runs_count() == 3
runs = instance.get_runs()
three, two, one = runs
assert one.tags[BACKFILL_ID_TAG] == "full"
assert one.tags[PARTITION_NAME_TAG] == "one"
assert one.status == PipelineRunStatus.SUCCESS
assert step_succeeded(instance, one, "step_one")
assert step_succeeded(instance, one, "step_two")
assert step_succeeded(instance, one, "step_three")
assert two.tags[BACKFILL_ID_TAG] == "full"
assert two.tags[PARTITION_NAME_TAG] == "two"
assert two.status == PipelineRunStatus.SUCCESS
assert step_succeeded(instance, two, "step_one")
assert step_succeeded(instance, two, "step_two")
assert step_succeeded(instance, two, "step_three")
assert three.tags[BACKFILL_ID_TAG] == "full"
assert three.tags[PARTITION_NAME_TAG] == "three"
assert three.status == PipelineRunStatus.SUCCESS
assert step_succeeded(instance, three, "step_one")
assert step_succeeded(instance, three, "step_two")
assert step_succeeded(instance, three, "step_three")
# delete one of the runs, the partial reexecution should still succeed because the steps
# can be executed independently, require no input/output config
instance.delete_run(one.run_id)
assert instance.get_runs_count() == 2
# create partial runs
instance.add_backfill(
PartitionBackfill(
backfill_id="partial",
partition_set_origin=external_partition_set.get_external_origin(),
status=BulkActionStatus.REQUESTED,
partition_names=["one", "two", "three"],
from_failure=False,
reexecution_steps=["step_one"],
tags=None,
backfill_timestamp=pendulum.now().timestamp(),
)
)
list(
execute_backfill_iteration(
instance, workspace, get_default_daemon_logger("BackfillDaemon")
)
)
wait_for_all_runs_to_start(instance)
assert instance.get_runs_count() == 5
partial_filter = PipelineRunsFilter(tags={BACKFILL_ID_TAG: "partial"})
assert instance.get_runs_count(filters=partial_filter) == 3
runs = instance.get_runs(filters=partial_filter)
three, two, one = runs
assert one.status == PipelineRunStatus.SUCCESS
assert step_succeeded(instance, one, "step_one")
assert step_did_not_run(instance, one, "step_two")
assert step_did_not_run(instance, one, "step_three")
assert two.status == PipelineRunStatus.SUCCESS
assert step_succeeded(instance, two, "step_one")
assert step_did_not_run(instance, two, "step_two")
assert step_did_not_run(instance, two, "step_three")
assert three.status == PipelineRunStatus.SUCCESS
assert step_succeeded(instance, three, "step_one")
assert step_did_not_run(instance, three, "step_two")
assert step_did_not_run(instance, three, "step_three")
@pytest.mark.parametrize("external_repo_context", repos())
def test_large_backfill(external_repo_context):
with instance_for_context(external_repo_context) as (
instance,
workspace,
external_repo,
):
external_partition_set = external_repo.get_external_partition_set("large_partition_set")
instance.add_backfill(
PartitionBackfill(
backfill_id="simple",
partition_set_origin=external_partition_set.get_external_origin(),
status=BulkActionStatus.REQUESTED,
partition_names=["one", "two", "three"],
from_failure=False,
reexecution_steps=None,
tags=None,
backfill_timestamp=pendulum.now().timestamp(),
)
)
assert instance.get_runs_count() == 0
list(
execute_backfill_iteration(
instance, workspace, get_default_daemon_logger("BackfillDaemon")
)
)
assert instance.get_runs_count() == 3
@pytest.mark.parametrize("external_repo_context", repos())
def test_unloadable_backfill(external_repo_context):
with instance_for_context(external_repo_context) as (
instance,
workspace,
_external_repo,
):
unloadable_origin = _unloadable_partition_set_origin()
instance.add_backfill(
PartitionBackfill(
backfill_id="simple",
partition_set_origin=unloadable_origin,
status=BulkActionStatus.REQUESTED,
partition_names=["one", "two", "three"],
from_failure=False,
reexecution_steps=None,
tags=None,
backfill_timestamp=pendulum.now().timestamp(),
)
)
assert instance.get_runs_count() == 0
list(
execute_backfill_iteration(
instance, workspace, get_default_daemon_logger("BackfillDaemon")
)
)
assert instance.get_runs_count() == 0
backfill = instance.get_backfill("simple")
assert backfill.status == BulkActionStatus.FAILED
assert isinstance(backfill.error, SerializableErrorInfo)
@pytest.mark.parametrize("external_repo_context", repos())
def test_backfill_from_partitioned_job(external_repo_context):
partition_name_list = [
partition.name for partition in my_config.partitions_def.get_partitions()
]
with instance_for_context(external_repo_context) as (
instance,
workspace,
external_repo,
):
external_partition_set = external_repo.get_external_partition_set(
"comp_always_succeed_default_partition_set"
)
instance.add_backfill(
PartitionBackfill(
backfill_id="partition_schedule_from_job",
partition_set_origin=external_partition_set.get_external_origin(),
status=BulkActionStatus.REQUESTED,
partition_names=partition_name_list[:3],
from_failure=False,
reexecution_steps=None,
tags=None,
backfill_timestamp=pendulum.now().timestamp(),
)
)
assert instance.get_runs_count() == 0
list(
execute_backfill_iteration(
instance, workspace, get_default_daemon_logger("BackfillDaemon")
)
)
assert instance.get_runs_count() == 3
runs = reversed(instance.get_runs())
for idx, run in enumerate(runs):
assert run.tags[BACKFILL_ID_TAG] == "partition_schedule_from_job"
assert run.tags[PARTITION_NAME_TAG] == partition_name_list[idx]
assert run.tags[PARTITION_SET_TAG] == "comp_always_succeed_default_partition_set"
|
(this.webpackJsonpenterprise=this.webpackJsonpenterprise||[]).push([[15],{108:function(t,r,n){"use strict";n.r(r),n.d(r,"ion_card",(function(){return d})),n.d(r,"ion_card_content",(function(){return l})),n.d(r,"ion_card_header",(function(){return p})),n.d(r,"ion_card_subtitle",(function(){return g})),n.d(r,"ion_card_title",(function(){return b}));var i=n(15),o=n(5),e=n(6),a=n(16),s=n(13),c=n(175),d=function(){function t(r){Object(o.a)(this,t),Object(a.l)(this,r),this.button=!1,this.type="button",this.disabled=!1,this.routerDirection="forward"}return Object(e.a)(t,[{key:"isClickable",value:function(){return void 0!==this.href||this.button}},{key:"renderCard",value:function(t){var r=this.isClickable();if(!r)return[Object(a.j)("slot",null)];var n=this.href,i=this.routerDirection,o=r?void 0===n?"button":"a":"div",e="button"===o?{type:this.type}:{download:this.download,href:this.href,rel:this.rel,target:this.target};return Object(a.j)(o,Object.assign({},e,{class:"card-native",disabled:this.disabled,onClick:function(t){return Object(c.d)(n,t,i)}}),Object(a.j)("slot",null),r&&"md"===t&&Object(a.j)("ion-ripple-effect",null))}},{key:"render",value:function(){var t=Object(s.b)(this);return Object(a.j)(a.b,{class:Object.assign(Object.assign(Object(i.a)({},t,!0),Object(c.a)(this.color)),{"card-disabled":this.disabled,"ion-activatable":this.isClickable()})},this.renderCard(t))}}]),t}();d.style={ios:":host{--ion-safe-area-left:0px;--ion-safe-area-right:0px;-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;display:block;position:relative;background:var(--background);color:var(--color);font-family:var(--ion-font-family, inherit);overflow:hidden}:host(.ion-color){background:var(--ion-color-base);color:var(--ion-color-contrast)}:host(.card-disabled){cursor:default;opacity:0.3;pointer-events:none}.card-native{font-family:inherit;font-size:inherit;font-style:inherit;font-weight:inherit;letter-spacing:inherit;text-decoration:inherit;text-indent:inherit;text-overflow:inherit;text-transform:inherit;text-align:inherit;white-space:inherit;color:inherit;padding-left:0;padding-right:0;padding-top:0;padding-bottom:0;margin-left:0;margin-right:0;margin-top:0;margin-bottom:0;display:block;width:100%;min-height:var(--min-height);-webkit-transition:var(--transition);transition:var(--transition);border-width:var(--border-width);border-style:var(--border-style);border-color:var(--border-color);outline:none;background:inherit}.card-native::-moz-focus-inner{border:0}button,a{cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;-webkit-user-drag:none}ion-ripple-effect{color:var(--ripple-color)}:host{--background:var(--ion-item-background, var(--ion-background-color, #fff));--color:var(--ion-color-step-600, #666666);margin-left:16px;margin-right:16px;margin-top:24px;margin-bottom:24px;border-radius:8px;-webkit-transform:translateZ(0);transform:translateZ(0);-webkit-transition:-webkit-transform 500ms cubic-bezier(0.12, 0.72, 0.29, 1);transition:-webkit-transform 500ms cubic-bezier(0.12, 0.72, 0.29, 1);transition:transform 500ms cubic-bezier(0.12, 0.72, 0.29, 1);transition:transform 500ms cubic-bezier(0.12, 0.72, 0.29, 1), -webkit-transform 500ms cubic-bezier(0.12, 0.72, 0.29, 1);font-size:14px;-webkit-box-shadow:0 4px 16px rgba(0, 0, 0, 0.12);box-shadow:0 4px 16px rgba(0, 0, 0, 0.12)}@supports ((-webkit-margin-start: 0) or (margin-inline-start: 0)) or (-webkit-margin-start: 0){:host{margin-left:unset;margin-right:unset;-webkit-margin-start:16px;margin-inline-start:16px;-webkit-margin-end:16px;margin-inline-end:16px}}:host(.ion-activated){-webkit-transform:scale3d(0.97, 0.97, 1);transform:scale3d(0.97, 0.97, 1)}",md:":host{--ion-safe-area-left:0px;--ion-safe-area-right:0px;-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;display:block;position:relative;background:var(--background);color:var(--color);font-family:var(--ion-font-family, inherit);overflow:hidden}:host(.ion-color){background:var(--ion-color-base);color:var(--ion-color-contrast)}:host(.card-disabled){cursor:default;opacity:0.3;pointer-events:none}.card-native{font-family:inherit;font-size:inherit;font-style:inherit;font-weight:inherit;letter-spacing:inherit;text-decoration:inherit;text-indent:inherit;text-overflow:inherit;text-transform:inherit;text-align:inherit;white-space:inherit;color:inherit;padding-left:0;padding-right:0;padding-top:0;padding-bottom:0;margin-left:0;margin-right:0;margin-top:0;margin-bottom:0;display:block;width:100%;min-height:var(--min-height);-webkit-transition:var(--transition);transition:var(--transition);border-width:var(--border-width);border-style:var(--border-style);border-color:var(--border-color);outline:none;background:inherit}.card-native::-moz-focus-inner{border:0}button,a{cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;-webkit-user-drag:none}ion-ripple-effect{color:var(--ripple-color)}:host{--background:var(--ion-item-background, var(--ion-background-color, #fff));--color:var(--ion-color-step-550, #737373);margin-left:10px;margin-right:10px;margin-top:10px;margin-bottom:10px;border-radius:4px;font-size:14px;-webkit-box-shadow:0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12);box-shadow:0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12)}@supports ((-webkit-margin-start: 0) or (margin-inline-start: 0)) or (-webkit-margin-start: 0){:host{margin-left:unset;margin-right:unset;-webkit-margin-start:10px;margin-inline-start:10px;-webkit-margin-end:10px;margin-inline-end:10px}}"};var l=function(){function t(r){Object(o.a)(this,t),Object(a.l)(this,r)}return Object(e.a)(t,[{key:"render",value:function(){var t,r=Object(s.b)(this);return Object(a.j)(a.b,{class:(t={},Object(i.a)(t,r,!0),Object(i.a)(t,"card-content-".concat(r),!0),t)})}}]),t}();l.style={ios:"ion-card-content{display:block;position:relative}.card-content-ios{padding-left:20px;padding-right:20px;padding-top:20px;padding-bottom:20px;font-size:16px;line-height:1.4}@supports ((-webkit-margin-start: 0) or (margin-inline-start: 0)) or (-webkit-margin-start: 0){.card-content-ios{padding-left:unset;padding-right:unset;-webkit-padding-start:20px;padding-inline-start:20px;-webkit-padding-end:20px;padding-inline-end:20px}}.card-content-ios h1{margin-left:0;margin-right:0;margin-top:0;margin-bottom:2px;font-size:24px;font-weight:normal}.card-content-ios h2{margin-left:0;margin-right:0;margin-top:2px;margin-bottom:2px;font-size:16px;font-weight:normal}.card-content-ios h3,.card-content-ios h4,.card-content-ios h5,.card-content-ios h6{margin-left:0;margin-right:0;margin-top:2px;margin-bottom:2px;font-size:14px;font-weight:normal}.card-content-ios p{margin-left:0;margin-right:0;margin-top:0;margin-bottom:2px;font-size:14px}ion-card-header+.card-content-ios{padding-top:0}",md:"ion-card-content{display:block;position:relative}.card-content-md{padding-left:16px;padding-right:16px;padding-top:13px;padding-bottom:13px;font-size:14px;line-height:1.5}@supports ((-webkit-margin-start: 0) or (margin-inline-start: 0)) or (-webkit-margin-start: 0){.card-content-md{padding-left:unset;padding-right:unset;-webkit-padding-start:16px;padding-inline-start:16px;-webkit-padding-end:16px;padding-inline-end:16px}}.card-content-md h1{margin-left:0;margin-right:0;margin-top:0;margin-bottom:2px;font-size:24px;font-weight:normal}.card-content-md h2{margin-left:0;margin-right:0;margin-top:2px;margin-bottom:2px;font-size:16px;font-weight:normal}.card-content-md h3,.card-content-md h4,.card-content-md h5,.card-content-md h6{margin-left:0;margin-right:0;margin-top:2px;margin-bottom:2px;font-size:14px;font-weight:normal}.card-content-md p{margin-left:0;margin-right:0;margin-top:0;margin-bottom:2px;font-size:14px;font-weight:normal;line-height:1.5}ion-card-header+.card-content-md{padding-top:0}"};var p=function(){function t(r){Object(o.a)(this,t),Object(a.l)(this,r),this.translucent=!1}return Object(e.a)(t,[{key:"render",value:function(){var t=Object(s.b)(this);return Object(a.j)(a.b,{class:Object.assign(Object.assign({},Object(c.a)(this.color)),Object(i.a)({"card-header-translucent":this.translucent,"ion-inherit-color":!0},t,!0))},Object(a.j)("slot",null))}}]),t}();p.style={ios:":host{--background:transparent;--color:inherit;display:block;position:relative;background:var(--background);color:var(--color)}:host(.ion-color){background:var(--ion-color-base);color:var(--ion-color-contrast)}:host{padding-left:20px;padding-right:20px;padding-top:20px;padding-bottom:16px}@supports ((-webkit-margin-start: 0) or (margin-inline-start: 0)) or (-webkit-margin-start: 0){:host{padding-left:unset;padding-right:unset;-webkit-padding-start:20px;padding-inline-start:20px;-webkit-padding-end:20px;padding-inline-end:20px}}@supports ((-webkit-backdrop-filter: blur(0)) or (backdrop-filter: blur(0))){:host(.card-header-translucent){background-color:rgba(var(--ion-background-color-rgb, 255, 255, 255), 0.9);-webkit-backdrop-filter:saturate(180%) blur(30px);backdrop-filter:saturate(180%) blur(30px)}}",md:":host{--background:transparent;--color:inherit;display:block;position:relative;background:var(--background);color:var(--color)}:host(.ion-color){background:var(--ion-color-base);color:var(--ion-color-contrast)}:host{padding-left:16px;padding-right:16px;padding-top:16px;padding-bottom:16px}@supports ((-webkit-margin-start: 0) or (margin-inline-start: 0)) or (-webkit-margin-start: 0){:host{padding-left:unset;padding-right:unset;-webkit-padding-start:16px;padding-inline-start:16px;-webkit-padding-end:16px;padding-inline-end:16px}}::slotted(ion-card-title:not(:first-child)),::slotted(ion-card-subtitle:not(:first-child)){margin-top:8px}"};var g=function(){function t(r){Object(o.a)(this,t),Object(a.l)(this,r)}return Object(e.a)(t,[{key:"render",value:function(){var t=Object(s.b)(this);return Object(a.j)(a.b,{role:"heading","aria-level":"3",class:Object.assign(Object.assign({},Object(c.a)(this.color)),Object(i.a)({"ion-inherit-color":!0},t,!0))},Object(a.j)("slot",null))}}]),t}();g.style={ios:":host{display:block;position:relative;color:var(--color)}:host(.ion-color){color:var(--ion-color-base)}:host{--color:var(--ion-color-step-600, #666666);margin-left:0;margin-right:0;margin-top:0;margin-bottom:4px;padding-left:0;padding-right:0;padding-top:0;padding-bottom:0;font-size:12px;font-weight:700;letter-spacing:0.4px;text-transform:uppercase}",md:":host{display:block;position:relative;color:var(--color)}:host(.ion-color){color:var(--ion-color-base)}:host{--color:var(--ion-color-step-550, #737373);margin-left:0;margin-right:0;margin-top:0;margin-bottom:0;padding-left:0;padding-right:0;padding-top:0;padding-bottom:0;font-size:14px;font-weight:500}"};var b=function(){function t(r){Object(o.a)(this,t),Object(a.l)(this,r)}return Object(e.a)(t,[{key:"render",value:function(){var t=Object(s.b)(this);return Object(a.j)(a.b,{role:"heading","aria-level":"2",class:Object.assign(Object.assign({},Object(c.a)(this.color)),Object(i.a)({"ion-inherit-color":!0},t,!0))},Object(a.j)("slot",null))}}]),t}();b.style={ios:":host{display:block;position:relative;color:var(--color)}:host(.ion-color){color:var(--ion-color-base)}:host{--color:var(--ion-text-color, #000);margin-left:0;margin-right:0;margin-top:0;margin-bottom:0;padding-left:0;padding-right:0;padding-top:0;padding-bottom:0;font-size:28px;font-weight:700;line-height:1.2}",md:":host{display:block;position:relative;color:var(--color)}:host(.ion-color){color:var(--ion-color-base)}:host{--color:var(--ion-color-step-850, #262626);margin-left:0;margin-right:0;margin-top:0;margin-bottom:0;padding-left:0;padding-right:0;padding-top:0;padding-bottom:0;font-size:20px;font-weight:500;line-height:1.2}"}},175:function(t,r,n){"use strict";n.d(r,"a",(function(){return c})),n.d(r,"b",(function(){return d})),n.d(r,"c",(function(){return s})),n.d(r,"d",(function(){return p}));var i=n(2),o=n.n(i),e=n(4),a=n(15),s=function(t,r){return null!==r.closest(t)},c=function(t){return"string"===typeof t&&t.length>0?Object(a.a)({"ion-color":!0},"ion-color-".concat(t),!0):void 0},d=function(t){var r={};return function(t){return void 0!==t?(Array.isArray(t)?t:t.split(" ")).filter((function(t){return null!=t})).map((function(t){return t.trim()})).filter((function(t){return""!==t})):[]}(t).forEach((function(t){return r[t]=!0})),r},l=/^[a-z][a-z0-9+\-.]*:/,p=function(){var t=Object(e.a)(o.a.mark((function t(r,n,i){var e;return o.a.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(null==r||"#"===r[0]||l.test(r)){t.next=5;break}if(!(e=document.querySelector("ion-router"))){t.next=5;break}return null!=n&&n.preventDefault(),t.abrupt("return",e.push(r,i));case 5:return t.abrupt("return",!1);case 6:case"end":return t.stop()}}),t)})));return function(r,n,i){return t.apply(this,arguments)}}()}}]);
//# sourceMappingURL=stencil-ion-card_5-md-entry-js.168553d6.chunk.js.map
|
import React from "react"
import { graphql } from "gatsby"
import Layout from "../components/layout"
import SEO from "../components/seo"
export default ({ data }) => {
const post = data.markdownRemark
return (
<Layout>
<SEO title={post.frontmatter.title} description={post.excerpt} />
<div>
<h1>{post.frontmatter.title}</h1>
<img alt="cover" src={post.frontmatter.coverImage}></img>
<div dangerouslySetInnerHTML={{ __html: post.html }} />
</div>
</Layout>
)
}
export const query = graphql`
query($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
html
frontmatter {
title
coverImage
}
excerpt
}
}
`
|
const ws = require('./../ws');
const ready = require('./../ready');
const timing = require('./../timing');
// TODO: Salakar: all of this will go in first release
// TODO: Salakar: jet global will provide it's own methods that internally call these
let detox;
try {
// eslint-disable-next-line global-require
detox = require('detox');
} catch (e) {
// ignore
}
if (detox) {
/* ---------------------
* DEVICE OVERRIDES
* --------------------- */
// TODO: Salakar: all of this will go in first release
// TODO: Salakar: jet global will provide it's own methods that internally call these
let device;
Object.defineProperty(global, 'device', {
get() {
return device;
},
set(originalDevice) {
// device.reloadReactNative({ ... })
// todo detoxOriginalReloadReactNative currently broken it seems
// const detoxOriginalReloadReactNative = originalDevice.reloadReactNative.bind(originalDevice);
if (!originalDevice) {
return undefined;
}
originalDevice.reloadReactNative = async () => {
ready.reset();
global.jet.reload();
return ready.wait();
};
// TODO: Salakar: all of this will go in first release
// TODO: Salakar: jet global will provide it's own methods that internally call these
// device.launchApp({ ... })
const detoxOriginalLaunchApp = originalDevice.launchApp.bind(originalDevice);
originalDevice.launchApp = async options => {
if (options && options.newInstance) {
ready.reset();
}
const result = detoxOriginalLaunchApp(options);
await ready.wait();
return result;
};
device = originalDevice;
return originalDevice;
},
});
// TODO: Salakar: all of this will go in first release
// TODO: Salakar: jet global will provide it's own methods that internally call these
/* -------------------
* DETOX OVERRIDES
* ------------------- */
// TODO: Salakar: all of this will go in first release
// TODO: Salakar: jet global will provide it's own methods that internally call these
// detox.cleanup()
const detoxOriginalCleanup = detox.cleanup.bind(detox);
detox.cleanup = async (...args) => {
timing.stop();
// detox doesn't automatically terminate ios apps after testing
// but does on android - added to keep consistency
if (device.getPlatform() === 'ios') {
await device.terminateApp();
}
ws.stop();
await detoxOriginalCleanup(...args);
};
}
module.exports = detox;
|
from torch_ac.algos import A2CAlgo, PPOAlgo, MultiQAlgo, WeightedPPOAlgo
from torch_ac.model import ACModel, RecurrentACModel
from torch_ac.utils import DictList
|
/*! Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: MIT-0
*/
const AWS = require('aws-sdk')
AWS.config.region = process.env.AWS_REGION || 'us-east-1'
const eventbridge = new AWS.EventBridge()
exports.handler = async (event) => {
console.log(JSON.stringify(event, 0, null));
let payload = { Entries: [] };
event.Records.forEach((item) => {
payload.Entries.push({
// Event envelope fields
Source: 'MyDynamoStream',
EventBusName: 'MyEventBus',
DetailType: 'transaction',
Time: new Date(),
// Main event body
Detail: JSON.stringify(item)
});
});
console.log("Payload to Event Bridge");
console.log(payload);
const result = await eventbridge.putEvents(payload).promise();
console.log('EventBridge result');
console.log(result);
}
|
import functools
import random
import string
import unittest
import msgpack
import mock
import responses
from ably.http.http import Http
class BaseTestCase(unittest.TestCase):
def responses_add_empty_msg_pack(self, url, method=responses.GET):
responses.add(responses.GET, url, body=msgpack.packb({}),
content_type='application/x-msgpack')
@classmethod
def get_channel_name(cls, prefix=''):
return prefix + random_string(10)
@classmethod
def get_channel(cls, prefix=''):
name = cls.get_channel_name(prefix)
return cls.ably.channels.get(name)
def assert_responses_type(protocol):
"""
This is a decorator to check if we retrieved responses with the correct protocol.
usage:
@assert_responses_type('json')
def test_something(self):
...
this will check if all responses received during the test will be in the format
json.
supports json and msgpack
"""
responses = []
def patch():
original = Http.make_request
def fake_make_request(self, *args, **kwargs):
response = original(self, *args, **kwargs)
responses.append(response)
return response
patcher = mock.patch.object(Http, 'make_request', fake_make_request)
patcher.start()
return patcher
def unpatch(patcher):
patcher.stop()
def test_decorator(fn):
@functools.wraps(fn)
def test_decorated(self, *args, **kwargs):
patcher = patch()
fn(self, *args, **kwargs)
unpatch(patcher)
assert len(responses) >= 1, "If your test doesn't make any requests, use the @dont_vary_protocol decorator"
for response in responses:
if protocol == 'json':
assert response.headers['content-type'] == 'application/json'
if response.content:
response.json()
else:
assert response.headers['content-type'] == 'application/x-msgpack'
if response.content:
msgpack.unpackb(response.content, encoding='utf-8')
return test_decorated
return test_decorator
class VaryByProtocolTestsMetaclass(type):
"""
Metaclass to run tests in more than one protocol.
Usage:
* set this as metaclass of the TestCase class
* create the following method:
def per_protocol_setup(self, use_binary_protocol):
# do something here that will run before each test.
* now every test will run twice and before test is run per_protocol_setup
is called
* exclude tests with the @dont_vary_protocol decorator
"""
def __new__(cls, clsname, bases, dct):
for key, value in tuple(dct.items()):
if key.startswith('test') and not getattr(value, 'dont_vary_protocol',
False):
wrapper_bin = cls.wrap_as('bin', key, value)
wrapper_text = cls.wrap_as('text', key, value)
dct[key + '_bin'] = wrapper_bin
dct[key + '_text'] = wrapper_text
del dct[key]
return super(VaryByProtocolTestsMetaclass, cls).__new__(cls, clsname,
bases, dct)
@staticmethod
def wrap_as(ttype, old_name, old_func):
expected_content = {'bin': 'msgpack', 'text': 'json'}
@assert_responses_type(expected_content[ttype])
def wrapper(self):
if hasattr(self, 'per_protocol_setup'):
self.per_protocol_setup(ttype == 'bin')
old_func(self)
wrapper.__name__ = old_name + '_' + ttype
return wrapper
def dont_vary_protocol(func):
func.dont_vary_protocol = True
return func
def random_string(length, alphabet=string.ascii_letters):
return ''.join([random.choice(alphabet) for x in range(length)])
def new_dict(src, **kw):
new = src.copy()
new.update(kw)
return new
def get_random_key(d):
return random.choice(list(d))
|
import { graphql } from "gatsby"
import { arrayOf, bool, shape, string, object} from "prop-types"
export const ProfileType = {
name: string.isRequired,
profession: string.isRequired,
relocation: bool.isRequired,
about: string.isRequired,
location: string.isRequied,
workingOn: string.isRequired,
email: string.isRequired,
for_hire: bool.isRequired,
image: shape({
childImageSharp: object.isRequired,
publicURL: string.isRequired
}),
skills: arrayOf(string).isRequired,
pluralsightProfile: string.isRequired,
}
export const query = graphql`
fragment ProfileFragment on ProfileYaml {
name
profession
relocation
about
location
workingOn
email
for_hire
image {
childImageSharp {
fluid(maxWidth: 224 quality: 85) {
...GatsbyImageSharpFluid_withWebp
}
}
publicURL
}
skills
pluralsightProfile
}
`
|
import RecordingField from '../../recordingfield'
import OptionsField from '../../optionsfield'
import SpeakField from '../../speakfield'
import PropTypes from 'prop-types'
import { Form } from '@admin'
import React from 'react'
import _ from 'lodash'
class Menu extends React.PureComponent {
static propTypes = {
config: PropTypes.object,
users: PropTypes.array,
onCancel: PropTypes.func,
onChange: PropTypes.func,
onDone: PropTypes.func
}
form = null
state = {
config: null
}
_handleCancel = this._handleCancel.bind(this)
_handleChange = this._handleChange.bind(this)
_handleDone = this._handleDone.bind(this)
_handleSubmit = this._handleSubmit.bind(this)
render() {
if(!this.state.config) return null
return <Form { ...this._getForm() } />
}
componentDidMount() {
this.setState({
config: {
...this._getDefault(),
...this.props.config || {}
}
})
}
_getDefault() {
return {
code: _.random(Math.pow(36, 9), Math.pow(36, 10) - 1).toString(36),
strategy: 'say',
say: {
voice: 'Salli',
text: 'Listen carefully to the following options'
},
options: [],
specials: []
}
}
_getForm() {
const { config } = this.state
return {
reference: node => this.form = node,
title: 'Dial Menu',
onCancel: this._handleCancel,
onChange: this._handleChange,
onSuccess: this._handleDone,
cancelIcon: 'chevron-left',
saveText: null,
buttons: [
{ label: 'Done', color: 'red', handler: this._handleSubmit }
],
sections: [
{
fields: [
{ name: 'code', type: 'hidden', defaultValue: config.code },
{ label: 'Menu Name', name: 'name', type: 'textfield', placeholder: 'Enter a name for this step', required: true, defaultValue: config.name },
{ label: 'Greeting', instructions: `
Play this greeting to inform the caller of their available
options. The greeting will stop when the caller begins to dial.
`, type: 'segment', fields: [
{ name: 'strategy', type: 'radiogroup', options: [
{ value: 'say', text: 'Speak text' },
{ value: 'play', text: 'Play an audio file' }
], defaultValue: config.strategy },
...this._getStrategy()
] },
{ label: 'Options', name: 'options', type: OptionsField, required: true, defaultValue: config.options },
{ label: 'Special Characters', type: 'segment', fields: [
{ name: 'specials', type: 'checkboxes', options: [
{ value: 'hash', text: 'Respond to hash (#)' },
{ value: 'star', text: 'Respond to star (*)' }
], defaultValue: config.specials }
] }
]
}
]
}
}
_getStrategy() {
const { config } = this.state
if(config.strategy === 'say') {
return [
{ name: 'say', type: SpeakField, placeholder: 'Enter a greeting', required: true, defaultValue: config.say }
]
}
if(config.strategy === 'play') {
return [
{ name: 'recording_id', type: RecordingField, required: true, defaultValue: config.recording_id }
]
}
return []
}
_handleCancel() {
this.props.onCancel()
}
_handleChange(config) {
this.setState({ config })
}
_handleDone() {
const { config } = this.state
this.props.onDone(config)
}
_handleSubmit() {
this.form.submit()
}
}
export default Menu
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.backends import cudnn
cudnn.benchmark = True
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
class LossFunctions:
def __init__(self, num_classes):
super(LossFunctions, self).__init__()
self.num_classes = int(num_classes)
# Log (cross-entropy) Loss
def cross_entropy_loss(self, x, y):
loss = F.cross_entropy(x, y)
return loss
# Sum of sqaures
def sos_loss(self, x, y):
ones = torch.sparse.torch.eye(self.num_classes).to('cuda:0')
y = ones.index_select(0, y)
m = nn.Softmax(dim=1)
criterion = nn.MSELoss(reduction='sum')
loss = criterion(m(x), y)
return loss
# Mean Sqaured loss - L2 loss
def mse_loss(self, x, y):
ones = torch.sparse.torch.eye(self.num_classes).to('cuda:0')
y = ones.index_select(0, y)
m = nn.Softmax(dim=1)
criterion = nn.MSELoss(reduction='mean')
loss = criterion(m(x), y)
return loss
# Negative log likelihood = logarithmic softmax
def neg_loglike_loss(self, x, y):
m = nn.LogSoftmax(dim=1)
nll_loss = nn.NLLLoss()
loss = nll_loss(m(x), y)
return loss
# Expectation Loss - L1 loss - Mean absoulte error
def expectation_loss(self, x, y):
ones = torch.sparse.torch.eye(self.num_classes).to('cuda:0')
y = ones.index_select(0, y)
m = nn.Softmax(dim=1)
loss = F.l1_loss(m(x), y)
return loss
def bce_loss(self, x, y):
ones = torch.sparse.torch.eye(self.num_classes).to('cuda:0')
y = ones.index_select(0, y)
loss = F.binary_cross_entropy_with_logits(x, y)
return loss
|
# qubit number=4
# total number=10
import pyquil
from pyquil.api import local_forest_runtime, QVMConnection
from pyquil import Program, get_qc
from pyquil.gates import *
import numpy as np
conn = QVMConnection()
def make_circuit()-> Program:
prog = Program() # circuit begin
prog += H(1) # number=2
prog += H(2) # number=3
prog += H(3) # number=4
prog += Y(3) # number=5
prog += SWAP(1,0) # number=6
prog += SWAP(1,0) # number=7
prog += X(0) # number=8
prog += X(0) # number=9
# circuit end
return prog
def summrise_results(bitstrings) -> dict:
d = {}
for l in bitstrings:
if d.get(l) is None:
d[l] = 1
else:
d[l] = d[l] + 1
return d
if __name__ == '__main__':
prog = make_circuit()
qvm = get_qc('4q-qvm')
results = qvm.run_and_measure(prog,1024)
bitstrings = np.vstack([results[i] for i in qvm.qubits()]).T
bitstrings = [''.join(map(str, l)) for l in bitstrings]
writefile = open("../data/startPyquil157.csv","w")
print(summrise_results(bitstrings),file=writefile)
writefile.close()
|
'''
copy from mmaction2
https://github.com/open-mmlab/mmaction2
'''
import argparse
import glob
import os
import os.path as osp
import sys
import warnings
from multiprocessing import Pool
import mmcv
import numpy as np
img_process_fn = None
'''def img_process_fn(img):
H,W,_ = img.shape
return img[:,W//2:]'''
def extract_frame(vid_item):
"""Generate optical flow using dense flow.
Args:
vid_item (list): Video item containing video full path,
video (short) path, video id.
Returns:
bool: Whether generate optical flow successfully.
"""
full_path, vid_path, vid_id, method, task = vid_item
if '/' in vid_path:
act_name = osp.basename(osp.dirname(vid_path))
out_full_path = osp.join(args.out_dir, act_name)
else:
out_full_path = args.out_dir
if task == 'rgb':
if args.use_opencv:
# Not like using denseflow,
# Use OpenCV will not make a sub directory with the video name
video_name = osp.splitext(osp.basename(vid_path))[0]
out_full_path = osp.join(out_full_path, video_name)
vr = mmcv.VideoReader(full_path)
print(f"{full_path} fps {vr.fps}.")
# for i in range(len(vr)):
for i, vr_frame in enumerate(vr):
if vr_frame is not None:
w, h, _ = np.shape(vr_frame)
if img_process_fn is not None:
vr_frame = img_process_fn(vr_frame)
if args.new_short == 0:
if args.new_width == 0 or args.new_height == 0:
# Keep original shape
out_img = vr_frame
else:
out_img = mmcv.imresize(vr_frame,
(args.new_width,
args.new_height))
else:
if min(h, w) == h:
new_h = args.new_short
new_w = int((new_h / h) * w)
else:
new_w = args.new_short
new_h = int((new_w / w) * h)
out_img = mmcv.imresize(vr_frame, (new_h, new_w))
mmcv.imwrite(out_img, f'{out_full_path}/img_{i + 1:05d}.jpg')
else:
warnings.warn(
'Length inconsistent!'
f'Early stop with {i + 1} out of {len(vr)} frames.')
break
else:
if args.new_short == 0:
cmd = osp.join(
f"denseflow '{full_path}' -b=20 -s=0 -o='{out_full_path}'"
f' -nw={args.new_width} -nh={args.new_height} -v')
else:
cmd = osp.join(
f"denseflow '{full_path}' -b=20 -s=0 -o='{out_full_path}'"
f' -ns={args.new_short} -v')
os.system(cmd)
elif task == 'flow':
if args.input_frames:
if args.new_short == 0:
cmd = osp.join(
f"denseflow '{full_path}' -a={method} -b=20 -s=1 -o='{out_full_path}'" # noqa: E501
f' -nw={args.new_width} --nh={args.new_height} -v --if')
else:
cmd = osp.join(
f"denseflow '{full_path}' -a={method} -b=20 -s=1 -o='{out_full_path}'" # noqa: E501
f' -ns={args.new_short} -v --if')
else:
if args.new_short == 0:
cmd = osp.join(
f"denseflow '{full_path}' -a={method} -b=20 -s=1 -o='{out_full_path}'" # noqa: E501
f' -nw={args.new_width} --nh={args.new_height} -v')
else:
cmd = osp.join(
f"denseflow '{full_path}' -a={method} -b=20 -s=1 -o='{out_full_path}'" # noqa: E501
f' -ns={args.new_short} -v')
os.system(cmd)
else:
if args.new_short == 0:
cmd_rgb = osp.join(
f"denseflow '{full_path}' -b=20 -s=0 -o='{out_full_path}'"
f' -nw={args.new_width} -nh={args.new_height} -v')
cmd_flow = osp.join(
f"denseflow '{full_path}' -a={method} -b=20 -s=1 -o='{out_full_path}'" # noqa: E501
f' -nw={args.new_width} -nh={args.new_height} -v')
else:
cmd_rgb = osp.join(
f"denseflow '{full_path}' -b=20 -s=0 -o='{out_full_path}'"
f' -ns={args.new_short} -v')
cmd_flow = osp.join(
f"denseflow '{full_path}' -a={method} -b=20 -s=1 -o='{out_full_path}'" # noqa: E501
f' -ns={args.new_short} -v')
os.system(cmd_rgb)
os.system(cmd_flow)
print(f'{task} {vid_id} {vid_path} {method} done')
sys.stdout.flush()
return True
def parse_args():
parser = argparse.ArgumentParser(description='extract optical flows')
parser.add_argument('src_dir', type=str, help='source video directory')
parser.add_argument('out_dir', type=str, help='output rawframe directory')
parser.add_argument(
'--task',
type=str,
default='rgb',
choices=['rgb', 'flow', 'both'],
help='which type of frames to be extracted')
parser.add_argument(
'--level',
type=int,
choices=[1, 2],
default=1,
help='directory level of data')
parser.add_argument(
'--num-worker',
type=int,
default=8,
help='number of workers to build rawframes')
parser.add_argument(
'--flow-type',
type=str,
default=None,
choices=[None, 'tvl1', 'warp_tvl1', 'farn', 'brox'],
help='flow type to be generated')
parser.add_argument(
'--out-format',
type=str,
default='jpg',
choices=['jpg', 'h5', 'png'],
help='output format')
parser.add_argument(
'--ext',
type=str,
default='mp4',
#choices=['avi', 'mp4', 'webm','MOV'],
help='video file extensions')
parser.add_argument(
'--mixed-ext',
action='store_true',
help='process video files with mixed extensions')
parser.add_argument(
'--new-width', type=int, default=0, help='resize image width')
parser.add_argument(
'--new-height', type=int, default=0, help='resize image height')
parser.add_argument(
'--new-short',
type=int,
default=0,
help='resize image short side length keeping ratio')
parser.add_argument('--num-gpu', type=int, default=8, help='number of GPU')
parser.add_argument(
'--resume',
action='store_true',
default=False,
help='resume optical flow extraction instead of overwriting')
parser.add_argument(
'--use-opencv',
action='store_true',
default=True,
help='Whether to use opencv to extract rgb frames')
parser.add_argument(
'--input-frames',
action='store_true',
help='Whether to extract flow frames based on rgb frames')
args = parser.parse_args()
return args
if __name__ == '__main__':
args = parse_args()
if not osp.isdir(args.out_dir):
print(f'Creating folder: {args.out_dir}')
os.makedirs(args.out_dir)
if args.level == 2:
classes = os.listdir(args.src_dir)
for classname in classes:
new_dir = osp.join(args.out_dir, classname)
if not osp.isdir(new_dir):
print(f'Creating folder: {new_dir}')
os.makedirs(new_dir)
if args.input_frames:
print('Reading rgb frames from folder: ', args.src_dir)
fullpath_list = glob.glob(args.src_dir + '/*' * args.level)
done_fullpath_list = glob.glob(args.out_dir + '/*' * args.level)
print('Total number of rgb frame folders found: ', len(fullpath_list))
else:
print('Reading videos from folder: ', args.src_dir)
if args.mixed_ext:
print('Extension of videos is mixed')
fullpath_list = glob.glob(args.src_dir + '/*' * args.level)
done_fullpath_list = glob.glob(args.out_dir + '/*' * args.level)
else:
print('Extension of videos: ', args.ext)
fullpath_list = glob.glob(args.src_dir + '/*' * args.level + '.' +
args.ext)
done_fullpath_list = glob.glob(args.out_dir + '/*' * args.level)
if len(fullpath_list) == 0 and osp.isfile(args.src_dir):
fullpath_list = [args.src_dir]
print('Total number of videos found: ', len(fullpath_list))
if args.resume:
fullpath_list = set(fullpath_list).difference(set(done_fullpath_list))
fullpath_list = list(fullpath_list)
print('Resuming. number of videos to be done: ', len(fullpath_list))
if args.level == 2:
vid_list = list(
map(
lambda p: osp.join(
osp.basename(osp.dirname(p)), osp.basename(p)),
fullpath_list))
elif args.level == 1:
vid_list = list(map(osp.basename, fullpath_list))
pool = Pool(args.num_worker)
pool.map(
extract_frame,
zip(fullpath_list, vid_list, range(len(vid_list)),
len(vid_list) * [args.flow_type],
len(vid_list) * [args.task]))
'''
Example: python build_rawframes.py /home/wj/ai/mldata/txc_park_videos/videos /home/wj/ai/mldata/txc_park_videos/videos_rgb --task rgb --level 1 --ext mp4 --use-opencv
'''
|
const fs = require('fs');
const path = require('path');
const yaml = require('js-yaml');
const NavigationPlugin = require('@11ty/eleventy-navigation');
const filters = require('./utils/filters');
const markdown = require('./utils/markdown');
const shortcodes = require('./utils/shortcodes');
const transforms = require('./utils/transforms');
module.exports = (config) => {
const manifestPath = path.resolve(__dirname, '_site/assets/manifest.json');
// Allow for customizing the built in markdown parser.
config.setLibrary('md', markdown);
// Allow eleventy to understand yaml files
config.addDataExtension('yml', (contents) => yaml.load(contents));
// Plugins
config.addPlugin(NavigationPlugin);
// Filters
Object.keys(filters).forEach((key) => {
config.addFilter(key, filters[key]);
});
// Transforms
Object.keys(transforms).forEach((key) => {
config.addTransform(key, transforms[key]);
});
// Shortcodes
config.addShortcode('icon', shortcodes.icon);
config.addPairedShortcode('markdown', shortcodes.markdown);
config.addNunjucksAsyncShortcode('image', shortcodes.image);
config.addNunjucksAsyncShortcode('webpack', shortcodes.webpack);
// Pass-through files
// Everything inside static is copied verbatim to `_site`
config.addPassthroughCopy('src/assets/static');
// BrowserSync Overrides
config.setBrowserSyncConfig({
...config.browserSyncConfig,
// Reload when manifest file changes
files: [manifestPath],
// Show 404 page on invalid urls
callbacks: {
ready: (err, browserSync) => {
browserSync.addMiddleware('*', (req, res) => {
const fourOFour = fs.readFileSync('_site/404.html');
res.writeHead(404, {"Content-Type": "text/html; charset=UTF-8"});
res.write(fourOFour);
res.end();
});
}
},
// Speed/clean up build time
ui: false,
ghostMode: false
});
return {
dir: { input: 'src', output: '_site', includes: 'includes', data: 'data' },
// Allow nunjucks, markdown and 11ty files to be processed
templateFormats: ['njk', 'md', '11ty.js'],
htmlTemplateEngine: 'njk',
// Allow pre-processing `.md` files with nunjucks
// thus transforming the shortcodes
markdownTemplateEngine: 'njk'
};
};
|
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================
"""Implementation of Neural Net (NN) functions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import candidate_sampling_ops
from tensorflow.python.ops import embedding_ops
from tensorflow.python.ops import gen_nn_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.ops import sparse_ops
def log_poisson_loss(targets, log_input, compute_full_loss=False, name=None):
"""Computes log Poisson loss given `log_input`.
Gives the log-likelihood loss between the prediction and the target under the
assumption that the target has a Poisson distribution.
Caveat: By default, this is not the exact loss, but the loss minus a
constant term [log(z!)]. That has no effect for optimization, but
does not play well with relative loss comparisons. To compute an
approximation of the log factorial term, specify
compute_full_loss=True to enable Stirling's Approximation.
For brevity, let `c = log(x) = log_input`, `z = targets`. The log Poisson
loss is
-log(exp(-x) * (x^z) / z!)
= -log(exp(-x) * (x^z)) + log(z!)
~ -log(exp(-x)) - log(x^z) [+ z * log(z) - z + 0.5 * log(2 * pi * z)]
[ Note the second term is the Stirling's Approximation for log(z!).
It is invariant to x and does not affect optimization, though
important for correct relative loss comparisons. It is only
computed when compute_full_loss == True. ]
= x - z * log(x) [+ z * log(z) - z + 0.5 * log(2 * pi * z)]
= exp(c) - z * c [+ z * log(z) - z + 0.5 * log(2 * pi * z)]
Args:
targets: A `Tensor` of the same type and shape as `log_input`.
log_input: A `Tensor` of type `float32` or `float64`.
compute_full_loss: whether to compute the full loss. If false, a constant
term is dropped in favor of more efficient optimization.
name: A name for the operation (optional).
Returns:
A `Tensor` of the same shape as `log_input` with the componentwise
logistic losses.
Raises:
ValueError: If `log_input` and `targets` do not have the same shape.
"""
with ops.name_scope(name, "log_poisson_loss", [log_input, targets]) as name:
log_input = ops.convert_to_tensor(log_input, name="log_input")
targets = ops.convert_to_tensor(targets, name="targets")
try:
targets.get_shape().merge_with(log_input.get_shape())
except ValueError:
raise ValueError(
"log_input and targets must have the same shape (%s vs %s)" %
(log_input.get_shape(), targets.get_shape()))
result = math_ops.exp(log_input) - log_input * targets
if compute_full_loss:
# need to create constant tensors here so that their dtypes can be matched
# to that of the targets.
point_five = constant_op.constant(0.5, dtype=targets.dtype)
two_pi = constant_op.constant(2 * math.pi, dtype=targets.dtype)
stirling_approx = (targets * math_ops.log(targets)) - targets + (
point_five * math_ops.log(two_pi * targets))
zeros = array_ops.zeros_like(targets, dtype=targets.dtype)
ones = array_ops.ones_like(targets, dtype=targets.dtype)
cond = math_ops.logical_and(targets >= zeros, targets <= ones)
result += array_ops.where(cond, zeros, stirling_approx)
return result
def sigmoid_cross_entropy_with_logits(logits, targets, name=None):
"""Computes sigmoid cross entropy given `logits`.
Measures the probability error in discrete classification tasks in which each
class is independent and not mutually exclusive. For instance, one could
perform multilabel classification where a picture can contain both an elephant
and a dog at the same time.
For brevity, let `x = logits`, `z = targets`. The logistic loss is
z * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x))
= z * -log(1 / (1 + exp(-x))) + (1 - z) * -log(exp(-x) / (1 + exp(-x)))
= z * log(1 + exp(-x)) + (1 - z) * (-log(exp(-x)) + log(1 + exp(-x)))
= z * log(1 + exp(-x)) + (1 - z) * (x + log(1 + exp(-x))
= (1 - z) * x + log(1 + exp(-x))
= x - x * z + log(1 + exp(-x))
For x < 0, to avoid overflow in exp(-x), we reformulate the above
x - x * z + log(1 + exp(-x))
= log(exp(x)) - x * z + log(1 + exp(-x))
= - x * z + log(1 + exp(x))
Hence, to ensure stability and avoid overflow, the implementation uses this
equivalent formulation
max(x, 0) - x * z + log(1 + exp(-abs(x)))
`logits` and `targets` must have the same type and shape.
Args:
logits: A `Tensor` of type `float32` or `float64`.
targets: A `Tensor` of the same type and shape as `logits`.
name: A name for the operation (optional).
Returns:
A `Tensor` of the same shape as `logits` with the componentwise
logistic losses.
Raises:
ValueError: If `logits` and `targets` do not have the same shape.
"""
with ops.name_scope(name, "logistic_loss", [logits, targets]) as name:
logits = ops.convert_to_tensor(logits, name="logits")
targets = ops.convert_to_tensor(targets, name="targets")
try:
targets.get_shape().merge_with(logits.get_shape())
except ValueError:
raise ValueError("logits and targets must have the same shape (%s vs %s)"
% (logits.get_shape(), targets.get_shape()))
# The logistic loss formula from above is
# x - x * z + log(1 + exp(-x))
# For x < 0, a more numerically stable formula is
# -x * z + log(1 + exp(x))
# Note that these two expressions can be combined into the following:
# max(x, 0) - x * z + log(1 + exp(-abs(x)))
# To allow computing gradients at zero, we define custom versions of max and
# abs functions.
zeros = array_ops.zeros_like(logits, dtype=logits.dtype)
cond = (logits >= zeros)
relu_logits = array_ops.where(cond, logits, zeros)
neg_abs_logits = array_ops.where(cond, -logits, logits)
return math_ops.add(relu_logits - logits * targets,
math_ops.log1p(math_ops.exp(neg_abs_logits)),
name=name)
def weighted_cross_entropy_with_logits(targets, logits, pos_weight, name=None):
"""Computes a weighted cross entropy.
This is like `sigmoid_cross_entropy_with_logits()` except that `pos_weight`,
allows one to trade off recall and precision by up- or down-weighting the
cost of a positive error relative to a negative error.
The usual cross-entropy cost is defined as:
targets * -log(sigmoid(logits)) + (1 - targets) * -log(1 - sigmoid(logits))
The argument `pos_weight` is used as a multiplier for the positive targets:
targets * -log(sigmoid(logits)) * pos_weight +
(1 - targets) * -log(1 - sigmoid(logits))
For brevity, let `x = logits`, `z = targets`, `q = pos_weight`.
The loss is:
qz * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x))
= qz * -log(1 / (1 + exp(-x))) + (1 - z) * -log(exp(-x) / (1 + exp(-x)))
= qz * log(1 + exp(-x)) + (1 - z) * (-log(exp(-x)) + log(1 + exp(-x)))
= qz * log(1 + exp(-x)) + (1 - z) * (x + log(1 + exp(-x))
= (1 - z) * x + (qz + 1 - z) * log(1 + exp(-x))
= (1 - z) * x + (1 + (q - 1) * z) * log(1 + exp(-x))
Setting `l = (1 + (q - 1) * z)`, to ensure stability and avoid overflow,
the implementation uses
(1 - z) * x + l * (log(1 + exp(-abs(x))) + max(-x, 0))
`logits` and `targets` must have the same type and shape.
Args:
targets: A `Tensor` of the same type and shape as `logits`.
logits: A `Tensor` of type `float32` or `float64`.
pos_weight: A coefficient to use on the positive examples.
name: A name for the operation (optional).
Returns:
A `Tensor` of the same shape as `logits` with the componentwise
weighted logistic losses.
Raises:
ValueError: If `logits` and `targets` do not have the same shape.
"""
with ops.name_scope(name, "logistic_loss", [logits, targets]) as name:
logits = ops.convert_to_tensor(logits, name="logits")
targets = ops.convert_to_tensor(targets, name="targets")
try:
targets.get_shape().merge_with(logits.get_shape())
except ValueError:
raise ValueError("logits and targets must have the same shape (%s vs %s)"
% (logits.get_shape(), targets.get_shape()))
# The logistic loss formula from above is
# (1 - z) * x + (1 + (q - 1) * z) * log(1 + exp(-x))
# For x < 0, a more numerically stable formula is
# (1 - z) * x + (1 + (q - 1) * z) * log(1 + exp(x)) - l * x
# To avoid branching, we use the combined version
# (1 - z) * x + l * (log(1 + exp(-abs(x))) + max(-x, 0))
log_weight = 1 + (pos_weight - 1) * targets
return math_ops.add(
(1 - targets) * logits,
log_weight * (math_ops.log1p(math_ops.exp(-math_ops.abs(logits))) +
nn_ops.relu(-logits)),
name=name)
def relu_layer(x, weights, biases, name=None):
"""Computes Relu(x * weight + biases).
Args:
x: a 2D tensor. Dimensions typically: batch, in_units
weights: a 2D tensor. Dimensions typically: in_units, out_units
biases: a 1D tensor. Dimensions: out_units
name: A name for the operation (optional). If not specified
"nn_relu_layer" is used.
Returns:
A 2-D Tensor computing relu(matmul(x, weights) + biases).
Dimensions typically: batch, out_units.
"""
with ops.name_scope(name, "relu_layer", [x, weights, biases]) as name:
x = ops.convert_to_tensor(x, name="x")
weights = ops.convert_to_tensor(weights, name="weights")
biases = ops.convert_to_tensor(biases, name="biases")
xw_plus_b = nn_ops.bias_add(math_ops.matmul(x, weights), biases)
return nn_ops.relu(xw_plus_b, name=name)
def l2_normalize(x, dim, epsilon=1e-12, name=None):
"""Normalizes along dimension `dim` using an L2 norm.
For a 1-D tensor with `dim = 0`, computes
output = x / sqrt(max(sum(x**2), epsilon))
For `x` with more dimensions, independently normalizes each 1-D slice along
dimension `dim`.
Args:
x: A `Tensor`.
dim: Dimension along which to normalize. A scalar or a vector of
integers.
epsilon: A lower bound value for the norm. Will use `sqrt(epsilon)` as the
divisor if `norm < sqrt(epsilon)`.
name: A name for this operation (optional).
Returns:
A `Tensor` with the same shape as `x`.
"""
with ops.name_scope(name, "l2_normalize", [x]) as name:
x = ops.convert_to_tensor(x, name="x")
square_sum = math_ops.reduce_sum(math_ops.square(x), dim, keep_dims=True)
x_inv_norm = math_ops.rsqrt(math_ops.maximum(square_sum, epsilon))
return math_ops.mul(x, x_inv_norm, name=name)
def zero_fraction(value, name=None):
"""Returns the fraction of zeros in `value`.
If `value` is empty, the result is `nan`.
This is useful in summaries to measure and report sparsity. For example,
```python
z = tf.Relu(...)
summ = tf.contrib.deprecated.scalar_summary('sparsity',
tf.nn.zero_fraction(z))
```
Args:
value: A tensor of numeric type.
name: A name for the operation (optional).
Returns:
The fraction of zeros in `value`, with type `float32`.
"""
with ops.name_scope(name, "zero_fraction", [value]):
value = ops.convert_to_tensor(value, name="value")
zero = constant_op.constant(0, dtype=value.dtype, name="zero")
return math_ops.reduce_mean(
math_ops.cast(math_ops.equal(value, zero), dtypes.float32))
# pylint: disable=redefined-builtin
def depthwise_conv2d(input, filter, strides, padding, rate=None, name=None):
"""Depthwise 2-D convolution.
Given an input tensor of shape `[batch, in_height, in_width, in_channels]`
and a filter tensor of shape
`[filter_height, filter_width, in_channels, channel_multiplier]`
containing `in_channels` convolutional filters of depth 1, `depthwise_conv2d`
applies a different filter to each input channel (expanding from 1 channel
to `channel_multiplier` channels for each), then concatenates the results
together. The output has `in_channels * channel_multiplier` channels.
In detail,
output[b, i, j, k * channel_multiplier + q] = sum_{di, dj}
filter[di, dj, k, q] * input[b, strides[1] * i + rate[0] * di,
strides[2] * j + rate[1] * dj, k]
Must have `strides[0] = strides[3] = 1`. For the most common case of the
same horizontal and vertical strides, `strides = [1, stride, stride, 1]`.
If any value in `rate` is greater than 1, we perform atrous depthwise
convolution, in which case all values in the `strides` tensor must be equal
to 1.
Args:
input: 4-D with shape `[batch, in_height, in_width, in_channels]`.
filter: 4-D with shape
`[filter_height, filter_width, in_channels, channel_multiplier]`.
strides: 1-D of size 4. The stride of the sliding window for each
dimension of `input`.
padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.
See the [comment
here](https://www.tensorflow.org/api_docs/python/nn.html#convolution)
rate: 1-D of size 2. The dilation rate in which we sample input values
across the `height` and `width` dimensions in atrous convolution. If it is
greater than 1, then all values of strides must be 1.
name: A name for this operation (optional).
Returns:
A 4-D `Tensor` of shape
`[batch, out_height, out_width, in_channels * channel_multiplier].`
"""
with ops.name_scope(name, "depthwise", [input, filter]) as name:
input = ops.convert_to_tensor(input, name="tensor_in")
filter = ops.convert_to_tensor(filter, name="filter_in")
if rate is None:
rate = [1, 1]
def op(input_converted, _, padding):
return nn_ops.depthwise_conv2d_native(
input=input_converted,
filter=filter,
strides=strides,
padding=padding,
name=name)
return nn_ops.with_space_to_batch(
input=input,
filter_shape=array_ops.shape(filter),
dilation_rate=rate,
padding=padding,
op=op)
# pylint: enable=redefined-builtin
# pylint: disable=redefined-builtin,line-too-long
def separable_conv2d(input,
depthwise_filter,
pointwise_filter,
strides,
padding,
rate=None,
name=None):
"""2-D convolution with separable filters.
Performs a depthwise convolution that acts separately on channels followed by
a pointwise convolution that mixes channels. Note that this is separability
between dimensions `[1, 2]` and `3`, not spatial separability between
dimensions `1` and `2`.
In detail,
output[b, i, j, k] = sum_{di, dj, q, r]
input[b, strides[1] * i + di, strides[2] * j + dj, q] *
depthwise_filter[di, dj, q, r] *
pointwise_filter[0, 0, q * channel_multiplier + r, k]
`strides` controls the strides for the depthwise convolution only, since
the pointwise convolution has implicit strides of `[1, 1, 1, 1]`. Must have
`strides[0] = strides[3] = 1`. For the most common case of the same
horizontal and vertical strides, `strides = [1, stride, stride, 1]`.
If any value in `rate` is greater than 1, we perform atrous depthwise
convolution, in which case all values in the `strides` tensor must be equal
to 1.
Args:
input: 4-D `Tensor` with shape `[batch, in_height, in_width, in_channels]`.
depthwise_filter: 4-D `Tensor` with shape
`[filter_height, filter_width, in_channels, channel_multiplier]`.
Contains `in_channels` convolutional filters of depth 1.
pointwise_filter: 4-D `Tensor` with shape
`[1, 1, channel_multiplier * in_channels, out_channels]`. Pointwise
filter to mix channels after `depthwise_filter` has convolved spatially.
strides: 1-D of size 4. The strides for the depthwise convolution for
each dimension of `input`.
padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.
See the [comment
here](https://www.tensorflow.org/api_docs/python/nn.html#convolution)
rate: 1-D of size 2. The dilation rate in which we sample input values
across the `height` and `width` dimensions in atrous convolution. If it is
greater than 1, then all values of strides must be 1.
name: A name for this operation (optional).
Returns:
A 4-D `Tensor` of shape `[batch, out_height, out_width, out_channels]`.
Raises:
ValueError: If channel_multiplier * in_channels > out_channels,
which means that the separable convolution is overparameterized.
"""
with ops.name_scope(name, "separable_conv2d",
[input, depthwise_filter, pointwise_filter]) as name:
input = ops.convert_to_tensor(input, name="tensor_in")
depthwise_filter = ops.convert_to_tensor(
depthwise_filter, name="depthwise_filter")
pointwise_filter = ops.convert_to_tensor(
pointwise_filter, name="pointwise_filter")
pointwise_filter_shape = pointwise_filter.get_shape().with_rank(4)
pointwise_filter_shape[0].assert_is_compatible_with(1)
pointwise_filter_shape[1].assert_is_compatible_with(1)
channel_multiplier = depthwise_filter.get_shape().with_rank(4)[3]
in_channels = input.get_shape().with_rank(4)[3]
out_channels = pointwise_filter_shape[3]
if rate is None:
rate = [1, 1]
# If any of channel numbers is unknown, then the comparison below returns
# None. See TensorShape.__gt__().
if channel_multiplier * in_channels > out_channels:
raise ValueError("Refusing to perform an overparameterized separable "
"convolution: channel_multiplier * in_channels = "
"%d * %d = %d > %d = out_channels" %
(channel_multiplier, in_channels,
channel_multiplier * in_channels, out_channels))
# The layout of the ops in the graph are expected to be as follows:
# depthwise_conv2d // Conv2D op corresponding to native deptwise conv.
# separable_conv2d // Conv2D op corresponding to the pointwise conv.
def op(input_converted, _, padding):
return nn_ops.depthwise_conv2d_native(
input=input_converted,
filter=depthwise_filter,
strides=strides,
padding=padding,
name="depthwise")
depthwise = nn_ops.with_space_to_batch(
input=input,
filter_shape=array_ops.shape(depthwise_filter),
dilation_rate=rate,
padding=padding,
op=op)
return nn_ops.conv2d(
depthwise, pointwise_filter, [1, 1, 1, 1], padding="VALID", name=name)
# pylint: enable=redefined-builtin,line-too-long
def sufficient_statistics(x, axes, shift=None, keep_dims=False, name=None):
"""Calculate the sufficient statistics for the mean and variance of `x`.
These sufficient statistics are computed using the one pass algorithm on
an input that's optionally shifted. See:
https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Computing_shifted_data
Args:
x: A `Tensor`.
axes: Array of ints. Axes along which to compute mean and variance.
shift: A `Tensor` containing the value by which to shift the data for
numerical stability, or `None` if no shift is to be performed. A shift
close to the true mean provides the most numerically stable results.
keep_dims: produce statistics with the same dimensionality as the input.
name: Name used to scope the operations that compute the sufficient stats.
Returns:
Four `Tensor` objects of the same type as `x`:
* the count (number of elements to average over).
* the (possibly shifted) sum of the elements in the array.
* the (possibly shifted) sum of squares of the elements in the array.
* the shift by which the mean must be corrected or None if `shift` is None.
"""
axes = list(set(axes))
with ops.name_scope(name, "sufficient_statistics", [x, shift]):
x = ops.convert_to_tensor(x, name="x")
x_shape = x.get_shape()
if all(x_shape[d].value is not None for d in axes):
counts = 1
for d in axes:
counts *= x_shape[d].value
counts = constant_op.constant(counts, dtype=x.dtype)
else: # shape needs to be inferred at runtime.
x_dims = array_ops.gather(
math_ops.cast(array_ops.shape(x), x.dtype), axes)
counts = math_ops.reduce_prod(x_dims, name="count")
if shift is not None:
shift = ops.convert_to_tensor(shift, name="shift")
m_ss = math_ops.sub(x, shift)
v_ss = math_ops.squared_difference(x, shift)
else: # no shift.
m_ss = x
v_ss = math_ops.square(x)
m_ss = math_ops.reduce_sum(m_ss, axes, keep_dims=keep_dims, name="mean_ss")
v_ss = math_ops.reduce_sum(v_ss, axes, keep_dims=keep_dims, name="var_ss")
return counts, m_ss, v_ss, shift
def normalize_moments(counts, mean_ss, variance_ss, shift, name=None):
"""Calculate the mean and variance of based on the sufficient statistics.
Args:
counts: A `Tensor` containing a the total count of the data (one value).
mean_ss: A `Tensor` containing the mean sufficient statistics: the (possibly
shifted) sum of the elements to average over.
variance_ss: A `Tensor` containing the variance sufficient statistics: the
(possibly shifted) squared sum of the data to compute the variance over.
shift: A `Tensor` containing the value by which the data is shifted for
numerical stability, or `None` if no shift was performed.
name: Name used to scope the operations that compute the moments.
Returns:
Two `Tensor` objects: `mean` and `variance`.
"""
with ops.name_scope(name, "normalize", [counts, mean_ss, variance_ss, shift]):
divisor = math_ops.reciprocal(counts, name="divisor")
if shift is not None:
shifted_mean = math_ops.mul(mean_ss, divisor, name="shifted_mean")
mean = math_ops.add(shifted_mean, shift, name="mean")
else: # no shift.
shifted_mean = math_ops.mul(mean_ss, divisor, name="mean")
mean = shifted_mean
variance = math_ops.sub(math_ops.mul(variance_ss, divisor),
math_ops.square(shifted_mean),
name="variance")
return (mean, variance)
def moments(x, axes, shift=None, name=None, keep_dims=False):
"""Calculate the mean and variance of `x`.
The mean and variance are calculated by aggregating the contents of `x`
across `axes`. If `x` is 1-D and `axes = [0]` this is just the mean
and variance of a vector.
When using these moments for batch normalization (see
`tf.nn.batch_normalization`):
* for so-called "global normalization", used with convolutional filters with
shape `[batch, height, width, depth]`, pass `axes=[0, 1, 2]`.
* for simple batch normalization pass `axes=[0]` (batch only).
Args:
x: A `Tensor`.
axes: Array of ints. Axes along which to compute mean and
variance.
shift: A `Tensor` containing the value by which to shift the data for
numerical stability, or `None` if no shift is to be performed. A shift
close to the true mean provides the most numerically stable results.
name: Name used to scope the operations that compute the moments.
keep_dims: produce moments with the same dimensionality as the input.
Returns:
Two `Tensor` objects: `mean` and `variance`.
"""
with ops.name_scope(name, "moments", [x, axes, shift]):
# The dynamic range of fp16 is too limited to support the collection of
# sufficient statistics. As a workaround we simply perform the operations
# on 32-bit floats before converting the mean and variance back to fp16
y = math_ops.cast(x, dtypes.float32) if x.dtype == dtypes.float16 else x
shift = math_ops.cast(shift, dtypes.float32) if (
shift is not None and x.dtype == dtypes.float16) else shift
counts, m_ss, v_ss, shift = sufficient_statistics(
y, axes, shift=shift, keep_dims=keep_dims, name=name)
with ops.control_dependencies([counts, m_ss, v_ss]):
mean, variance = normalize_moments(counts, m_ss, v_ss, shift, name=name)
if x.dtype == dtypes.float16:
return (math_ops.cast(mean, dtypes.float16),
math_ops.cast(variance, dtypes.float16))
else:
return (mean, variance)
def weighted_moments(x, axes, frequency_weights, name=None, keep_dims=False):
"""Returns the frequency-weighted mean and variance of `x`.
Args:
x: A tensor.
axes: 1-d tensor of int32 values; these are the axes along which
to compute mean and variance.
frequency_weights: A tensor of positive weights which can be
broadcast with x.
name: Name used to scope the operation.
keep_dims: Produce moments with the same dimensionality as the input.
Returns:
Two tensors: `weighted_mean` and `weighted_variance`.
"""
with ops.name_scope(name, "weighted_moments", [x, frequency_weights, axes]):
x = ops.convert_to_tensor(x, name="x")
frequency_weights = ops.convert_to_tensor(
frequency_weights, name="frequency_weights")
# Unlike moments(), this just uses a simpler two-pass method.
# See comment in moments() WRT precision; it applies here too.
needs_cast = x.dtype == dtypes.float16
if needs_cast:
x = math_ops.cast(x, dtypes.float32)
if frequency_weights.dtype != x.dtype:
frequency_weights = math_ops.cast(frequency_weights, x.dtype)
# Note that we use keep_dims=True for our reductions regardless of the arg;
# this is so that the results remain broadcast-compatible with the inputs.
weighted_input_sum = math_ops.reduce_sum(
frequency_weights * x, axes, name="weighted_input_sum", keep_dims=True)
# The shape of the weights isn't necessarily the same as x's
# shape, just broadcast-compatible with it -- so this expression
# performs broadcasting to give a per-item weight, with the same
# shape as (freqency_weights * x). This avoids having to reason
# through all the broadcast logic to compute a correct
# sum_of_weights.
broadcasted_weights = frequency_weights + array_ops.zeros_like(x)
sum_of_weights = math_ops.reduce_sum(
broadcasted_weights, axes, name="sum_of_weights", keep_dims=True)
divisor = math_ops.reciprocal(sum_of_weights, name="inv_weight_sum")
weighted_mean = math_ops.mul(weighted_input_sum, divisor)
# Have the weighted mean; now on to variance:
weighted_distsq = math_ops.reduce_sum(
frequency_weights * math_ops.squared_difference(x, weighted_mean),
axes,
name="weighted_distsq",
keep_dims=True)
weighted_variance = math_ops.mul(weighted_distsq, divisor)
if not keep_dims:
weighted_mean = array_ops.squeeze(weighted_mean, squeeze_dims=axes)
weighted_variance = array_ops.squeeze(
weighted_variance, squeeze_dims=axes)
if needs_cast:
weighted_mean = math_ops.cast(weighted_mean, dtypes.float16)
weighted_variance = math_ops.cast(weighted_variance, dtypes.float16)
return weighted_mean, weighted_variance
def batch_normalization(x,
mean,
variance,
offset,
scale,
variance_epsilon,
name=None):
r"""Batch normalization.
As described in http://arxiv.org/abs/1502.03167.
Normalizes a tensor by `mean` and `variance`, and applies (optionally) a
`scale` \\(\gamma\\) to it, as well as an `offset` \\(\beta\\):
\\(\frac{\gamma(x-\mu)}{\sigma}+\beta\\)
`mean`, `variance`, `offset` and `scale` are all expected to be of one of two
shapes:
* In all generality, they can have the same number of dimensions as the
input `x`, with identical sizes as `x` for the dimensions that are not
normalized over (the 'depth' dimension(s)), and dimension 1 for the
others which are being normalized over.
`mean` and `variance` in this case would typically be the outputs of
`tf.nn.moments(..., keep_dims=True)` during training, or running averages
thereof during inference.
* In the common case where the 'depth' dimension is the last dimension in
the input tensor `x`, they may be one dimensional tensors of the same
size as the 'depth' dimension.
This is the case for example for the common `[batch, depth]` layout of
fully-connected layers, and `[batch, height, width, depth]` for
convolutions.
`mean` and `variance` in this case would typically be the outputs of
`tf.nn.moments(..., keep_dims=False)` during training, or running averages
thereof during inference.
Args:
x: Input `Tensor` of arbitrary dimensionality.
mean: A mean `Tensor`.
variance: A variance `Tensor`.
offset: An offset `Tensor`, often denoted \\(\beta\\) in equations, or
None. If present, will be added to the normalized tensor.
scale: A scale `Tensor`, often denoted \\(\gamma\\) in equations, or
`None`. If present, the scale is applied to the normalized tensor.
variance_epsilon: A small float number to avoid dividing by 0.
name: A name for this operation (optional).
Returns:
the normalized, scaled, offset tensor.
"""
with ops.name_scope(name, "batchnorm", [x, mean, variance, scale, offset]):
inv = math_ops.rsqrt(variance + variance_epsilon)
if scale is not None:
inv *= scale
return x * inv + (offset - mean * inv
if offset is not None else -mean * inv)
def fused_batch_norm(
x,
scale,
offset, # pylint: disable=invalid-name
mean=None,
variance=None,
epsilon=0.001,
data_format="NHWC",
is_training=True,
name=None):
r"""Batch normalization.
As described in http://arxiv.org/abs/1502.03167.
Args:
x: Input `Tensor` of 4 dimensions.
scale: A `Tensor` of 1 dimension for scaling.
offset: A `Tensor` of 1 dimension for bias.
mean: A `Tensor` of 1 dimension for population mean used for inference.
variance: A `Tensor` of 1 dimension for population variance
used for inference.
epsilon: A small float number added to the variance of x.
data_format: The data format for x. Either "NHWC" (default) or "NCHW".
is_training: A bool value to specify if the operation is used for
training or inference.
name: A name for this operation (optional).
Returns:
y: A 4D Tensor for the normalized, scaled, offsetted x.
batch_mean: A 1D Tensor for the mean of x.
batch_var: A 1D Tensor for the variance of x.
Raises:
ValueError: If mean or variance is not None when is_training is True.
"""
x = ops.convert_to_tensor(x, name="input")
scale = ops.convert_to_tensor(scale, name="scale")
offset = ops.convert_to_tensor(offset, name="offset")
if is_training:
if (mean is not None) or (variance is not None):
raise ValueError("Both 'mean' and 'variance' must be None "
"if is_training is True.")
if mean is None:
mean = constant_op.constant([])
if variance is None:
variance = constant_op.constant([])
# Add 1e-12 to epsilon when epsilon <= 1e-5 to prevent CUDNN exception.
epsilon = epsilon if epsilon > 1e-5 else epsilon + 1e-12
# pylint: disable=protected-access
y, batch_mean, batch_var, _, _ = gen_nn_ops._fused_batch_norm(
x,
scale,
offset,
mean,
variance,
epsilon=epsilon,
data_format=data_format,
is_training=is_training,
name=name)
return y, batch_mean, batch_var
# pylint: enable=protected-access
def batch_norm_with_global_normalization(t,
m,
v,
beta,
gamma,
variance_epsilon,
scale_after_normalization,
name=None):
"""Batch normalization.
This op is deprecated. See `tf.nn.batch_normalization`.
Args:
t: A 4D input Tensor.
m: A 1D mean Tensor with size matching the last dimension of t.
This is the first output from tf.nn.moments,
or a saved moving average thereof.
v: A 1D variance Tensor with size matching the last dimension of t.
This is the second output from tf.nn.moments,
or a saved moving average thereof.
beta: A 1D beta Tensor with size matching the last dimension of t.
An offset to be added to the normalized tensor.
gamma: A 1D gamma Tensor with size matching the last dimension of t.
If "scale_after_normalization" is true, this tensor will be multiplied
with the normalized tensor.
variance_epsilon: A small float number to avoid dividing by 0.
scale_after_normalization: A bool indicating whether the resulted tensor
needs to be multiplied with gamma.
name: A name for this operation (optional).
Returns:
A batch-normalized `t`.
"""
return batch_normalization(t, m, v, beta, gamma if scale_after_normalization
else None, variance_epsilon, name)
def _sum_rows(x):
"""Returns a vector summing up each row of the matrix x."""
# _sum_rows(x) is equivalent to math_ops.reduce_sum(x, 1) when x is
# a matrix. The gradient of _sum_rows(x) is more efficient than
# reduce_sum(x, 1)'s gradient in today's implementation. Therefore,
# we use _sum_rows(x) in the nce_loss() computation since the loss
# is mostly used for training.
cols = array_ops.shape(x)[1]
ones_shape = array_ops.pack([cols, 1])
ones = array_ops.ones(ones_shape, x.dtype)
return array_ops.reshape(math_ops.matmul(x, ones), [-1])
def _compute_sampled_logits(weights,
biases,
labels,
inputs,
num_sampled,
num_classes,
num_true=1,
sampled_values=None,
subtract_log_q=True,
remove_accidental_hits=False,
partition_strategy="mod",
name=None):
"""Helper function for nce_loss and sampled_softmax_loss functions.
Computes sampled output training logits and labels suitable for implementing
e.g. noise-contrastive estimation (see nce_loss) or sampled softmax (see
sampled_softmax_loss).
Note: In the case where num_true > 1, we assign to each target class
the target probability 1 / num_true so that the target probabilities
sum to 1 per-example.
Args:
weights: A `Tensor` of shape `[num_classes, dim]`, or a list of `Tensor`
objects whose concatenation along dimension 0 has shape
`[num_classes, dim]`. The (possibly-partitioned) class embeddings.
biases: A `Tensor` of shape `[num_classes]`. The class biases.
labels: A `Tensor` of type `int64` and shape `[batch_size,
num_true]`. The target classes. Note that this format differs from
the `labels` argument of `nn.softmax_cross_entropy_with_logits`.
inputs: A `Tensor` of shape `[batch_size, dim]`. The forward
activations of the input network.
num_sampled: An `int`. The number of classes to randomly sample per batch.
num_classes: An `int`. The number of possible classes.
num_true: An `int`. The number of target classes per training example.
sampled_values: a tuple of (`sampled_candidates`, `true_expected_count`,
`sampled_expected_count`) returned by a `*_candidate_sampler` function.
(if None, we default to `log_uniform_candidate_sampler`)
subtract_log_q: A `bool`. whether to subtract the log expected count of
the labels in the sample to get the logits of the true labels.
Default is True. Turn off for Negative Sampling.
remove_accidental_hits: A `bool`. whether to remove "accidental hits"
where a sampled class equals one of the target classes. Default is
False.
partition_strategy: A string specifying the partitioning strategy, relevant
if `len(weights) > 1`. Currently `"div"` and `"mod"` are supported.
Default is `"mod"`. See `tf.nn.embedding_lookup` for more details.
name: A name for the operation (optional).
Returns:
out_logits, out_labels: `Tensor` objects each with shape
`[batch_size, num_true + num_sampled]`, for passing to either
`nn.sigmoid_cross_entropy_with_logits` (NCE) or
`nn.softmax_cross_entropy_with_logits` (sampled softmax).
"""
if not isinstance(weights, list):
weights = [weights]
with ops.name_scope(name, "compute_sampled_logits",
weights + [biases, inputs, labels]):
if labels.dtype != dtypes.int64:
labels = math_ops.cast(labels, dtypes.int64)
labels_flat = array_ops.reshape(labels, [-1])
# Sample the negative labels.
# sampled shape: [num_sampled] tensor
# true_expected_count shape = [batch_size, 1] tensor
# sampled_expected_count shape = [num_sampled] tensor
if sampled_values is None:
sampled_values = candidate_sampling_ops.log_uniform_candidate_sampler(
true_classes=labels,
num_true=num_true,
num_sampled=num_sampled,
unique=True,
range_max=num_classes)
# NOTE: pylint cannot tell that 'sampled_values' is a sequence
# pylint: disable=unpacking-non-sequence
sampled, true_expected_count, sampled_expected_count = sampled_values
# pylint: enable=unpacking-non-sequence
# labels_flat is a [batch_size * num_true] tensor
# sampled is a [num_sampled] int tensor
all_ids = array_ops.concat_v2([labels_flat, sampled], 0)
# weights shape is [num_classes, dim]
all_w = embedding_ops.embedding_lookup(
weights, all_ids, partition_strategy=partition_strategy)
all_b = embedding_ops.embedding_lookup(biases, all_ids)
# true_w shape is [batch_size * num_true, dim]
# true_b is a [batch_size * num_true] tensor
true_w = array_ops.slice(
all_w, [0, 0], array_ops.pack([array_ops.shape(labels_flat)[0], -1]))
true_b = array_ops.slice(all_b, [0], array_ops.shape(labels_flat))
# inputs shape is [batch_size, dim]
# true_w shape is [batch_size * num_true, dim]
# row_wise_dots is [batch_size, num_true, dim]
dim = array_ops.shape(true_w)[1:2]
new_true_w_shape = array_ops.concat_v2([[-1, num_true], dim], 0)
row_wise_dots = math_ops.mul(
array_ops.expand_dims(inputs, 1),
array_ops.reshape(true_w, new_true_w_shape))
# We want the row-wise dot plus biases which yields a
# [batch_size, num_true] tensor of true_logits.
dots_as_matrix = array_ops.reshape(row_wise_dots,
array_ops.concat_v2([[-1], dim], 0))
true_logits = array_ops.reshape(_sum_rows(dots_as_matrix), [-1, num_true])
true_b = array_ops.reshape(true_b, [-1, num_true])
true_logits += true_b
# Lookup weights and biases for sampled labels.
# sampled_w shape is [num_sampled, dim]
# sampled_b is a [num_sampled] float tensor
sampled_w = array_ops.slice(
all_w, array_ops.pack([array_ops.shape(labels_flat)[0], 0]), [-1, -1])
sampled_b = array_ops.slice(all_b, array_ops.shape(labels_flat), [-1])
# inputs has shape [batch_size, dim]
# sampled_w has shape [num_sampled, dim]
# sampled_b has shape [num_sampled]
# Apply X*W'+B, which yields [batch_size, num_sampled]
sampled_logits = math_ops.matmul(
inputs, sampled_w, transpose_b=True) + sampled_b
if remove_accidental_hits:
acc_hits = candidate_sampling_ops.compute_accidental_hits(
labels, sampled, num_true=num_true)
acc_indices, acc_ids, acc_weights = acc_hits
# This is how SparseToDense expects the indices.
acc_indices_2d = array_ops.reshape(acc_indices, [-1, 1])
acc_ids_2d_int32 = array_ops.reshape(
math_ops.cast(acc_ids, dtypes.int32), [-1, 1])
sparse_indices = array_ops.concat_v2([acc_indices_2d, acc_ids_2d_int32],
1, "sparse_indices")
# Create sampled_logits_shape = [batch_size, num_sampled]
sampled_logits_shape = array_ops.concat_v2(
[array_ops.shape(labels)[:1], array_ops.expand_dims(num_sampled, 0)],
0)
if sampled_logits.dtype != acc_weights.dtype:
acc_weights = math_ops.cast(acc_weights, sampled_logits.dtype)
sampled_logits += sparse_ops.sparse_to_dense(
sparse_indices,
sampled_logits_shape,
acc_weights,
default_value=0.0,
validate_indices=False)
if subtract_log_q:
# Subtract log of Q(l), prior probability that l appears in sampled.
true_logits -= math_ops.log(true_expected_count)
sampled_logits -= math_ops.log(sampled_expected_count)
# Construct output logits and labels. The true labels/logits start at col 0.
out_logits = array_ops.concat_v2([true_logits, sampled_logits], 1)
# true_logits is a float tensor, ones_like(true_logits) is a float tensor
# of ones. We then divide by num_true to ensure the per-example labels sum
# to 1.0, i.e. form a proper probability distribution.
out_labels = array_ops.concat_v2([
array_ops.ones_like(true_logits) / num_true,
array_ops.zeros_like(sampled_logits)
], 1)
return out_logits, out_labels
def nce_loss(weights,
biases,
labels,
inputs,
num_sampled,
num_classes,
num_true=1,
sampled_values=None,
remove_accidental_hits=False,
partition_strategy="mod",
name="nce_loss"):
"""Computes and returns the noise-contrastive estimation training loss.
See [Noise-contrastive estimation: A new estimation principle for
unnormalized statistical
models](http://www.jmlr.org/proceedings/papers/v9/gutmann10a/gutmann10a.pdf).
Also see our [Candidate Sampling Algorithms
Reference](../../extras/candidate_sampling.pdf)
Note: By default this uses a log-uniform (Zipfian) distribution for sampling,
so your labels must be sorted in order of decreasing frequency to achieve
good results. For more details, see
[log_uniform_candidate_sampler](#log_uniform_candidate_sampler).
Note: In the case where `num_true` > 1, we assign to each target class
the target probability 1 / `num_true` so that the target probabilities
sum to 1 per-example.
Note: It would be useful to allow a variable number of target classes per
example. We hope to provide this functionality in a future release.
For now, if you have a variable number of target classes, you can pad them
out to a constant number by either repeating them or by padding
with an otherwise unused class.
Args:
weights: A `Tensor` of shape `[num_classes, dim]`, or a list of `Tensor`
objects whose concatenation along dimension 0 has shape
[num_classes, dim]. The (possibly-partitioned) class embeddings.
biases: A `Tensor` of shape `[num_classes]`. The class biases.
labels: A `Tensor` of type `int64` and shape `[batch_size,
num_true]`. The target classes.
inputs: A `Tensor` of shape `[batch_size, dim]`. The forward
activations of the input network.
num_sampled: An `int`. The number of classes to randomly sample per batch.
num_classes: An `int`. The number of possible classes.
num_true: An `int`. The number of target classes per training example.
sampled_values: a tuple of (`sampled_candidates`, `true_expected_count`,
`sampled_expected_count`) returned by a `*_candidate_sampler` function.
(if None, we default to `log_uniform_candidate_sampler`)
remove_accidental_hits: A `bool`. Whether to remove "accidental hits"
where a sampled class equals one of the target classes. If set to
`True`, this is a "Sampled Logistic" loss instead of NCE, and we are
learning to generate log-odds instead of log probabilities. See
our [Candidate Sampling Algorithms Reference]
(../../extras/candidate_sampling.pdf).
Default is False.
partition_strategy: A string specifying the partitioning strategy, relevant
if `len(weights) > 1`. Currently `"div"` and `"mod"` are supported.
Default is `"mod"`. See `tf.nn.embedding_lookup` for more details.
name: A name for the operation (optional).
Returns:
A `batch_size` 1-D tensor of per-example NCE losses.
"""
logits, labels = _compute_sampled_logits(
weights=weights,
biases=biases,
labels=labels,
inputs=inputs,
num_sampled=num_sampled,
num_classes=num_classes,
num_true=num_true,
sampled_values=sampled_values,
subtract_log_q=True,
remove_accidental_hits=remove_accidental_hits,
partition_strategy=partition_strategy,
name=name)
sampled_losses = sigmoid_cross_entropy_with_logits(
logits, labels, name="sampled_losses")
# sampled_losses is batch_size x {true_loss, sampled_losses...}
# We sum out true and sampled losses.
return _sum_rows(sampled_losses)
def sampled_softmax_loss(weights,
biases,
inputs,
labels,
num_sampled,
num_classes,
num_true=1,
sampled_values=None,
remove_accidental_hits=True,
partition_strategy="mod",
name="sampled_softmax_loss"):
"""Computes and returns the sampled softmax training loss.
This is a faster way to train a softmax classifier over a huge number of
classes.
This operation is for training only. It is generally an underestimate of
the full softmax loss.
At inference time, you can compute full softmax probabilities with the
expression `tf.nn.softmax(tf.matmul(inputs, tf.transpose(weights)) + biases)`.
See our [Candidate Sampling Algorithms Reference]
(../../extras/candidate_sampling.pdf)
Also see Section 3 of [Jean et al., 2014](http://arxiv.org/abs/1412.2007)
([pdf](http://arxiv.org/pdf/1412.2007.pdf)) for the math.
Args:
weights: A `Tensor` of shape `[num_classes, dim]`, or a list of `Tensor`
objects whose concatenation along dimension 0 has shape
[num_classes, dim]. The (possibly-sharded) class embeddings.
biases: A `Tensor` of shape `[num_classes]`. The class biases.
inputs: A `Tensor` of shape `[batch_size, dim]`. The forward
activations of the input network.
labels: A `Tensor` of type `int64` and shape `[batch_size,
num_true]`. The target classes. Note that this format differs from
the `labels` argument of `nn.softmax_cross_entropy_with_logits`.
num_sampled: An `int`. The number of classes to randomly sample per batch.
num_classes: An `int`. The number of possible classes.
num_true: An `int`. The number of target classes per training example.
sampled_values: a tuple of (`sampled_candidates`, `true_expected_count`,
`sampled_expected_count`) returned by a `*_candidate_sampler` function.
(if None, we default to `log_uniform_candidate_sampler`)
remove_accidental_hits: A `bool`. whether to remove "accidental hits"
where a sampled class equals one of the target classes. Default is
True.
partition_strategy: A string specifying the partitioning strategy, relevant
if `len(weights) > 1`. Currently `"div"` and `"mod"` are supported.
Default is `"mod"`. See `tf.nn.embedding_lookup` for more details.
name: A name for the operation (optional).
Returns:
A `batch_size` 1-D tensor of per-example sampled softmax losses.
"""
logits, labels = _compute_sampled_logits(
weights=weights,
biases=biases,
labels=labels,
inputs=inputs,
num_sampled=num_sampled,
num_classes=num_classes,
num_true=num_true,
sampled_values=sampled_values,
subtract_log_q=True,
remove_accidental_hits=remove_accidental_hits,
partition_strategy=partition_strategy,
name=name)
sampled_losses = nn_ops.softmax_cross_entropy_with_logits(logits, labels)
# sampled_losses is a [batch_size] tensor.
return sampled_losses
|
/**
* Configure your Gatsby site with this file.
*
* See: https://www.gatsbyjs.org/docs/gatsby-config/
*/
module.exports = {
/* Your site config here */
siteMetadata: require("./site-meta-data.json"),
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
name: `markdown-pages`,
path: `${__dirname}/_data`,
},
},
{
resolve: `gatsby-transformer-remark`,
options: {
plugins: [{
resolve: `gatsby-remark-prismjs`,
options: {
classPrefix: "language-",
inlineCodeMarker: null,
aliases: {},
showLineNumbers: false,
noInlineHighlight: false,
},
},
{
resolve: 'gatsby-remark-emojis',
}],
},
},
{
resolve: `gatsby-plugin-google-analytics`,
options: {
// The property ID; the tracking code won't be generated without it. replace with yours
trackingId: "UA-164743872-1",
head: true,
}
},
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `Dan Collins - Developer`,
short_name: `DanCollins`,
start_url: `/`,
background_color: `#fff`,
theme_color: `#381696`,
display: `standalone`,
icon: "src/images/icon.png",
},
},
`gatsby-plugin-sass`,
`gatsby-plugin-react-helmet`,
`gatsby-plugin-netlify-cms`,
'gatsby-plugin-dark-mode',
// siteURL is a must for sitemap generation
`gatsby-plugin-sitemap`,
`gatsby-plugin-offline`,
],
}
|
import {$, apply, isString, mergeOptions, toNode} from 'uikit-util';
export default function (UIkit) {
const DATA = UIkit.data;
UIkit.use = function (plugin) {
if (plugin.installed) {
return;
}
plugin.call(null, this);
plugin.installed = true;
return this;
};
UIkit.mixin = function (mixin, component) {
component = (isString(component) ? UIkit.component(component) : component) || this;
component.options = mergeOptions(component.options, mixin);
};
UIkit.extend = function (options) {
options = options || {};
const Super = this;
const Sub = function UIkitComponent (options) {
this._init(options);
};
Sub.prototype = Object.create(Super.prototype);
Sub.prototype.constructor = Sub;
Sub.options = mergeOptions(Super.options, options);
Sub.super = Super;
Sub.extend = Super.extend;
return Sub;
};
UIkit.update = function (element, e) {
element = element ? toNode(element) : document.body;
path(element, element => update(element[DATA], e));
apply(element, element => update(element[DATA], e));
};
let container;
Object.defineProperty(UIkit, 'container', {
get() {
return container || document.body;
},
set(element) {
container = $(element);
}
});
function update(data, e) {
if (!data) {
return;
}
for (const name in data) {
if (data[name]._connected) {
data[name]._callUpdate(e);
}
}
}
function path(node, fn) {
if (node && node !== document.body && node.parentNode) {
path(node.parentNode, fn);
fn(node.parentNode);
}
}
}
|
import React from 'react';
import { storiesOf } from '@storybook/react';
import { withKnobs, text } from '@storybook/addon-knobs';
import Theme from '@quarkly/theme';
import getKnobs from './knobs';
import Wrapper from '../../modules/wrapper';
import U from './index';
const stories = storiesOf('Wysiwyg/Underline', module);
stories.addDecorator(withKnobs);
stories.add('u', () => (
<Theme>
<Wrapper>
<U {...getKnobs()}>{text('Text', 'Underline text here')}</U>
</Wrapper>
</Theme>
));
|
function do_submit(flg, kind, product_id)
{
if( flg == 1 ) {
if( kind == 'add' ) {
$('#frm_product_confirm').prop('action', SITE_URL + 'admin/product/add');
}
else {
$('#frm_product_confirm').prop('action', SITE_URL + 'admin/product/modify/' + product_id);
}
}
else {
$('#frm_product_confirm').prop('action', SITE_URL + 'admin/product/complete');
}
$('#frm_product_confirm').submit();
}
|
from __future__ import absolute_import
from __future__ import print_function
import sys
import os
# the next line can be removed after installation
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))))
from veriloggen import *
import veriloggen.thread as vthread
import veriloggen.types.axi as axi
def mkLed(memory_datawidth=128):
m = Module('blinkled')
clk = m.Input('CLK')
rst = m.Input('RST')
datawidth = 32
addrwidth = 10
myaxi = vthread.AXIM(m, 'myaxi', clk, rst, memory_datawidth)
myram0 = vthread.RAM(m, 'myram0', clk, rst, datawidth, addrwidth)
myram1 = vthread.RAM(m, 'myram1', clk, rst, datawidth, addrwidth)
all_ok = m.TmpReg(initval=0, prefix='all_ok')
wdata = m.TmpReg(width=datawidth, initval=0, prefix='wdata')
rdata = m.TmpReg(width=datawidth, initval=0, prefix='rdata')
rexpected = m.TmpReg(width=datawidth, initval=0, prefix='rexpected')
def blink(size):
all_ok.value = True
for i in range(4):
print('# iter %d start' % i)
# Test for 4KB boundary check
offset = i * 1024 * 16 + (myaxi.boundary_size - (memory_datawidth // 8) * 3)
body(size, offset)
print('# iter %d end' % i)
if all_ok:
print('# verify: PASSED')
else:
print('# verify: FAILED')
vthread.finish()
def body(size, offset):
# write
for i in range(size):
wdata.value = i + 0x1000
myram0.write(i, wdata)
laddr = 0
gaddr = offset
myaxi.dma_write(myram0, laddr, gaddr, size)
print('dma_write: [%d] -> [%d]' % (laddr, gaddr))
# write
for i in range(size):
wdata.value = i + 0x4000
myram1.write(i, wdata)
laddr = 0
gaddr = (size + size) * 4 + offset
myaxi.dma_write(myram1, laddr, gaddr, size)
print('dma_write: [%d] -> [%d]' % (laddr, gaddr))
# read
laddr = 0
gaddr = offset
myaxi.dma_read(myram1, laddr, gaddr, size)
print('dma_read: [%d] <- [%d]' % (laddr, gaddr))
for i in range(size):
rdata.value = myram1.read(i)
rexpected.value = i + 0x1000
if vthread.verilog.NotEql(rdata, rexpected):
print('rdata[%d] = %d (expected %d)' % (i, rdata, rexpected))
all_ok.value = False
# read
laddr = 0
gaddr = (size + size) * 4 + offset
myaxi.dma_read(myram0, laddr, gaddr, size)
print('dma_read: [%d] <- [%d]' % (laddr, gaddr))
for i in range(size):
rdata.value = myram0.read(i)
rexpected.value = i + 0x4000
if vthread.verilog.NotEql(rdata, rexpected):
print('rdata[%d] = %d (expected %d)' % (i, rdata, rexpected))
all_ok.value = False
th = vthread.Thread(m, 'th_blink', clk, rst, blink)
fsm = th.start(17)
return m
def mkTest(memimg_name=None, memory_datawidth=128):
m = Module('test')
# target instance
led = mkLed(memory_datawidth)
# copy paras and ports
params = m.copy_params(led)
ports = m.copy_sim_ports(led)
clk = ports['CLK']
rst = ports['RST']
memory = axi.AxiMemoryModel(m, 'memory', clk, rst, memory_datawidth,
memimg_name=memimg_name)
memory.connect(ports, 'myaxi')
uut = m.Instance(led, 'uut',
params=m.connect_params(led),
ports=m.connect_ports(led))
# simulation.setup_waveform(m, uut)
simulation.setup_clock(m, clk, hperiod=5)
init = simulation.setup_reset(m, rst, m.make_reset(), period=100)
init.add(
Delay(1000000),
Systask('finish'),
)
return m
def run(filename='tmp.v', simtype='iverilog', outputfile=None):
if outputfile is None:
outputfile = os.path.splitext(os.path.basename(__file__))[0] + '.out'
memimg_name = 'memimg_' + outputfile
test = mkTest(memimg_name=memimg_name)
if filename is not None:
test.to_verilog(filename)
sim = simulation.Simulator(test, sim=simtype)
rslt = sim.run(outputfile=outputfile)
lines = rslt.splitlines()
if simtype == 'verilator' and lines[-1].startswith('-'):
rslt = '\n'.join(lines[:-1])
return rslt
if __name__ == '__main__':
rslt = run(filename='tmp.v')
print(rslt)
|
import * as React from "react"
import { Container, Jumbotron, Carousel, Col, Row, Card } from "react-bootstrap"
import { useEffect, useState } from "react"
import { GatsbyImage } from "gatsby-plugin-image"
import Layout from "../../components/Layout/Layout.js"
import Seo from "../../components/seo"
import { graphql } from "gatsby"
import dataCollection1 from "../../images/data collection/picture1.png"
import dataCollection2 from "../../images/data collection/picture2.png"
const DataCollection = ({
data: {
page: {
name,
cover,
description,
childMarkdownRemark: { html },
},
chartData,
lineData,
},
}) => {
return (
<Layout>
{/* <Seo title={pageTitle} /> */}
{cover && (
<GatsbyImage
image={cover.image.childImageSharp.gatsbyImageData}
alt={cover.alt}
title={cover.title}
style={{
height: `500px`,
display: `flex`,
justifyContent: `center`,
marginBottom: `15px`,
}}
imgStyle={{ objectPosition: "0px" }}
/>
)}
<Jumbotron style={{ backgroundColor: "#F2F4F8", padding: `0` }}>
<h1
style={{
justifyContent: "center",
height: "100px",
display: "flex",
alignItems: "center",
}}
>
Data Collection
</h1>
</Jumbotron>
<Container>
<div dangerouslySetInnerHTML={{ __html: html }} />
</Container>
<Container>
<Row>
<Col xs={5}>
<Card className="dataCollectionCard">
<Card.Img
variant="top"
src={dataCollection1}
width="200px"
height="600px"
/>
<Card.Body>
<Card.Text>
The Matsumoto Ballet Company from Japan: National Theatre, 2
Sep 1977, 8pm. (Source: National Theatre Trust Collection,
courtesy of National Archives of Singapore)
</Card.Text>
</Card.Body>
</Card>
</Col>
<Col xs={5}>
<Card className="dataCollectionCard">
<Card.Img
variant="top"
src={dataCollection2}
width="200px"
height="600px"
/>
<Card.Body>
<Card.Text>
Nihon Buyo: Lee Foundation Theatre, Nanyang Academy of Fine
Arts, 4 & 5 November 2010, 7pm - 8.30pm (Source:{" "}
<a href="https://www.sg.emb-japan.go.jp/JCC/event_BUYO_04112010.html">
Japan Creative Centre
</a>
)
</Card.Text>
</Card.Body>
</Card>
</Col>
</Row>
</Container>
</Layout>
)
}
export default DataCollection
export const data = graphql`
query DataCollection {
page: googleDocs(slug: { eq: "/about-this-project/data-collection" }) {
name
description
cover {
alt
title
image {
childImageSharp {
gatsbyImageData(placeholder: BLURRED, formats: [AUTO, WEBP, AVIF])
}
}
}
childMarkdownRemark {
html
}
}
}
`
|
import passport from 'passport';
module.exports = passport.authenticate('jwt', {
session: false
});
|
'''
v.0.0.9
LDSReplicate - LDSDataStore_Test
Copyright 2011 Crown copyright (c)
Land Information New Zealand and the New Zealand Government.
All rights reserved
This program is released under the terms of the new BSD license. See the
LICENSE file for more information.
Tests for command line URLs
Created on 03/10/2013
@author: jramsay
'''
import unittest
import os
import sys
import time
import subprocess
sys.path.append('..')
from lds.LDSUtilities import LDSUtilities
from lds.LDSDataStore import LDSDataStore
testlog = LDSUtilities.setupLogging(ff=2)
class Test_1_LDSDataStore(unittest.TestCase):
UCONF = 'TEST'
LGVAL = 'v:x100'
DESTNAME = 'PostgreSQL'
def setUp(self):
testlog.debug('LDSDataStore_Test.setUp')
self.ldsdatastore = LDSDataStore(None,self.UCONF)
def tearDown(self):
testlog.debug('LDSDataStore_Test.tearDown')
def test_1_getLayerOptions(self):
cfl = ['CPL_DEBUG=OFF', 'GDAL_HTTP_USERAGENT=LDSReplicate/0.0.9.0', 'OGR_WFS_PAGING_ALLOWED=OFF', 'OGR_WFS_PAGE_SIZE=10000', 'OGR_WFS_USE_STREAMING=NO', 'OGR_WFS_LOAD_MULTIPLE_LAYER_DEFN=OFF', 'OGR_WFS_BASE_START_INDEX=0']
self.assertEqual(self.ldsdatastore.getConfigOptions()[1],cfl[1],'config options 1')
self.assertEqual(self.ldsdatastore.getConfigOptions()[2],cfl[2],'config options 2')
self.assertEqual(self.ldsdatastore.getConfigOptions()[3],cfl[3],'config options 3')
self.assertEqual(self.ldsdatastore.getConfigOptions()[4],cfl[4],'config options 4')
self.assertEqual(self.ldsdatastore.getConfigOptions()[5],cfl[5],'config options 5')
def test_2_getCapabilities(self):
self.assertEqual(self.ldsdatastore.getCapabilities()[74:77],'WFS','uri service')
self.assertEqual(self.ldsdatastore.getCapabilities()[86:91],'1.1.0','uri version')
self.assertEqual(self.ldsdatastore.getCapabilities()[100:115],'GetCapabilities','uri getcapabilities')
def test_3_fetchLayerInfo(self):
rsl = [('v:x845', '12 Mile Territorial Sea Limit Basepoints', ['New Zealand', 'Hydrographic & Maritime', 'Maritime Boundaries']), ('v:x846', '12 Mile Territorial Sea Outer Limit', ['New Zealand', 'Hydrographic & Maritime', 'Maritime Boundaries'])]
gcu = self.ldsdatastore.getCapabilities()
res = self.ldsdatastore.fetchLayerInfo(gcu)
self.assertEqual(res[0][0],rsl[0][0],'res 00')
self.assertEqual(res[1][1],rsl[1][1],'res 11')
self.assertEqual(res[0][2][0],rsl[0][2][0],'res 020')
self.assertEqual(res[1][2][1],rsl[1][2][1],'res 121')
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testLDSRead']
unittest.main()
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require("react");
var _react2 = _interopRequireDefault(_react);
var _propTypes = require("prop-types");
var _propTypes2 = _interopRequireDefault(_propTypes);
var _classnames = require("classnames");
var _classnames2 = _interopRequireDefault(_classnames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
// import styles from "./styles"
var cleanups = {
// some useless stuff for us
// that svgo doesn't remove
title: /<title>.*<\/title>/gi,
desc: /<desc>.*<\/desc>/gi,
comment: /<!--.*-->/gi,
defs: /<defs>.*<\/defs>/gi,
// remove hardcoded dimensions
width: / +width="\d+(\.\d+)?(px)?"/gi,
height: / +height="\d+(\.\d+)?(px)?"/gi,
// remove fill
fill: / +fill=\"(none|#[0-9a-f]+)\"/gi,
// Sketch.app shit
sketchMSShapeGroup: / +sketch:type=\"MSShapeGroup\"/gi,
sketchMSPage: / +sketch:type=\"MSPage\"/gi,
sketchMSLayerGroup: / +sketch:type=\"MSLayerGroup\"/gi
// @styled(styles)
};
var SVGInline = function (_Component) {
_inherits(SVGInline, _Component);
function SVGInline() {
_classCallCheck(this, SVGInline);
return _possibleConstructorReturn(this, (SVGInline.__proto__ || Object.getPrototypeOf(SVGInline)).apply(this, arguments));
}
_createClass(SVGInline, [{
key: "render",
value: function render() {
var _props = this.props,
className = _props.className,
component = _props.component,
svg = _props.svg,
fill = _props.fill,
stroke = _props.stroke,
strokeSize = _props.strokeSize,
width = _props.width,
accessibilityLabel = _props.accessibilityLabel,
accessibilityDesc = _props.accessibilityDesc,
classSuffix = _props.classSuffix,
cleanupExceptions = _props.cleanupExceptions,
componentProps = _objectWithoutProperties(_props, ["className", "component", "svg", "fill", "stroke", "strokeSize", "width", "accessibilityLabel", "accessibilityDesc", "classSuffix", "cleanupExceptions"]);
var _props2 = this.props,
cleanup = _props2.cleanup,
height = _props2.height;
if (
// simple way to enable entire cleanup
cleanup === true ||
// passing cleanupExceptions enable cleanup as well
cleanup.length === 0 && cleanupExceptions.length > 0) {
cleanup = Object.keys(cleanups);
}
cleanup = cleanup.filter(function (key) {
return !(cleanupExceptions.indexOf(key) > -1);
});
if (width && height === undefined) {
height = width;
}
// remove useless props for wrapper
delete componentProps.cleanup;
delete componentProps.height;
var classes = (0, _classnames2.default)(_defineProperty({
"SVGInline": true,
"SVGInline--cleaned": cleanup.length
}, className, className));
var svgClasses = classes.split(" ").join(classSuffix + " ") + classSuffix;
var svgStr = SVGInline.cleanupSvg(svg, cleanup).replace(/<svg/, "<svg class=\"" + svgClasses + "\"" + (fill ? " fill=\"" + fill + "\"" : "") + (stroke ? " stroke=\"" + stroke + "\"" : "") + (strokeSize ? " stroke-width=\"" + strokeSize + "\"" : "") + "stroke-linecap=\"square\"" + (width || height ? " style=\"" + (width ? "width: " + width + ";" : "") + (height ? "height: " + height + ";" : "") + "\"" : ""));
var match = void 0;
if (accessibilityDesc) {
match = /<svg.*?>/.exec(svgStr);
var pos = match.index + match[0].length;
svgStr = svgStr.substr(0, pos) + ("<desc>" + accessibilityDesc + "</desc>") + svgStr.substr(pos);
}
if (accessibilityLabel) {
match = match || /<svg.*?>/.exec(svgStr);
var _pos = match.index + match[0].length - 1;
var id = "SVGInline-" + SVGInline.idCount++ + "-title";
svgStr = svgStr.substr(0, _pos) + (" role=\"img\" aria-labelledby=\"" + id + "\"") + svgStr.substr(_pos, 1) + ("<title id=\"" + id + "\">" + accessibilityLabel + "</title>") + svgStr.substr(_pos + 1);
}
return _react2.default.createElement(component, _extends({}, componentProps, { // take most props
className: classes,
dangerouslySetInnerHTML: {
__html: svgStr
}
}));
}
}]);
return SVGInline;
}(_react.Component);
SVGInline.propTypes = {
className: _propTypes2.default.string,
classSuffix: _propTypes2.default.string,
component: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.func]),
svg: _propTypes2.default.string.isRequired,
fill: _propTypes2.default.string,
stroke: _propTypes2.default.string,
strokeSize: _propTypes2.default.number,
cleanup: _propTypes2.default.oneOfType([_propTypes2.default.bool, _propTypes2.default.array]),
cleanupExceptions: _propTypes2.default.array,
width: _propTypes2.default.string,
height: _propTypes2.default.string,
accessibilityLabel: _propTypes2.default.string,
accessibilityDesc: _propTypes2.default.string
};
SVGInline.defaultProps = {
component: "span",
classSuffix: "-svg",
cleanup: [],
cleanupExceptions: []
};
SVGInline.idCount = 0;
SVGInline.cleanupSvg = function (svg) {
var cleanup = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
return Object.keys(cleanups).filter(function (key) {
return cleanup.indexOf(key) > -1;
}).reduce(function (acc, key) {
return acc.replace(cleanups[key], "");
}, svg).trim();
};
exports.default = SVGInline;
|
const { expect } = require('chai');
const csvParse = require('../../../../src/data/import/parse/csvParser');
const StreamTest = require('streamtest');
describe('CSV Parser', function(){
const importFilePath = __dirname + '/files/data.csv';
it('should parse the file', function(done){
const outStream = StreamTest['v2'].toObjects(function(error, results){
expect(error).to.be.null;
expect(results).to.have.length(2);
expect(results[0]).to.deep.equal({
Location: 'MA',
Year: '2012',
Percent: '.5'
});
expect(results[1]).to.deep.equal({
Location: 'NY',
Year: '2013',
Percent: '.7'
});
done();
});
csvParse(importFilePath)
.pipe(outStream);
});
});
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from './containers/App'
ReactDOM.render(<App /> , document.getElementById('app'));
|
import styled from '@emotion/styled'
import { FormHelperText as ChakraFormHelperText } from '@chakra-ui/core'
export const FormHelperText = styled(ChakraFormHelperText)()
FormHelperText.defaultProps = {
as: 'p',
mt: 1,
mb: 0,
fontSize: 'md',
color: 'black',
fontFamily: 'body',
lineHeight: 1.25,
maxW: '600px',
}
|
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import json
from django.utils.translation import ugettext as _
from desktop.lib.django_util import JsonResponse, render
from desktop.lib.exceptions_renderable import PopupException
from desktop.models import get_cluster_config
from indexer.solr_client import SolrClient
from indexer.fields import FIELD_TYPES, Field
from indexer.file_format import get_file_indexable_format_types
from indexer.management.commands import indexer_setup
from indexer.indexers.morphline_operations import OPERATORS
LOG = logging.getLogger(__name__)
HIVE_PRIMITIVE_TYPES = (
"string", "tinyint", "smallint", "int", "bigint", "boolean", "float", "double", "decimal", "timestamp", "date", "char", "varchar"
)
HIVE_TYPES = HIVE_PRIMITIVE_TYPES + ("array", "map", "struct")
def collections(request, is_redirect=False):
if not request.user.has_hue_permission(action="access", app='indexer'):
raise PopupException(_('Missing permission.'), error_code=403)
return render('collections.mako', request, {
'is_embeddable': request.GET.get('is_embeddable', False),
})
def indexes(request, index=''):
if not request.user.has_hue_permission(action="access", app='indexer'):
raise PopupException(_('Missing permission.'), error_code=403)
return render('indexes.mako', request, {
'is_embeddable': request.GET.get('is_embeddable', False),
'index': index
})
def topics(request, index=''):
if not request.user.has_hue_permission(action="access", app='search'):
raise PopupException(_('Missing permission.'), error_code=403)
return render('topics.mako', request, {
'is_embeddable': request.GET.get('is_embeddable', False),
'index': index
})
def indexer(request):
if not request.user.has_hue_permission(action="access", app='indexer'):
raise PopupException(_('Missing permission.'), error_code=403)
searcher = SolrClient(request.user)
indexes = searcher.get_indexes()
for index in indexes:
index['isSelected'] = False
return render('indexer.mako', request, {
'is_embeddable': request.GET.get('is_embeddable', False),
'indexes_json': json.dumps(indexes),
'fields_json': json.dumps([field.name for field in FIELD_TYPES]),
'operators_json': json.dumps([operator.to_dict() for operator in OPERATORS]),
'file_types_json': json.dumps([format_.format_info() for format_ in get_file_indexable_format_types()]),
'default_field_type': json.dumps(Field().to_dict())
})
def importer(request):
prefill = {
'source_type': '',
'target_type': '',
'target_path': ''
}
return _importer(request, prefill)
def importer_prefill(request, source_type, target_type, target_path=None):
prefill = {
'source_type': source_type,
'target_type': target_type,
'target_path': target_path or ''
}
return _importer(request, prefill)
def _importer(request, prefill):
cluster_config = get_cluster_config(request.user)
source_type = request.GET.get('sourceType') or cluster_config['default_sql_interpreter']
return render('importer.mako', request, {
'is_embeddable': request.GET.get('is_embeddable', False),
'fields_json': json.dumps({'solr': [field.name for field in FIELD_TYPES], 'hive': HIVE_TYPES, 'hivePrimitive': HIVE_PRIMITIVE_TYPES}),
'operators_json': json.dumps([operator.to_dict() for operator in OPERATORS]),
'file_types_json': json.dumps([format_.format_info() for format_ in get_file_indexable_format_types()]),
'default_field_type': json.dumps(Field().to_dict()),
'prefill': json.dumps(prefill),
'source_type': source_type
})
def install_examples(request, is_redirect=False):
result = {'status': -1, 'message': ''}
if request.method != 'POST':
result['message'] = _('A POST request is required.')
else:
try:
data = request.POST.get('data')
indexer_setup.Command().handle(data=data)
result['status'] = 0
except Exception as e:
LOG.exception(e)
result['message'] = str(e)
return JsonResponse(result)
|
import { shell } from 'electron'
import isElectronRenderer from 'is-electron-renderer'
export default function electronBrowserLink(url) {
if (isElectronRenderer) {
shell.openExternal(url)
} else {
window.location.href = url
}
}
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { PanelHeader } from './panel_header';
import { PanelOptionsMenuContainer } from './panel_options_menu_container';
import { PanelMaximizeIcon } from './panel_maximize_icon';
import { PanelMinimizeIcon } from './panel_minimize_icon';
import { DashboardViewMode } from '../../dashboard_view_mode';
import {
maximizePanel,
minimizePanel,
} from '../../actions';
import {
getEmbeddable,
getEmbeddableTitle,
getMaximizedPanelId,
getFullScreenMode,
getViewMode
} from '../../selectors';
const mapStateToProps = ({ dashboard }, { panelId }) => {
const embeddable = getEmbeddable(dashboard, panelId);
return {
title: embeddable ? getEmbeddableTitle(dashboard, panelId) : '',
isExpanded: getMaximizedPanelId(dashboard) === panelId,
isViewOnlyMode: getFullScreenMode(dashboard) || getViewMode(dashboard) === DashboardViewMode.VIEW,
};
};
const mapDispatchToProps = (dispatch, { panelId }) => ({
onMaximizePanel: () => dispatch(maximizePanel(panelId)),
onMinimizePanel: () => dispatch(minimizePanel()),
});
const mergeProps = (stateProps, dispatchProps, ownProps) => {
const { isExpanded, isViewOnlyMode, title } = stateProps;
const { onMaximizePanel, onMinimizePanel } = dispatchProps;
const { panelId, embeddableHandler } = ownProps;
let actions;
if (isViewOnlyMode) {
actions = isExpanded ?
<PanelMinimizeIcon onMinimize={onMinimizePanel} /> :
<PanelMaximizeIcon onMaximize={onMaximizePanel} />;
} else {
actions = (
<PanelOptionsMenuContainer
panelId={panelId}
embeddableHandler={embeddableHandler}
/>
);
}
return {
title,
actions,
};
};
export const PanelHeaderContainer = connect(
mapStateToProps,
mapDispatchToProps,
mergeProps,
)(PanelHeader);
PanelHeaderContainer.propTypes = {
panelId: PropTypes.string.isRequired,
/**
* @type {EmbeddableHandler}
*/
embeddableHandler: PropTypes.shape({
destroy: PropTypes.func.isRequired,
render: PropTypes.func.isRequired,
addDestroyEmeddable: PropTypes.func.isRequired,
}).isRequired,
};
|
export default {
params: {
w: { // width in meters
type: 'number',
defaultValue: 0.6,
optional: false,
min: 0.01 // 1cm
},
h: { // height in meters
type: 'number',
defaultValue: 2.4,
optional: false,
min: 0.01 // 1cm
},
l: { // length in meters
type: 'number',
defaultValue: 1.8,
optional: false,
min: 0.01
},
baseboard: {
type: 'number',
defaultValue: 0.1,
optional: true,
min: 0.01
},
doorWidth: {
type: 'number',
defaultValue: 0.02,
optional: true,
min: 0.01
},
handleLength: {
type: 'number',
defaultValue: 0.02,
optional: true,
min: 0.01
},
handleWidth: {
type: 'number',
defaultValue: 0.02,
optional: true,
min: 0.01
},
handleHeight: {
type: 'number',
defaultValue: 0.3,
optional: true,
min: 0.01
}
},
possibleChildrenTypes: []
}
|
import execa from 'execa'
import { getPaths } from 'src/lib'
export const command = 'lint'
export const desc = 'Lint your files.'
export const builder = {
fix: { type: 'boolean', default: false },
}
export const handler = ({ fix }) => {
execa('yarn eslint', [fix && '--fix', 'web/src', 'api/src'].filter(Boolean), {
cwd: getPaths().base,
shell: true,
stdio: 'inherit',
})
}
|
'use strict'
const Datastore = require('nedb')
const tickers = new Datastore({
filename: 'tickers.db',
autoload: true
})
function find(query) {
return new Promise((resolve, reject) => {
tickers.find(query, (err, docs) => {
if (err) reject(err)
resolve(docs)
})
})
}
function findByPair(pair) {
return find({ pair: pair.toUpperCase() })
}
function parseTicker(upholdTicker, time) {
return {
time,
price: upholdTicker.ask
}
}
function save(ticker) {
return new Promise((resolve, reject) => {
tickers.insert(ticker, (err) => {
if (err) reject(err)
resolve()
})
})
}
function length() {
return new Promise((resolve, reject) => {
tickers.count({}, (err, count) => {
if (err) reject(err)
resolve(count)
})
})
}
module.exports = { find, findByPair, parseTicker, save, length }
|
(function() {
"use strict";
angular
.module('insurance-app.core', ['ui.router','smoothScroll','ui.bootstrap']);
})();
|
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
import * as mutations from './mutations';
import * as actions from './actions';
const store = new Vuex.Store({
state: {
navStatus: false,
scrollPos: {
list: 0,
cream: 0,
issue: 0
},
navList: [{
name: '推荐',
routerName: 'index',
className: 'recommend',
icon: 'iconfont icon-newshot'
}, {
name: '文章',
routerName: 'list',
className: 'list',
icon: 'iconfont icon-list'
}, {
name: '精华',
routerName: 'cream',
className: 'cream',
icon: 'iconfont icon-hot'
}, {
name: 'Q&A',
routerName: 'help',
className: 'help',
icon: 'iconfont icon-question'
}],
activeNav: {},
msgInfo: {
type: 0,
msg: ''
},
confirmInfo: {
type: 0,
msg: '',
callBack: null
},
userInfo: {},
listInfo: {
loaded: false,
page: 0,
list: [],
hasMore: true
},
creamInfo: {
loaded: false,
page: 0,
list: [],
hasMore: true
},
issueInfo: {
loaded: false,
page: 0,
list: [],
hasMore: true
}
},
getters: {
NAV_STAT(state) {
return state.navStatus;
},
SCROLL_POS(state) {
return state.scrollPos;
},
NAV_LIST(state) {
return state.navList;
},
ACTIVE_NAV(state) {
return state.activeNav;
},
MSG_INFO(state) {
return state.msgInfo;
},
CONFIRM_INFO(state) {
return state.confirmInfo;
},
USER_INFO(state) {
return state.userInfo;
},
LIST_DATA(state) {
return state.listInfo;
},
CREAM_DATA(state) {
return state.creamInfo;
},
ISSUE_DATA(state) {
return state.issueInfo;
}
},
mutations: {
[mutations.SET_NAV_STAT](state, payload) {
state.navStatus = payload.status;
},
[mutations.SET_LIST_SCROLL](state, payload) {
state.scrollPos.list = payload.pos;
},
[mutations.SET_CREAM_SCROLL](state, payload) {
state.scrollPos.cream = payload.pos;
},
[mutations.SET_ISSUE_SCROLL](state, payload) {
state.scrollPos.issue = payload.pos;
},
[mutations.SET_ACTIVE_NAV](state, payload) {
state.activeNav = payload.nav;
},
[mutations.SET_USER_INFO](state, payload) {
state.userInfo = payload.user;
},
[mutations.SET_MESSAGE](state, payload) {
state.msgInfo = payload.msgInfo;
},
[mutations.SET_CONFIRM](state, payload) {
state.confirmInfo = payload.confirmInfo;
},
[mutations.SET_LIST_DATA](state, payload) {
state.listInfo = payload.listInfo;
},
[mutations.SET_CREAM_DATA](state, payload) {
state.creamInfo = payload.creamInfo;
},
[mutations.SET_ISSUE_DATA](state, payload) {
state.issueInfo = payload.issueInfo;
}
},
actions: {
[actions.TRIGGER_NAV]({ commit }, payload) {
commit(mutations.SET_NAV_STAT, payload);
},
[actions.SET_POS]({ commit }, payload) {
if (payload.module === 'list') {
commit(mutations.SET_LIST_SCROLL, {pos: payload.pos});
} else if (payload.module === 'cream') {
commit(mutations.SET_CREAM_SCROLL, {pos: payload.pos});
} else if (payload.module === 'issue') {
commit(mutations.SET_ISSUE_SCROLL, {pos: payload.pos});
}
},
[actions.CHANGE_NAV]({ commit }, payload) {
commit(mutations.SET_ACTIVE_NAV, payload);
},
[actions.SET_USER]({ commit }, payload) {
commit(mutations.SET_USER_INFO, payload);
},
[actions.TRIGGER_MESSAGE]({ commit }, payload) {
commit(mutations.SET_MESSAGE, payload);
},
[actions.TRIGGER_CONFIRM]({ commit }, payload) {
commit(mutations.SET_CONFIRM, payload);
},
[actions.AJAX_DATA]({ commit }, payload) {
if (payload.module === 'list') {
commit(mutations.SET_LIST_DATA, {
listInfo: {
loaded: true,
page: payload.page || 0,
list: payload.list || [],
hasMore: payload.hasMore === undefined ? true : payload.hasMore
}
});
} else if (payload.module === 'cream') {
commit(mutations.SET_CREAM_DATA, {
creamInfo: {
loaded: true,
page: payload.page || 0,
list: payload.list || [],
hasMore: payload.hasMore === undefined ? true : payload.hasMore
}
});
} else if (payload.module === 'issue') {
commit(mutations.SET_ISSUE_DATA, {
issueInfo: {
loaded: true,
page: payload.page || 0,
list: payload.list || [],
hasMore: payload.hasMore === undefined ? true : payload.hasMore
}
});
}
}
}
});
export default store;
|
import Router from "express";
import {
updateUser,
deleteUser,
getUser,
getList,
getStats,
} from "../controllers/users.js";
import { verifyToken } from "../utils/jwt.js";
const router = Router();
// GET
router.get("/find", getUser);
router.get("/", verifyToken, getList);
router.get("/stats", verifyToken, getStats);
// PUT
router.put("/:id", verifyToken, updateUser);
// DELETE
router.delete("/:id", verifyToken, deleteUser);
export default router;
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import Layout from '@theme/Layout';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import Link from '@docusaurus/Link';
import useBaseUrl from '@docusaurus/useBaseUrl';
import versions from '../../versions.json';
function Version() {
const context = useDocusaurusContext();
const {siteConfig = {}} = context;
const latestVersion = versions[0];
const pastVersions = versions.filter((version) => version !== latestVersion);
const repoUrl = `https://github.com/${siteConfig.organizationName}/${siteConfig.projectName}`;
return (
<Layout
title="Versions"
permalink="/versions"
description="Docusaurus 2 Versions page listing all documented site versions">
<main className="container margin-vert--lg">
<h1>Docusaurus documentation versions</h1>
<div className="margin-bottom--lg">
<h3 id="latest">Latest version (Stable)</h3>
<p>Here you can find the latest documentation.</p>
<table>
<tbody>
<tr>
<th>{latestVersion}</th>
<td>
<Link to={useBaseUrl('/docs/introduction')}>
Documentation
</Link>
</td>
<td>
<a href={`${repoUrl}/releases/tag/v${latestVersion}`}>
Release Notes
</a>
</td>
</tr>
</tbody>
</table>
</div>
<div className="margin-bottom--lg">
<h3 id="next">Next version (Unreleased)</h3>
<p>Here you can find the documentation for unreleased version.</p>
<table>
<tbody>
<tr>
<th>master</th>
<td>
<Link to={useBaseUrl('/docs/next/introduction')}>
Documentation
</Link>
</td>
<td>
<a href={repoUrl}>Source Code</a>
</td>
</tr>
</tbody>
</table>
</div>
{pastVersions.length > 0 && (
<div className="margin-bottom--lg">
<h3 id="archive">Past Versions</h3>
<p>
Here you can find documentation for previous versions of
Docusaurus.
</p>
<table>
<tbody>
{pastVersions.map((version) => (
<tr key={version}>
<th>{version}</th>
<td>
<Link to={useBaseUrl(`/docs/${version}/introduction`)}>
Documentation
</Link>
</td>
<td>
<a href={`${repoUrl}/releases/tag/v${version}`}>
Release Notes
</a>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</main>
</Layout>
);
}
export default Version;
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 Chris Caron <lead2gold@gmail.com>
# All rights reserved.
#
# This code is licensed under the MIT License.
#
# 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.
import requests
from json import dumps
from .NotifyBase import NotifyBase
from ..URLBase import PrivacyMode
from ..common import NotifyType
from ..common import NotifyImageSize
from ..utils import parse_bool
from ..AppriseLocale import gettext_lazy as _
class NotifyXBMC(NotifyBase):
"""
A wrapper for XBMC/KODI Notifications
"""
# The default descriptive name associated with the Notification
service_name = 'Kodi/XBMC'
# The services URL
service_url = 'http://kodi.tv/'
xbmc_protocol = 'xbmc'
xbmc_secure_protocol = 'xbmcs'
kodi_protocol = 'kodi'
kodi_secure_protocol = 'kodis'
# The default protocols
protocol = (xbmc_protocol, kodi_protocol)
# The default secure protocols
secure_protocol = (xbmc_secure_protocol, kodi_secure_protocol)
# A URL that takes you to the setup/help of the specific protocol
setup_url = 'https://github.com/caronc/apprise/wiki/Notify_kodi'
# Disable throttle rate for XBMC/KODI requests since they are normally
# local anyway
request_rate_per_sec = 0
# Limit results to just the first 2 line otherwise there is just to much
# content to display
body_max_line_count = 2
# XBMC uses the http protocol with JSON requests
xbmc_default_port = 8080
# Allows the user to specify the NotifyImageSize object
image_size = NotifyImageSize.XY_128
# The number of seconds to display the popup for
default_popup_duration_sec = 12
# XBMC default protocol version (v2)
xbmc_remote_protocol = 2
# KODI default protocol version (v6)
kodi_remote_protocol = 6
# Define object templates
templates = (
'{schema}://{host}',
'{schema}://{host}:{port}',
'{schema}://{user}:{password}@{host}',
'{schema}://{user}:{password}@{host}:{port}',
)
# Define our tokens
template_tokens = dict(NotifyBase.template_tokens, **{
'host': {
'name': _('Hostname'),
'type': 'string',
'required': True,
},
'port': {
'name': _('Port'),
'type': 'int',
'min': 1,
'max': 65535,
},
'user': {
'name': _('Username'),
'type': 'string',
},
'password': {
'name': _('Password'),
'type': 'string',
'private': True,
},
})
# Define our template arguments
template_args = dict(NotifyBase.template_args, **{
'duration': {
'name': _('Duration'),
'type': 'int',
'min': 1,
'default': 12,
},
'image': {
'name': _('Include Image'),
'type': 'bool',
'default': True,
'map_to': 'include_image',
},
})
def __init__(self, include_image=True, duration=None, **kwargs):
"""
Initialize XBMC/KODI Object
"""
super(NotifyXBMC, self).__init__(**kwargs)
# Number of seconds to display notification for
self.duration = self.default_popup_duration_sec \
if not (isinstance(duration, int) and duration > 0) else duration
# Build our schema
self.schema = 'https' if self.secure else 'http'
# Prepare the default header
self.headers = {
'User-Agent': self.app_id,
'Content-Type': 'application/json'
}
# Default protocol
self.protocol = kwargs.get('protocol', self.xbmc_remote_protocol)
# Track whether or not we want to send an image with our notification
# or not.
self.include_image = include_image
def _payload_60(self, title, body, notify_type, **kwargs):
"""
Builds payload for KODI API v6.0
Returns (headers, payload)
"""
# prepare JSON Object
payload = {
'jsonrpc': '2.0',
'method': 'GUI.ShowNotification',
'params': {
'title': title,
'message': body,
# displaytime is defined in microseconds so we need to just
# do some simple math
'displaytime': int(self.duration * 1000),
},
'id': 1,
}
# Acquire our image url if configured to do so
image_url = None if not self.include_image else \
self.image_url(notify_type)
if image_url:
payload['params']['image'] = image_url
if notify_type is NotifyType.FAILURE:
payload['type'] = 'error'
elif notify_type is NotifyType.WARNING:
payload['type'] = 'warning'
else:
payload['type'] = 'info'
return (self.headers, dumps(payload))
def _payload_20(self, title, body, notify_type, **kwargs):
"""
Builds payload for XBMC API v2.0
Returns (headers, payload)
"""
# prepare JSON Object
payload = {
'jsonrpc': '2.0',
'method': 'GUI.ShowNotification',
'params': {
'title': title,
'message': body,
# displaytime is defined in microseconds so we need to just
# do some simple math
'displaytime': int(self.duration * 1000),
},
'id': 1,
}
# Include our logo if configured to do so
image_url = None if not self.include_image \
else self.image_url(notify_type)
if image_url:
payload['params']['image'] = image_url
return (self.headers, dumps(payload))
def send(self, body, title='', notify_type=NotifyType.INFO, **kwargs):
"""
Perform XBMC/KODI Notification
"""
if self.protocol == self.xbmc_remote_protocol:
# XBMC v2.0
(headers, payload) = self._payload_20(
title, body, notify_type, **kwargs)
else:
# KODI v6.0
(headers, payload) = self._payload_60(
title, body, notify_type, **kwargs)
auth = None
if self.user:
auth = (self.user, self.password)
url = '%s://%s' % (self.schema, self.host)
if self.port:
url += ':%d' % self.port
url += '/jsonrpc'
self.logger.debug('XBMC/KODI POST URL: %s (cert_verify=%r)' % (
url, self.verify_certificate,
))
self.logger.debug('XBMC/KODI Payload: %s' % str(payload))
# Always call throttle before any remote server i/o is made
self.throttle()
try:
r = requests.post(
url,
data=payload,
headers=headers,
auth=auth,
verify=self.verify_certificate,
)
if r.status_code != requests.codes.ok:
# We had a problem
status_str = \
NotifyXBMC.http_response_code_lookup(r.status_code)
self.logger.warning(
'Failed to send XBMC/KODI notification: '
'{}{}error={}.'.format(
status_str,
', ' if status_str else '',
r.status_code))
self.logger.debug('Response Details:\r\n{}'.format(r.content))
# Return; we're done
return False
else:
self.logger.info('Sent XBMC/KODI notification.')
except requests.RequestException as e:
self.logger.warning(
'A Connection error occured sending XBMC/KODI '
'notification.'
)
self.logger.debug('Socket Exception: %s' % str(e))
# Return; we're done
return False
return True
def url(self, privacy=False, *args, **kwargs):
"""
Returns the URL built dynamically based on specified arguments.
"""
# Define any arguments set
args = {
'format': self.notify_format,
'overflow': self.overflow_mode,
'image': 'yes' if self.include_image else 'no',
'duration': str(self.duration),
'verify': 'yes' if self.verify_certificate else 'no',
}
# Determine Authentication
auth = ''
if self.user and self.password:
auth = '{user}:{password}@'.format(
user=NotifyXBMC.quote(self.user, safe=''),
password=self.pprint(
self.password, privacy, mode=PrivacyMode.Secret, safe=''),
)
elif self.user:
auth = '{user}@'.format(
user=NotifyXBMC.quote(self.user, safe=''),
)
default_schema = self.xbmc_protocol if (
self.protocol <= self.xbmc_remote_protocol) else self.kodi_protocol
default_port = 443 if self.secure else self.xbmc_default_port
if self.secure:
# Append 's' to schema
default_schema += 's'
return '{schema}://{auth}{hostname}{port}/?{args}'.format(
schema=default_schema,
auth=auth,
hostname=NotifyXBMC.quote(self.host, safe=''),
port='' if not self.port or self.port == default_port
else ':{}'.format(self.port),
args=NotifyXBMC.urlencode(args),
)
@staticmethod
def parse_url(url):
"""
Parses the URL and returns enough arguments that can allow
us to substantiate this object.
"""
results = NotifyBase.parse_url(url)
if not results:
# We're done early
return results
# We want to set our protocol depending on whether we're using XBMC
# or KODI
if results.get('schema', '').startswith('xbmc'):
# XBMC Support
results['protocol'] = NotifyXBMC.xbmc_remote_protocol
# Assign Default XBMC Port
if not results['port']:
results['port'] = NotifyXBMC.xbmc_default_port
else:
# KODI Support
results['protocol'] = NotifyXBMC.kodi_remote_protocol
# Include images with our message
results['include_image'] = \
parse_bool(results['qsd'].get('image', True))
# Set duration
try:
results['duration'] = abs(int(results['qsd'].get('duration')))
except (TypeError, ValueError):
# Not a valid integer; ignore entry
pass
return results
|
from numpy import cos
from numpy.random import randint
from OpenGL.GL import *
from data.mydata import d
import lib.basic_shapes as bs
import lib.easy_shaders as es
import lib.scene_graph as sg
import lib.transformations as tr
class Apple():
def __init__(self):
gpu_stem = es.toGPUShape(bs.createColorQuad(159/255, 107/255, 61/255))
gpu_skin = es.toGPUShape(bs.create_circle(0.5, (0, 0), (1.0, 0.0, 0.0)))
gpu_leaf = es.toGPUShape(bs.createColorQuad(0.0, 1.0, 0.0))
stem = sg.SceneGraphNode("stem")
stem.transform = tr.matmul([tr.uniformScale(0.5), tr.scale(0.5, 1, 1), tr.translate(0, 1, 0)])
stem.childs += [gpu_stem]
skin = sg.SceneGraphNode("skin")
skin.transform = tr.matmul([tr.scale(1, 1, 1), tr.translate(0, 0, 0)])
skin.childs += [gpu_skin]
leaf = sg.SceneGraphNode("leaf")
leaf.transform = tr.matmul([tr.uniformScale(0.5), tr.scale(1, 0.5, 1), tr.translate(0.25, 3, 0)])
leaf.childs += [gpu_leaf]
apple = sg.SceneGraphNode("apple")
apple.transform = tr.matmul([tr.uniformScale(0.75), tr.scale(1/d["n"], 1/d["n"], 1), tr.scale(1, d["w"]/d["h"], 1)])
apple.childs += [stem, skin, leaf]
self.x, self.y = randint(0, d["n"]-2, 2)
apple_tr = sg.SceneGraphNode('apple_tr')
apple_tr.transform = tr.translate(self.x, self.y, 0)
apple_tr.childs += [apple]
self.model = apple_tr
def draw(self, pipeline, t):
if d["n"] % 2 == 0:
self.model.transform = tr.translate((self.x - d["n"]//2 + 1 + 0.5)/d["n"], (self.y - d["n"]//2 + 1 + 0.5 + cos(2*t)/6)/d["n"]*d["w"]/d["h"], 0)
else:
self.model.transform = tr.translate((self.x - d["n"]//2 + 1)/d["n"], (self.y - d["n"]//2 + 1 + cos(2*t)/6)/d["n"]*d["w"]/d["h"], 0)
sg.drawSceneGraphNode(self.model, pipeline, "transform")
def respawn(self, snake):
self.x, self.y = randint(0, d["n"]-2, 2)
if snake.time - snake.grid[self.y][self.x] < snake.length:
return self.respawn(snake)
|
/* jslint node: true, esversion: 6 */
"use strict";
const express = require("express");
const path = require("path");
const bodyParser = require("body-parser");
const minimist = require("minimist");
var config = {
"firmware": "-",
"protocol": "-",
"espflash": 4194304,
"version": "DEMO",
"diodet": 0,
"gfcit": 0,
"groundt": 0,
"relayt": 0,
"ventt": 0,
"tempt": 0,
"service": 2,
"scale": 220,
"offset": 0,
"ssid": "demo",
"pass": "___DUMMY_PASSWORD___",
"emoncms_enabled": false,
"emoncms_server": "emoncms.org",
"emoncms_node": "openevse",
"emoncms_apikey": "",
"emoncms_fingerprint": "",
"mqtt_enabled": true,
"mqtt_server": "emonpi.local",
"mqtt_topic": "openevse",
"mqtt_user": "emonpi",
"mqtt_pass": "___DUMMY_PASSWORD___",
"mqtt_solar": "emon/emonpi/power1",
"mqtt_grid_ie": "",
"www_username": "",
"www_password": "",
"ohm_enabled": false
};
var status = {
"mode": "STA",
"wifi_client_connected": 1,
"srssi": -50,
"ipaddress": "172.16.0.191",
"emoncms_connected": 0,
"packets_sent": 0,
"packets_success": 0,
"mqtt_connected": 1,
"ohm_hour": "NotConnected",
"free_heap": 20816,
"comm_sent": 1077,
"comm_success": 1075,
"amp": 27500,
"pilot": 32,
"temp1": 247,
"temp2": 0,
"temp3": 230,
"state": 3,
"elapsed": 10790,
"wattsec": 71280000,
"watthour": 72970,
"gfcicount": 0,
"nogndcount": 0,
"stuckcount": 0,
"divertmode": 1,
"solar": 0,
"grid_ie": 0,
"charge_rate": 0,
"divert_update": 0
};
var autoService = 1;
var autoStart = 0;
var serialDebug = 0;
var lcdType = 0;
var commandEcho = 0;
var ffSupported = true;
let args = minimist(process.argv.slice(2), {
alias: {
h: "help",
v: "version"
},
default: {
help: false,
version: false,
port: 3000
},
});
if(args.help) {
console.log("OpenEVSE WiFi Simulator");
return 0;
}
if(args.version) {
console.log(config.version);
return 0;
}
var port = args.port;
const app = express();
const expressWs = require("express-ws")(app);
function toHex(num, len)
{
var str = num.toString(16);
while(str.length < len) {
str = "0" + str;
}
return str.toUpperCase();
}
function checksum(msg)
{
var check = 0;
for(var i = 0; i < msg.length; i++) {
check ^= msg.charCodeAt(i);
}
var checkString = toHex(check, 2);
return msg + "^" + checkString;
}
//
// Create HTTP server by ourselves.
//
// Setup the static content
app.use(express.static(path.join(__dirname, "../gui/dist"), { index: "home.html" }));
// Setup the API endpoints
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/config", function (req, res) {
res.header("Cache-Control", "no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0");
res.json(config);
});
app.get("/status", function (req, res) {
res.header("Cache-Control", "no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0");
status.srssi += 5 - (Math.floor(Math.random() * 11));
res.json(status);
});
app.get("/update", function (req, res) {
res.header("Cache-Control", "no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0");
res.send("<html><form method='POST' action='/update' enctype='multipart/form-data'><input type='file' name='firmware'> <input type='submit' value='Update'></form></html>");
});
app.post("/update", function (req, res) {
res.header("Cache-Control", "no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0");
res.status(500).send("Not implemented");
});
app.get("/r", function (req, res) {
res.header("Cache-Control", "no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0");
var dummyData = {
"GT": "$OK 18 0 25 23 54 27^1B",
"GE": "$OK 20 0229^2B",
"GC": "$OK 10 80^29",
"G3": "$OK 0^30",
"GH": "$OK 0^30",
"GO": "$OK 650 650^20",
"GD": "$OK 0 0 0 0^20"
};
var rapi = req.query.rapi;
status.comm_sent++;
var regex = /\$([^\^]*)(\^..)?/;
var match = rapi.match(regex);
var request = match[1].split(" ");
var cmd = request[0];
var resp = { "cmd": rapi, "ret": "" };
var success = false;
switch (cmd) {
case "GT": {
var date = new Date();
var time = [
date.getFullYear() % 100,
date.getMonth() + 1,
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds()
];
resp.ret = checksum("$OK " + time.join(" "));
success = true;
break;
}
case "GE": {
var flags = 0;
flags |= (2 === config.service ? 0x0001 : 0);
flags |= (config.diodet ? 0x0002 : 0);
flags |= (config.ventt ? 0x0004 : 0);
flags |= (config.groundt ? 0x0008 : 0);
flags |= (config.relayt ? 0x0010 : 0);
flags |= (autoService ? 0x0020 : 0);
flags |= (autoStart ? 0x0040 : 0);
flags |= (serialDebug ? 0x0080 : 0);
flags |= (lcdType ? 0x0100 : 0);
flags |= (config.gfcit ? 0x0200 : 0);
flags |= (config.tempt ? 0x0400 : 0);
var flagsStr = toHex(flags, 4);
resp.ret = checksum("$OK " + status.pilot.toString() + " " + flagsStr);
success = true;
break;
}
case "FF": {
if(ffSupported && request.length >= 3)
{
switch(request[1])
{
case "D":
config.diodet = parseInt(request[2]) ? 0 : 1;
success = true;
break;
case "E":
commandEcho = parseInt(request[2]);
success = true;
break;
case "F":
config.gfcit = parseInt(request[2]) ? 0 : 1;
success = true;
break;
case "G":
config.groundt = parseInt(request[2]) ? 0 : 1;
success = true;
break;
case "R":
config.relayt = parseInt(request[2]) ? 0 : 1;
success = true;
break;
case "T":
config.tempt = parseInt(request[2]) ? 0 : 1;
success = true;
break;
case "V":
config.ventt = parseInt(request[2]) ? 0 : 1;
success = true;
break;
}
if(success) {
resp.ret = checksum("$OK");
}
}
} break;
case "SD": {
if(!ffSupported && request.length >= 2) {
config.diodet = parseInt(request[1]) ? 0 : 1;
success = true;
resp.ret = checksum("$OK");
}
} break;
case "SE": {
if(!ffSupported && request.length >= 2) {
commandEcho = parseInt(request[1]);
success = true;
resp.ret = checksum("$OK");
}
} break;
case "SF": {
if(!ffSupported && request.length >= 2) {
config.gfcit = parseInt(request[1]) ? 0 : 1;
success = true;
resp.ret = checksum("$OK");
}
} break;
case "SG": {
if(!ffSupported && request.length >= 2) {
config.groundt = parseInt(request[1]) ? 0 : 1;
success = true;
resp.ret = checksum("$OK");
}
} break;
case "SR": {
if(!ffSupported && request.length >= 2) {
config.relayt = parseInt(request[1]) ? 0 : 1;
success = true;
resp.ret = checksum("$OK");
}
} break;
case "SV": {
if(!ffSupported && request.length >= 2) {
config.ventt = parseInt(request[1]) ? 0 : 1;
success = true;
resp.ret = checksum("$OK");
}
} break;
default:
if (rapi.hasOwnProperty(cmd)) {
resp.ret = dummyData[cmd];
success = true;
break;
}
}
if(success) {
status.comm_success++;
} else {
resp.ret = "$NK";
}
res.json(resp);
});
app.post("/savenetwork", function (req, res) {
res.header("Cache-Control", "no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0");
res.status(500).send("Not implemented");
});
app.post("/saveemoncms", function (req, res) {
res.header("Cache-Control", "no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0");
res.status(500).send("Not implemented");
});
app.post("/savemqtt", function (req, res) {
res.header("Cache-Control", "no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0");
res.status(500).send("Not implemented");
});
app.post("/saveadmin", function (req, res) {
res.header("Cache-Control", "no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0");
res.status(500).send("Not implemented");
});
app.post("/saveohmkey", function (req, res) {
res.header("Cache-Control", "no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0");
res.status(500).send("Not implemented");
});
app.post("/reset", function (req, res) {
res.header("Cache-Control", "no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0");
res.status(500).send("Not implemented");
});
app.post("/restart", function (req, res) {
res.header("Cache-Control", "no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0");
res.status(500).send("Not implemented");
});
app.get("/scan", function (req, res) {
res.header("Cache-Control", "no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0");
setTimeout(function () {
res.json([{"rssi":-51,"ssid":"wibble_ext","bssid":"C4:04:15:5A:45:DE","channel":11,"secure":4,"hidden":false},{"rssi":-45,"ssid":"esplug_10560510","bssid":"1A:FE:34:A1:23:FE","channel":11,"secure":7,"hidden":false},{"rssi":-85,"ssid":"BTWifi-with-FON","bssid":"02:FE:F4:32:F1:08","channel":6,"secure":7,"hidden":false},{"rssi":-87,"ssid":"BTWifi-X","bssid":"22:FE:F4:32:F1:08","channel":6,"secure":7,"hidden":false},{"rssi":-75,"ssid":"wibble","bssid":"6C:B0:CE:20:7C:3A","channel":6,"secure":4,"hidden":false},{"rssi":-89,"ssid":"BTHub3-ZWCW","bssid":"00:FE:F4:32:F1:08","channel":6,"secure":8,"hidden":false}]);
}, 5000);
});
app.post("/apoff", function (req, res) {
res.header("Cache-Control", "no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0");
res.status(500).send("Not implemented");
});
app.post("/divertmode", function (req, res) {
res.header("Cache-Control", "no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0");
res.status(500).send("Not implemented");
});
app.ws("/ws", function(ws, req) {
ws.on("message", function(msg) {
//ws.send(msg);
});
});
app.listen(port, () => console.log("OpenEVSE WiFi Simulator listening on port " + port + "!"));
|
// json2.js
// 2017-06-12
// Public Domain.
const rx_one = /^[\],:{}\s]*$/
const rx_two = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g
const rx_three = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g
const rx_four = /(?:^|:|,)(?:\s*\[)+/g
const rx_escapable = /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g
const rx_dangerous = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g
export const jsonParser = function (text, reviver) {
let j
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
let k
let v
const value = holder[key]
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k)
if (v !== undefined) {
value[k] = v
} else {
delete value[k]
}
}
}
}
return reviver.call(holder, key, value)
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text)
rx_dangerous.lastIndex = 0
if (rx_dangerous.test(text)) {
text = text.replace(rx_dangerous, a => '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4))
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with "()" and "new"
// because they can cause invocation, and "=" because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with "@" (a non-JSON character). Second, we
// replace all simple value tokens with "]" characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or "]" or
// "," or ":" or "{" or "}". If that is so, then the text is safe for eval.
if (
rx_one.test(
text
.replace(rx_two, '@')
.replace(rx_three, ']')
.replace(rx_four, '')
)
) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The "{" operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')')
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return (typeof reviver === 'function')
? walk({ '': j }, '')
: j
}
throw new SyntaxError('JSON.parse')
}
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getAlerts = getAlerts;
exports.getLatestAlert = getLatestAlert;
exports.getLatestErrorAlert = exports.getLatestDeveloperAlert = exports.getLatestNotificationAlert = void 0;
require("core-js/modules/es6.array.find");
var _reselect = require("reselect");
var _constants = require("../../constants");
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
// @flow
function getAlerts(state
/*: GlobalState*/
) {
return state.entities.alerts.alertStack;
}
function getLatestAlert(state
/*: GlobalState*/
) {
return state.entities.alerts.alertStack[0];
}
var getLatestNotificationAlert
/*: (state: GlobalState) => ?AlertType*/
= (0, _reselect.createSelector)(getAlerts, function (alerts) {
return alerts.find(function (a) {
return a.type === _constants.Alerts.ALERT_NOTIFICATION;
});
});
exports.getLatestNotificationAlert = getLatestNotificationAlert;
var getLatestDeveloperAlert
/*: (state: GlobalState) => ?AlertType*/
= (0, _reselect.createSelector)(getAlerts, function (alerts) {
return alerts.find(function (a) {
return a.type === _constants.Alerts.ALERT_DEVELOPER;
});
});
exports.getLatestDeveloperAlert = getLatestDeveloperAlert;
var getLatestErrorAlert
/*: (state: GlobalState) => ?AlertType*/
= (0, _reselect.createSelector)(getAlerts, function (alerts) {
return alerts.find(function (a) {
return a.type === _constants.Alerts.ALERT_ERROR;
});
});
exports.getLatestErrorAlert = getLatestErrorAlert;
|
import {
VALID_ANNOTATION_FILES_ARRAY, IMAGE_FILES_OBJECT, IMAGE_FILE_INDICATOR,
ONE_ANNOTATION_FILE_ALLOWED_ERROR_MESSAGE, ACTIVE_ANNOTATION_FILE, ANNOTATION_FILE_INDICATOR,
} from '../../../../consts.js';
import {
insertRowToImagesTable, enableFinishButton,
disableFinishButton, changeAllImagesTableRowsToDefault,
insertRowToAnnotationsTable, changeAnnotationRowToDefault,
} from '../../style.js';
function validateExistingImagesWhenMultipleAnnotationFilesAllowed(datasetObject,
updateImageFileErrorStatusFunc, validateFileFunc) {
if (datasetObject[VALID_ANNOTATION_FILES_ARRAY].length > 0) {
let foundValid = false;
Object.keys(datasetObject[IMAGE_FILES_OBJECT]).forEach((key) => {
const imageFile = datasetObject[IMAGE_FILES_OBJECT][key];
const validationResult = validateFileFunc(imageFile);
if (!validationResult.error) { foundValid = true; }
const { name } = imageFile.body.fileMetaData;
insertRowToImagesTable(name, validationResult);
updateImageFileErrorStatusFunc(name, validationResult.error);
});
if (foundValid) {
enableFinishButton();
} else {
disableFinishButton();
}
} else {
changeAllImagesTableRowsToDefault();
disableFinishButton();
}
}
function validateExistingImagesWhenOneAnnotationFileAllowed(datasetObject,
updateImageFileErrorStatusFunc, validateFileFunc) {
let foundValid = false;
Object.keys(datasetObject[IMAGE_FILES_OBJECT]).forEach((key) => {
const imageFile = datasetObject[IMAGE_FILES_OBJECT][key];
const validationResult = validateFileFunc(imageFile);
if (!validationResult.error) { foundValid = true; }
const { name } = imageFile.body.fileMetaData;
insertRowToImagesTable(name, validationResult);
updateImageFileErrorStatusFunc(name, validationResult.error);
});
if (foundValid) {
enableFinishButton();
} else {
disableFinishButton();
}
}
function reValidateExistingAnnotations(annotationFiles, validateFileFunc) {
annotationFiles.forEach((annotationFile) => {
const validationResult = validateFileFunc(annotationFile);
const { name } = annotationFile.body.fileMetaData;
if (!validationResult.error) {
validationResult.error = true;
validationResult.message = ONE_ANNOTATION_FILE_ALLOWED_ERROR_MESSAGE;
}
insertRowToAnnotationsTable(name, validationResult);
});
}
function checkAnnotationAlreadyInTable(validationResult, datasetObject,
updateImageFileErrorStatusFunc, validateFileFunc) {
const activeAnnotationFile = datasetObject[ACTIVE_ANNOTATION_FILE];
const validAnnotationFiles = datasetObject[VALID_ANNOTATION_FILES_ARRAY];
if (!validationResult.error) {
reValidateExistingAnnotations(validAnnotationFiles, validateFileFunc);
validateExistingImagesWhenOneAnnotationFileAllowed(datasetObject,
updateImageFileErrorStatusFunc, validateFileFunc);
return validationResult;
}
if (validAnnotationFiles.length > 0) {
if (activeAnnotationFile && activeAnnotationFile.newlyActive) {
changeAnnotationRowToDefault(activeAnnotationFile.body.fileMetaData.name);
activeAnnotationFile.newlyActive = false;
validateExistingImagesWhenOneAnnotationFileAllowed(datasetObject,
updateImageFileErrorStatusFunc, validateFileFunc);
}
return { error: true, message: validationResult.message };
}
changeAllImagesTableRowsToDefault();
return validationResult;
}
function updateAnnotationTableWhenOneAnnotationFileAllowed(fileName, validationResult,
datasetObject, updateImageFileErrorStatusFunc, validateFormatFunc) {
const newValidationResult = checkAnnotationAlreadyInTable(
validationResult, datasetObject, updateImageFileErrorStatusFunc, validateFormatFunc,
);
// whilst the reValidateExistingAnnotations inserts the new annotation,
// this overwrites it if it has been incorrectly set with an error
insertRowToAnnotationsTable(fileName, newValidationResult);
}
function updateAnnotationTableWhenMultipleAnnotationFilesAllowed(fileName, validationResult,
datasetObject, updateImageFileErrorStatusFunc, validateFormatFunc) {
validateExistingImagesWhenMultipleAnnotationFilesAllowed(datasetObject,
updateImageFileErrorStatusFunc, validateFormatFunc);
// whilst the reValidateExistingAnnotations inserts the new annotation,
// this overwrites it if it has been incorrectly set with an error
insertRowToAnnotationsTable(fileName, validationResult);
}
function updateTables(parsedObj, validationResult) {
if (!parsedObj.body) return;
const fileName = parsedObj.body.fileMetaData.name;
const datasetObject = this.datasetObjectManager.getDatasetObject();
if (parsedObj.fileFormat === IMAGE_FILE_INDICATOR) {
insertRowToImagesTable(fileName, validationResult);
if (validationResult.valid) { enableFinishButton(); }
}
if (parsedObj.fileFormat === ANNOTATION_FILE_INDICATOR) {
this.updateAnnotationTableFunc(fileName, validationResult, datasetObject,
this.datasetObjectManager.updateImageFileErrorStatus, this.validateFormat);
}
}
function buildTableUpdaterForMultipleAnnotationFilesStrategy(datasetObjectManager,
validateFormat) {
const updateAnnotationTableFunc = updateAnnotationTableWhenMultipleAnnotationFilesAllowed;
return updateTables.bind(
{ datasetObjectManager, validateFormat, updateAnnotationTableFunc },
);
}
function buildTableUpdaterForOneAnnotationFileStrategy(datasetObjectManager, validateFormat) {
const updateAnnotationTableFunc = updateAnnotationTableWhenOneAnnotationFileAllowed;
return updateTables.bind(
{ datasetObjectManager, validateFormat, updateAnnotationTableFunc },
);
}
const TableUpdaterGenericBuilder = {
buildTableUpdaterForOneAnnotationFileStrategy,
buildTableUpdaterForMultipleAnnotationFilesStrategy,
};
export { TableUpdaterGenericBuilder as default };
|
var router = require('express').Router();
router.use('/', require('./users'))
router.use('/articles', require('./articles'))
router.use('/collections', require('./collections'))
router.use('/about', require('./about'))
router.use(function(err, req, res, next){
if(err.name === 'ValidationError'){
return res.status(422).json({
errors: Object.keys(err.errors).reduce(function(errors, key){
errors[key] = err.errors[key].message
return errors
}, {})
})
}
return next(err)
})
module.exports = router;
|
/*
* @Author: zsj
* @Date: 2018-02-12 15:58:08
* @Last Modified by: wangweixin
* @Last Modified time: 2019-04-10 14:22:09
*/
import React, { Component } from "react";
import { any } from "prop-types";
import classNames from "classnames";
/**
* 页面头部标题
*/
class PageTitle extends Component {
render() {
const { name, children, className, style } = this.props;
const classes = classNames("row page-max-title", className);
// const _key = `${Math.random().toFixed(6)}hjsd`
return (
<div className={classes} style={style}>
{children}
{name}
</div>
);
}
}
PageTitle.displayName = "PageTitle";
PageTitle.propTypes = {
/** 唯一需要传入的属性 */
name: any.isRequired
};
PageTitle.defaultProps = {
name: ""
};
export default PageTitle;
|
define([
], function(
) {
return {
"NAME": "tool"
};
});
|
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.cyrToLatTranslit = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
'use strict';
module.exports = function cyrToLatTranslit(config) {
const invert = require('lodash.invert');
const _preset = config ? config.preset : "tj";
/*
ASSOCIATIONS FOR INITIAL POSITION
*/
// letters shared between languages
const _firstLetters = {
"а": "a",
"б": "b",
"в": "v",
"д": "d",
"з": "z",
"й": "y",
"к": "k",
"л": "l",
"м": "m",
"н": "n",
"о": "o",
"п": "p",
"р": "r",
"с": "s",
"т": "t",
"у": "u",
"ф": "f",
"э": "e",
"и": "i",
"г": "g",
};
// language-specific letters
if (_preset === "ru") {
Object.assign(_firstLetters, {
"ь": "",
"ъ": "",
"ы": "i",
});
} else if (_preset === "tj") {
Object.assign(_firstLetters, {
"ҳ": "h",
"қ": "q",
"ҷ": "j",
"ӯ": "u",
"ғ": "g",
"ӣ": "i",
"й": "y",
})
}
let _reversedFirstLetters;
if (_preset === "ru") {
// Russian: i > always и, y > й in initial position, e > э in initial position
_reversedFirstLetters = Object.assign(invert(_firstLetters), {"i": "и", "": ""});
} else if (_preset === "tj") {
_reversedFirstLetters = Object.assign(invert(_firstLetters), {"": ""});
}
// digraphs appearing only in initial position
const _initialDigraphs = (_preset === "ru") ? {"е": "ye"} : {"е": "e"};
// digraphs appearing in all positions
const _regularDigraphs = {
"ё": "yo",
"ж": "zh",
"х": "kh",
"ц": "ts",
"ч": "ch",
"ш": "sh",
"щ": "shch",
"ю": "yu",
"я": "ya",
}
const _firstDigraphs = Object.assign({}, _regularDigraphs, _initialDigraphs);
const _reversedFirstDigraphs = Object.assign(invert(_firstDigraphs));
const _firstAssociations = Object.assign(_firstLetters, _firstDigraphs);
/*
ASSOCIATIONS FOR NON-INITIAL POSITION
*/
let _nonFirstLetters = {};
if (_preset === "ru") {
_nonFirstLetters = Object.assign({}, _firstLetters, { "й": "i" });
Object.assign(_nonFirstLetters, {"е": "e"});
} else if (_preset === "tj") {
Object.assign(_nonFirstLetters, _firstLetters, {"": ""});
}
let _reversedNonFirstLetters;
if (_preset === "ru") {
// Russian: i > always и, y > ы in non-initial position, e > е in non-initial position
_reversedNonFirstLetters = Object.assign(invert(_firstLetters), {
"i": "и",
"y": "ы",
"e": "е",
"": ""
});
} else if (_preset === "tj") {
_reversedNonFirstLetters = Object.assign(invert(_firstLetters), {"": ""});
}
// digraphs appearing only in non-initial positions
let _nonInitialDigraphs = {};
const _nonFirstDigraphs = Object.assign(_regularDigraphs, _nonInitialDigraphs);
const _reversedNonFirstDigraphs = Object.assign(invert(_nonFirstDigraphs));
const _nonFirstAssociations = Object.assign(_nonFirstLetters, _nonFirstDigraphs);
function transform(input, spaceReplacement) {
if (!input) {
return "";
}
// We must normalize string for transform all unicode chars to uniform form
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize
const normalizedInput = input.normalize();
let newStr = "";
let isWordBoundary = false;
for (let i = 0; i < normalizedInput.length; i++) {
const isUpperCaseOrWhatever = normalizedInput[i] === normalizedInput[i].toUpperCase();
let strLowerCase = normalizedInput[i].toLowerCase();
if (strLowerCase === " ") {
newStr += spaceReplacement ? spaceReplacement : " ";
isWordBoundary = true;
continue;
}
let newLetter;
if (i === 0 || isWordBoundary) {
newLetter = _firstAssociations[strLowerCase];
isWordBoundary = false;
} else {
newLetter = _nonFirstAssociations[strLowerCase];
}
if ("undefined" === typeof newLetter) {
newStr += isUpperCaseOrWhatever ? strLowerCase.toUpperCase() : strLowerCase;
} else if (isUpperCaseOrWhatever) {
// handle multi-symbol letters
newLetter.length > 1
? newStr += newLetter[0].toUpperCase() + newLetter.slice(1)
: newStr += newLetter.toUpperCase();
} else {
newStr += newLetter;
}
}
return newStr;
}
function reverse(input, spaceReplacement) {
if (!input) return "";
const normalizedInput = input.normalize();
let newStr = "";
let isWordBoundary = false;
let i = 0;
while (i < normalizedInput.length) {
const isUpperCaseOrWhatever = normalizedInput[i] === normalizedInput[i].toUpperCase();
let strLowerCase = normalizedInput[i].toLowerCase();
let currentIndex = i;
if (strLowerCase === " " || strLowerCase === spaceReplacement) {
newStr += " ";
isWordBoundary = true;
i++;
continue;
}
let newLetter;
let digraph = normalizedInput.slice(i, i + 2).toLowerCase();
if (i === 0 || isWordBoundary) {
newLetter = _reversedFirstDigraphs[digraph];
if (newLetter) {
i += 2;
} else {
newLetter = _reversedFirstLetters[strLowerCase];
i++;
}
isWordBoundary = false;
} else {
newLetter = _reversedNonFirstDigraphs[digraph];
if (newLetter) {
i += 2;
} else {
newLetter = _reversedNonFirstLetters[strLowerCase];
i++;
}
}
// special cases: щ and зг
if (normalizedInput.slice(currentIndex, currentIndex + 4).toLowerCase() === "shch") {
newLetter = "щ";
i = currentIndex + 4;
} else if (normalizedInput.slice(currentIndex - 1, currentIndex + 2).toLowerCase() === "zgh") {
newLetter = "г";
i = currentIndex + 2;
}
if ("undefined" === typeof newLetter) {
newStr += isUpperCaseOrWhatever ? strLowerCase.toUpperCase() : strLowerCase;
} else {
if (isUpperCaseOrWhatever) {
// handle multi-symbol letters
newLetter.length > 1
? newStr += newLetter[0].toUpperCase() + newLetter.slice(1)
: newStr += newLetter.toUpperCase();
} else {
newStr += newLetter;
}
}
}
return newStr;
}
return {
transform: transform,
reverse: reverse
};
};
},{"lodash.invert":2}],2:[function(require,module,exports){
/**
* lodash (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]';
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = overArg(Object.keys, Object);
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
// Safari 8.1 makes `arguments.callee` enumerable in strict mode.
// Safari 9 makes `arguments.length` enumerable in strict mode.
var result = (isArray(value) || isArguments(value))
? baseTimes(value.length, String)
: [];
var length = result.length,
skipIndexes = !!length;
for (var key in value) {
if ((inherited || hasOwnProperty.call(value, key)) &&
!(skipIndexes && (key == 'length' || isIndex(key, length)))) {
result.push(key);
}
}
return result;
}
/**
* The base implementation of `baseForOwn` which iterates over `object`
* properties returned by `keysFunc` and invokes `iteratee` for each property.
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseFor = createBaseFor();
/**
* The base implementation of `_.forOwn` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwn(object, iteratee) {
return object && baseFor(object, iteratee, keys);
}
/**
* The base implementation of `_.invert` and `_.invertBy` which inverts
* `object` with values transformed by `iteratee` and set by `setter`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform values.
* @param {Object} accumulator The initial inverted object.
* @returns {Function} Returns `accumulator`.
*/
function baseInverter(object, setter, iteratee, accumulator) {
baseForOwn(object, function(value, key, object) {
setter(accumulator, iteratee(value), key, object);
});
return accumulator;
}
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
/**
* Creates a base function for methods like `_.forIn` and `_.forOwn`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var index = -1,
iterable = Object(object),
props = keysFunc(object),
length = props.length;
while (length--) {
var key = props[fromRight ? length : ++index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
/**
* Creates a function like `_.invertBy`.
*
* @private
* @param {Function} setter The function to set accumulator values.
* @param {Function} toIteratee The function to resolve iteratees.
* @returns {Function} Returns the new inverter function.
*/
function createInverter(setter, toIteratee) {
return function(object, iteratee) {
return baseInverter(object, setter, toIteratee(iteratee), {});
};
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length &&
(typeof value == 'number' || reIsUint.test(value)) &&
(value > -1 && value % 1 == 0 && value < length);
}
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
// Safari 8.1 makes `arguments.callee` enumerable in strict mode.
return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
(!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
}
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 8-9 which returns 'object' for typed array and other constructors.
var tag = isObject(value) ? objectToString.call(value) : '';
return tag == funcTag || tag == genTag;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Creates an object composed of the inverted keys and values of `object`.
* If `object` contains duplicate values, subsequent values overwrite
* property assignments of previous values.
*
* @static
* @memberOf _
* @since 0.7.0
* @category Object
* @param {Object} object The object to invert.
* @returns {Object} Returns the new inverted object.
* @example
*
* var object = { 'a': 1, 'b': 2, 'c': 1 };
*
* _.invert(object);
* // => { '1': 'c', '2': 'b' }
*/
var invert = createInverter(function(result, value, key) {
result[value] = key;
}, constant(identity));
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new constant function.
* @example
*
* var objects = _.times(2, _.constant({ 'a': 1 }));
*
* console.log(objects);
* // => [{ 'a': 1 }, { 'a': 1 }]
*
* console.log(objects[0] === objects[1]);
* // => true
*/
function constant(value) {
return function() {
return value;
};
}
/**
* This method returns the first argument it receives.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'a': 1 };
*
* console.log(_.identity(object) === object);
* // => true
*/
function identity(value) {
return value;
}
module.exports = invert;
},{}]},{},[1])(1)
});
|
'use strict';
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var iconHelpers = require('@carbon/icon-helpers');
var PropTypes = _interopDefault(require('prop-types'));
var React = _interopDefault(require('react'));
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
var defaultStyle = {
"willChange": "transform"
};
var DocumentExport20 = React.forwardRef(function (_ref, ref) {
var className = _ref.className,
children = _ref.children,
style = _ref.style,
tabIndex = _ref.tabIndex,
rest = _objectWithoutProperties(_ref, ["className", "children", "style", "tabIndex"]);
var _getAttributes = iconHelpers.getAttributes(_objectSpread({}, rest, {
tabindex: tabIndex
})),
tabindex = _getAttributes.tabindex,
props = _objectWithoutProperties(_getAttributes, ["tabindex"]);
if (className) {
props.className = className;
}
if (tabindex !== undefined && tabindex !== null) {
props.tabIndex = tabindex;
}
if (_typeof(style) === 'object') {
props.style = _objectSpread({}, defaultStyle, style);
} else {
props.style = defaultStyle;
}
if (ref) {
props.ref = ref;
}
return React.createElement('svg', props, children, React.createElement('path', {
d: 'M13 21h13.17l-2.58 2.59L25 25l5-5-5-5-1.41 1.41L26.17 19H13v2z'
}), React.createElement('path', {
d: 'M22 14v-4a1 1 0 0 0-.29-.71l-7-7A1 1 0 0 0 14 2H4a2 2 0 0 0-2 2v24a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2h-2v2H4V4h8v6a2 2 0 0 0 2 2h6v2zm-8-4V4.41L19.59 10z'
}));
});
DocumentExport20.displayName = 'DocumentExport20';
DocumentExport20.propTypes = {
'aria-hidden': PropTypes.bool,
'aria-label': PropTypes.string,
'aria-labelledby': PropTypes.string,
className: PropTypes.string,
children: PropTypes.node,
height: PropTypes.number,
preserveAspectRatio: PropTypes.string,
tabIndex: PropTypes.string,
viewBox: PropTypes.string,
width: PropTypes.number,
xmlns: PropTypes.string
};
DocumentExport20.defaultProps = {
width: 20,
height: 20,
viewBox: '0 0 32 32',
xmlns: 'http://www.w3.org/2000/svg',
preserveAspectRatio: 'xMidYMid meet'
};
module.exports = DocumentExport20;
|
/*!
* jQuery JavaScript Library v1.12.4
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-05-20T17:17Z
*/
(function( global, factory ) {
if ( typeof module === "object" && typeof module.exports === "object" ) {
// For CommonJS and CommonJS-like environments where a proper `window`
// is present, execute the factory and get jQuery.
// For environments that do not have a `window` with a `document`
// (such as Node.js), expose a factory as module.exports.
// This accentuates the need for the creation of a real `window`.
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info.
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else {
factory( global );
}
// Pass this if window is not defined yet
}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
// Support: Firefox 18+
// Can't be in strict mode, several libs including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
//"use strict";
var deletedIds = [];
var document = window.document;
var slice = deletedIds.slice;
var concat = deletedIds.concat;
var push = deletedIds.push;
var indexOf = deletedIds.indexOf;
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var support = {};
var
version = "1.12.4",
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init( selector, context );
},
// Support: Android<4.1, IE<9
// Make sure we trim BOM and NBSP
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num != null ?
// Return just the one element from the set
( num < 0 ? this[ num + this.length ] : this[ num ] ) :
// Return all the elements in a clean array
slice.call( this );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// 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;
},
// Execute a callback for every element in the matched set.
each: function( callback ) {
return jQuery.each( this, callback );
},
map: function( callback ) {
return this.pushStack( jQuery.map( this, function( elem, i ) {
return callback.call( elem, i, elem );
} ) );
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] );
},
end: function() {
return this.prevObject || this.constructor();
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: deletedIds.sort,
splice: deletedIds.splice
};
jQuery.extend = jQuery.fn.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;
// skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// 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 ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( ( options = arguments[ i ] ) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
( copyIsArray = jQuery.isArray( copy ) ) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray( src ) ? src : [];
} else {
clone = src && jQuery.isPlainObject( src ) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend( {
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
// Assume jQuery is ready without the ready module
isReady: true,
error: function( msg ) {
throw new Error( msg );
},
noop: function() {},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type( obj ) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type( obj ) === "array";
},
isWindow: function( obj ) {
/* jshint eqeqeq: false */
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
// adding 1 corrects loss of precision from parseFloat (#15100)
var realStringObj = obj && obj.toString();
return !jQuery.isArray( obj ) && ( realStringObj - parseFloat( realStringObj ) + 1 ) >= 0;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
isPlainObject: function( obj ) {
var key;
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call( obj, "constructor" ) &&
!hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Support: IE<9
// Handle iteration over inherited properties before own properties.
if ( !support.ownFirst ) {
for ( key in obj ) {
return hasOwn.call( obj, key );
}
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
type: function( obj ) {
if ( obj == null ) {
return obj + "";
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call( obj ) ] || "object" :
typeof obj;
},
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && 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 ); // jscs:ignore requireDotNotation
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
each: function( obj, callback ) {
var length, i = 0;
if ( isArrayLike( obj ) ) {
length = obj.length;
for ( ; i < length; i++ ) {
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
break;
}
}
} else {
for ( i in obj ) {
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
break;
}
}
}
return obj;
},
// Support: Android<4.1, IE<9
trim: function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArrayLike( Object( arr ) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( indexOf ) {
return indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var len = +second.length,
j = 0,
i = first.length;
while ( j < len ) {
first[ i++ ] = second[ j++ ];
}
// Support: IE<9
// Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists)
if ( len !== len ) {
while ( second[ j ] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, invert ) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
callbackInverse = !callback( elems[ i ], i );
if ( callbackInverse !== callbackExpect ) {
matches.push( elems[ i ] );
}
}
return matches;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var length, value,
i = 0,
ret = [];
// Go through the array, translating each of the items to their new values
if ( isArrayLike( elems ) ) {
length = elems.length;
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
}
// Flatten any nested arrays
return concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var 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 = slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
now: function() {
return +( new Date() );
},
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
} );
// JSHint would error on this code due to the Symbol not being defined in ES5.
// Defining this global in .jshintrc would create a danger of using the global
// unguarded in another place, it seems safer to just disable JSHint for these
// three lines.
/* jshint ignore: start */
if ( typeof Symbol === "function" ) {
jQuery.fn[ Symbol.iterator ] = deletedIds[ Symbol.iterator ];
}
/* jshint ignore: end */
// Populate the class2type map
jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
function( i, name ) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
} );
function isArrayLike( obj ) {
// Support: iOS 8.2 (not reproducible in simulator)
// `in` check used to prevent JIT error (gh-2145)
// hasOwn isn't used here due to false negatives
// regarding Nodelist length in IE
var length = !!obj && "length" in obj && obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
* Sizzle CSS Selector Engine v2.2.1
* http://sizzlejs.com/
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2015-10-17
*/
(function( window ) {
var i,
support,
Expr,
getText,
isXML,
tokenize,
compile,
select,
outermostContext,
sortInput,
hasDuplicate,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + 1 * new Date(),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
}
return 0;
},
// General-purpose constants
MAX_NEGATIVE = 1 << 31,
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf as it's faster than native
// http://jsperf.com/thor-indexof-vs-for/5
indexOf = function( list, elem ) {
var i = 0,
len = list.length;
for ( ; i < len; i++ ) {
if ( list[i] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +
// Operator (capture 2)
"*([*^$|!~]?=)" + whitespace +
// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
"*\\]",
pseudos = ":(" + identifier + ")(?:\\((" +
// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
// 1. quoted (capture 3; capture 4 or capture 5)
"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
// 2. simple (capture 6)
"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
// 3. anything else (capture 2)
".*" +
")\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rwhitespace = new RegExp( whitespace + "+", "g" ),
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + identifier + ")" ),
"CLASS": new RegExp( "^\\.(" + identifier + ")" ),
"TAG": new RegExp( "^(" + identifier + "|[*])" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rsibling = /[+~]/,
rescape = /'|\\/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox<24
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
high < 0 ?
// BMP codepoint
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
},
// Used for iframes
// See setDocument()
// Removing the function wrapper causes a "Permission Denied"
// error in IE
unloadHandler = function() {
setDocument();
};
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var m, i, elem, nid, nidselect, match, groups, newSelector,
newContext = context && context.ownerDocument,
// nodeType defaults to 9, since context defaults to document
nodeType = context ? context.nodeType : 9;
results = results || [];
// Return early from calls with invalid selector or context
if ( typeof selector !== "string" || !selector ||
nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
return results;
}
// Try to shortcut find operations (as opposed to filters) in HTML documents
if ( !seed ) {
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
if ( documentIsHTML ) {
// If the selector is sufficiently simple, try using a "get*By*" DOM method
// (excepting DocumentFragment context, where the methods don't exist)
if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) {
// ID selector
if ( (m = match[1]) ) {
// Document context
if ( nodeType === 9 ) {
if ( (elem = context.getElementById( m )) ) {
// Support: IE, Opera, Webkit
// TODO: identify versions
// getElementById can match elements by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
// Element context
} else {
// Support: IE, Opera, Webkit
// TODO: identify versions
// getElementById can match elements by name instead of ID
if ( newContext && (elem = newContext.getElementById( m )) &&
contains( context, elem ) &&
elem.id === m ) {
results.push( elem );
return results;
}
}
// Type selector
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Class selector
} else if ( (m = match[3]) && support.getElementsByClassName &&
context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// Take advantage of querySelectorAll
if ( support.qsa &&
!compilerCache[ selector + " " ] &&
(!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
if ( nodeType !== 1 ) {
newContext = context;
newSelector = selector;
// qSA looks outside Element context, which is not what we want
// Thanks to Andrew Dupont for this workaround technique
// Support: IE <=8
// Exclude object elements
} else if ( context.nodeName.toLowerCase() !== "object" ) {
// Capture the context ID, setting it first if necessary
if ( (nid = context.getAttribute( "id" )) ) {
nid = nid.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", (nid = expando) );
}
// Prefix every selector in the list
groups = tokenize( selector );
i = groups.length;
nidselect = ridentifier.test( nid ) ? "#" + nid : "[id='" + nid + "']";
while ( i-- ) {
groups[i] = nidselect + " " + toSelector( groups[i] );
}
newSelector = groups.join( "," );
// Expand context for sibling selectors
newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||
context;
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch ( qsaError ) {
} finally {
if ( nid === expando ) {
context.removeAttribute( "id" );
}
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Create key-value caches of limited size
* @returns {function(string, object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key + " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key + " " ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied
*/
function addHandle( attrs, handler ) {
var arr = attrs.split("|"),
i = arr.length;
while ( i-- ) {
Expr.attrHandle[ arr[i] ] = handler;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Checks a node for validity as a Sizzle context
* @param {Element|Object=} context
* @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
*/
function testContext( context ) {
return context && typeof context.getElementsByTagName !== "undefined" && context;
}
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Detects XML nodes
* @param {Element|Object} elem An element or a document
* @returns {Boolean} True iff elem is a non-HTML XML node
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var hasCompare, parent,
doc = node ? node.ownerDocument || node : preferredDoc;
// Return early if doc is invalid or already selected
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Update global variables
document = doc;
docElem = document.documentElement;
documentIsHTML = !isXML( document );
// Support: IE 9-11, Edge
// Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
if ( (parent = document.defaultView) && parent.top !== parent ) {
// Support: IE 11
if ( parent.addEventListener ) {
parent.addEventListener( "unload", unloadHandler, false );
// Support: IE 9 - 10 only
} else if ( parent.attachEvent ) {
parent.attachEvent( "onunload", unloadHandler );
}
}
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties
// (excepting IE8 booleans)
support.attributes = assert(function( div ) {
div.className = "i";
return !div.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( div ) {
div.appendChild( document.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Support: IE<9
support.getElementsByClassName = rnative.test( document.getElementsByClassName );
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( div ) {
docElem.appendChild( div ).id = expando;
return !document.getElementsByName || !document.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
var m = context.getElementById( id );
return m ? [ m ] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== "undefined" &&
elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== "undefined" ) {
return context.getElementsByTagName( tag );
// DocumentFragment nodes don't have gEBTN
} else if ( support.qsa ) {
return context.querySelectorAll( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
// By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( document.querySelectorAll )) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
docElem.appendChild( div ).innerHTML = "<a id='" + expando + "'></a>" +
"<select id='" + expando + "-\r\\' msallowcapture=''>" +
"<option selected=''></option></select>";
// Support: IE8, Opera 11-12.16
// Nothing should be selected when empty strings follow ^= or $= or *=
// The test attribute must be unknown in Opera but "safe" for WinRT
// http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
if ( div.querySelectorAll("[msallowcapture^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+
if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
rbuggyQSA.push("~=");
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
// Support: Safari 8+, iOS 8+
// https://bugs.webkit.org/show_bug.cgi?id=136851
// In-page `selector#id sibing-combinator selector` fails
if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) {
rbuggyQSA.push(".#.+[+~]");
}
});
assert(function( div ) {
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = document.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "name", "D" );
// Support: IE8
// Enforce case-sensitivity of name attribute
if ( div.querySelectorAll("[name=d]").length ) {
rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
/* Contains
---------------------------------------------------------------------- */
hasCompare = rnative.test( docElem.compareDocumentPosition );
// Element contains another
// Purposefully self-exclusive
// As in, an element does not contain itself
contains = hasCompare || rnative.test( docElem.contains ) ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Document order sorting
sortOrder = hasCompare ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
// Sort on method existence if only one input has compareDocumentPosition
var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
if ( compare ) {
return compare;
}
// Calculate position if both inputs belong to the same document
compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
a.compareDocumentPosition( b ) :
// Otherwise we know they are disconnected
1;
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
return -1;
}
if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
} :
function( a, b ) {
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Parentless nodes are either documents or disconnected
if ( !aup || !bup ) {
return a === document ? -1 :
b === document ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return document;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
!compilerCache[ expr + " " ] &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch (e) {}
}
return Sizzle( expr, document, null, [ elem ] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined;
return val !== undefined ?
val :
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
// Clear input after sorting to release objects
// See https://github.com/jquery/sizzle/pull/225
sortInput = null;
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
while ( (node = elem[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 (jQuery #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[6] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] ) {
match[2] = match[4] || match[5] || "";
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, uniqueCache, outerCache, node, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType,
diff = false;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ?
node.nodeName.toLowerCase() === name :
node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
// ...in a gzip-friendly way
node = parent;
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
cache = uniqueCache[ type ] || [];
nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
diff = nodeIndex && cache[ 2 ];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
uniqueCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
} else {
// Use previously-cached element index if available
if ( useCache ) {
// ...in a gzip-friendly way
node = elem;
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
cache = uniqueCache[ type ] || [];
nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
diff = nodeIndex;
}
// xml :nth-child(...)
// or :nth-last-child(...) or :nth(-last)?-of-type(...)
if ( diff === false ) {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ?
node.nodeName.toLowerCase() === name :
node.nodeType === 1 ) &&
++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
uniqueCache[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
// Don't keep the element (issue #299)
input[0] = null;
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
text = text.replace( runescape, funescape );
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
// but not by others (comment: 8; processing instruction: 7; etc.)
// nodeType < 6 works because attributes (2) do not appear as children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeType < 6 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
// Support: IE<8
// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( (tokens = []) );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
};
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var oldCache, uniqueCache, outerCache,
newCache = [ dirruns, doneName ];
// We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {});
if ( (oldCache = uniqueCache[ dir ]) &&
oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
// Assign to newCache so results back-propagate to previous elements
return (newCache[ 2 ] = oldCache[ 2 ]);
} else {
// Reuse newcache so results back-propagate to previous elements
uniqueCache[ dir ] = newCache;
// A match means we're done; a fail means we have to keep checking
if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
// Avoid hanging onto element (issue #299)
checkContext = null;
return ret;
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, outermost ) {
var elem, j, matcher,
matchedCount = 0,
i = "0",
unmatched = seed && [],
setMatched = [],
contextBackup = outermostContext,
// We must always have either seed elements or outermost context
elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
len = elems.length;
if ( outermost ) {
outermostContext = context === document || context || outermost;
}
// Add elements passing elementMatchers directly to results
// Support: IE<9, Safari
// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
if ( !context && elem.ownerDocument !== document ) {
setDocument( elem );
xml = !documentIsHTML;
}
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context || document, xml) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// `i` is now the count of elements visited above, and adding it to `matchedCount`
// makes the latter nonnegative.
matchedCount += i;
// Apply set filters to unmatched elements
// NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
// equals `i`), unless we didn't visit _any_ elements in the above loop because we have
// no element matchers and no seed.
// Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
// case, which will result in a "00" `matchedCount` that differs from `i` but is also
// numerically zero.
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !match ) {
match = tokenize( selector );
}
i = match.length;
while ( i-- ) {
cached = matcherFromTokens( match[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
// Save selector and tokenization
cached.selector = selector;
}
return cached;
};
/**
* A low-level selection function that works with Sizzle's compiled
* selector functions
* @param {String|Function} selector A selector or a pre-compiled
* selector function built with Sizzle.compile
* @param {Element} context
* @param {Array} [results]
* @param {Array} [seed] A set of elements to match against
*/
select = Sizzle.select = function( selector, context, results, seed ) {
var i, tokens, token, type, find,
compiled = typeof selector === "function" && selector,
match = !seed && tokenize( (selector = compiled.selector || selector) );
results = results || [];
// Try to minimize operations if there is only one selector in the list and no seed
// (the latter of which guarantees us context)
if ( match.length === 1 ) {
// Reduce context if the leading compound selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && context.nodeType === 9 && documentIsHTML &&
Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
// Precompiled matchers will still verify ancestry, so step up a level
} else if ( compiled ) {
context = context.parentNode;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
// Compile and execute a filtering function if one is not provided
// Provide `match` to avoid retokenization if we modified the selector above
( compiled || compile( selector, match ) )(
seed,
context,
!documentIsHTML,
results,
!context || rsibling.test( selector ) && testContext( context.parentNode ) || context
);
return results;
};
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Support: Chrome 14-35+
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate;
// Initialize against the default document
setDocument();
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( div1 ) {
// Should return 1, but returns 4 (following)
return div1.compareDocumentPosition( document.createElement("div") ) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild.getAttribute("href") === "#" ;
}) ) {
addHandle( "type|href|height|width", function( elem, name, isXML ) {
if ( !isXML ) {
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
});
}
// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if ( !support.attributes || !assert(function( div ) {
div.innerHTML = "<input/>";
div.firstChild.setAttribute( "value", "" );
return div.firstChild.getAttribute( "value" ) === "";
}) ) {
addHandle( "value", function( elem, name, isXML ) {
if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
});
}
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if ( !assert(function( div ) {
return div.getAttribute("disabled") == null;
}) ) {
addHandle( booleans, function( elem, name, isXML ) {
var val;
if ( !isXML ) {
return elem[ name ] === true ? name.toLowerCase() :
(val = elem.getAttributeNode( name )) && val.specified ?
val.value :
null;
}
});
}
return Sizzle;
})( window );
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[ ":" ] = jQuery.expr.pseudos;
jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
var dir = function( elem, dir, until ) {
var matched = [],
truncate = until !== undefined;
while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) {
if ( elem.nodeType === 1 ) {
if ( truncate && jQuery( elem ).is( until ) ) {
break;
}
matched.push( elem );
}
}
return matched;
};
var siblings = function( n, elem ) {
var matched = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
matched.push( n );
}
}
return matched;
};
var rneedsContext = jQuery.expr.match.needsContext;
var rsingleTag = ( /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/ );
var risSimple = /^.[^:#\[\.,]*$/;
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
} );
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
} );
}
if ( typeof qualifier === "string" ) {
if ( risSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( jQuery.inArray( elem, qualifier ) > -1 ) !== not;
} );
}
jQuery.filter = function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
} ) );
};
jQuery.fn.extend( {
find: function( selector ) {
var i,
ret = [],
self = this,
len = self.length;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter( function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
} ) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ 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 : selector;
return ret;
},
filter: function( selector ) {
return this.pushStack( winnow( this, selector || [], false ) );
},
not: function( selector ) {
return this.pushStack( winnow( this, selector || [], true ) );
},
is: function( selector ) {
return !!winnow(
this,
// 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".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
}
} );
// Initialize a jQuery object
// A central reference to the root jQuery(document)
var rootjQuery,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
init = jQuery.fn.init = function( selector, context, root ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// init accepts an alternate rootjQuery
// so migrate can support jQuery.sub (gh-2101)
root = root || rootjQuery;
// 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
// Intentionally let the error be thrown if parseHTML is not present
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 || root ).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 typeof root.ready !== "undefined" ?
root.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
};
// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;
// Initialize central reference
rootjQuery = jQuery( document );
var rparentsprev = /^(?:parents|prev(?:Until|All))/,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend( {
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter( function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[ i ] ) ) {
return true;
}
}
} );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && ( pos ?
pos.index( cur ) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector( cur, selectors ) ) ) {
matched.push( cur );
break;
}
}
}
return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.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 );
},
add: function( selector, context ) {
return this.pushStack(
jQuery.uniqueSort(
jQuery.merge( this.get(), jQuery( selector, context ) )
)
);
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter( selector )
);
}
} );
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each( {
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return siblings( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return siblings( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
ret = jQuery.uniqueSort( ret );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
ret = ret.reverse();
}
}
return this.pushStack( ret );
};
} );
var rnotwhite = ( /\S+/g );
// Convert String-formatted options into Object-formatted ones
function createOptions( options ) {
var object = {};
jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
} );
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
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,
// Flag to prevent firing
locked,
// Actual callback list
list = [],
// Queue of execution data for repeatable lists
queue = [],
// Index of currently firing callback (modified by add/remove as needed)
firingIndex = -1,
// Fire callbacks
fire = function() {
// Enforce single-firing
locked = options.once;
// Execute callbacks for all pending executions,
// respecting firingIndex overrides and runtime changes
fired = firing = true;
for ( ; queue.length; firingIndex = -1 ) {
memory = queue.shift();
while ( ++firingIndex < list.length ) {
// Run callback and check for early termination
if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false &&
options.stopOnFalse ) {
// Jump to end and forget the data so .add doesn't re-fire
firingIndex = list.length;
memory = false;
}
}
}
// Forget the data if we're done with it
if ( !options.memory ) {
memory = false;
}
firing = false;
// Clean up if we're done firing for good
if ( locked ) {
// Keep an empty list if we have data for future add calls
if ( memory ) {
list = [];
// Otherwise, this object is spent
} else {
list = "";
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// If we have memory from a past run, we should fire after adding
if ( memory && !firing ) {
firingIndex = list.length - 1;
queue.push( memory );
}
( function add( args ) {
jQuery.each( args, function( _, arg ) {
if ( jQuery.isFunction( arg ) ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) {
// Inspect recursively
add( arg );
}
} );
} )( arguments );
if ( memory && !firing ) {
fire();
}
}
return this;
},
// Remove a callback from the list
remove: function() {
jQuery.each( arguments, function( _, arg ) {
var index;
while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
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.length > 0;
},
// Remove all callbacks from the list
empty: function() {
if ( list ) {
list = [];
}
return this;
},
// Disable .fire and .add
// Abort any current/pending executions
// Clear all callbacks and values
disable: function() {
locked = queue = [];
list = memory = "";
return this;
},
disabled: function() {
return !list;
},
// Disable .fire
// Also disable .add unless we have memory (since it would have no effect)
// Abort any pending executions
lock: function() {
locked = true;
if ( !memory ) {
self.disable();
}
return this;
},
locked: function() {
return !!locked;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( !locked ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
queue.push( args );
if ( !firing ) {
fire();
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend( {
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks( "once memory" ), "resolved" ],
[ "reject", "fail", jQuery.Callbacks( "once memory" ), "rejected" ],
[ "notify", "progress", jQuery.Callbacks( "memory" ) ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred( function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var 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()
.progress( newDefer.notify )
.done( newDefer.resolve )
.fail( newDefer.reject );
} else {
newDefer[ tuple[ 0 ] + "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;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = 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 ? 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()
.progress( updateFunc( i, progressContexts, progressValues ) )
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
} );
// The deferred used on DOM ready
var readyList;
jQuery.fn.ready = function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
};
jQuery.extend( {
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// 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.triggerHandler ) {
jQuery( document ).triggerHandler( "ready" );
jQuery( document ).off( "ready" );
}
}
} );
/**
* Clean-up method for dom ready events
*/
function detach() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed );
window.removeEventListener( "load", completed );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
}
/**
* The ready event handler and self cleanup method
*/
function completed() {
// readyState === "complete" is good enough for us to call the dom ready in oldIE
if ( document.addEventListener ||
window.event.type === "load" ||
document.readyState === "complete" ) {
detach();
jQuery.ready();
}
}
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called
// after the browser event has already occurred.
// Support: IE6-10
// Older IE sometimes signals "interactive" too soon
if ( document.readyState === "complete" ||
( document.readyState !== "loading" && !document.documentElement.doScroll ) ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
window.setTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch ( e ) {}
if ( top && top.doScroll ) {
( function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll( "left" );
} catch ( e ) {
return window.setTimeout( doScrollCheck, 50 );
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
} )();
}
}
}
return readyList.promise( obj );
};
// Kick off the DOM ready check even if the user does not
jQuery.ready.promise();
// Support: IE<9
// Iteration over object's inherited properties before its own
var i;
for ( i in jQuery( support ) ) {
break;
}
support.ownFirst = i === "0";
// Note: most support tests are defined in their respective modules.
// false until the test is run
support.inlineBlockNeedsLayout = false;
// Execute ASAP in case we need to set body.style.zoom
jQuery( function() {
// Minified: var a,b,c,d
var val, div, body, container;
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body || !body.style ) {
// Return for frameset docs that don't have a body
return;
}
// Setup
div = document.createElement( "div" );
container = document.createElement( "div" );
container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
body.appendChild( container ).appendChild( div );
if ( typeof div.style.zoom !== "undefined" ) {
// Support: IE<8
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
div.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1";
support.inlineBlockNeedsLayout = val = div.offsetWidth === 3;
if ( val ) {
// Prevent IE 6 from affecting layout for positioned elements #11048
// Prevent IE from shrinking the body in IE 7 mode #12869
// Support: IE<8
body.style.zoom = 1;
}
}
body.removeChild( container );
} );
( function() {
var div = document.createElement( "div" );
// Support: IE<9
support.deleteExpando = true;
try {
delete div.test;
} catch ( e ) {
support.deleteExpando = false;
}
// Null elements to avoid leaks in IE.
div = null;
} )();
var acceptData = function( elem ) {
var noData = jQuery.noData[ ( elem.nodeName + " " ).toLowerCase() ],
nodeType = +elem.nodeType || 1;
// Do not set data on non-element DOM nodes because it will not be cleared (#8335).
return nodeType !== 1 && nodeType !== 9 ?
false :
// Nodes accept data unless otherwise specified; rejection can be conditional
!noData || noData !== true && elem.getAttribute( "classid" ) === noData;
};
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
rmultiDash = /([A-Z])/g;
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch ( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[ name ] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
function internalData( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !acceptData( elem ) ) {
return;
}
var ret, thisCache,
internalKey = jQuery.expando,
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( ( !id || !cache[ id ] || ( !pvt && !cache[ id ].data ) ) &&
data === undefined && typeof name === "string" ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
// Avoid exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
cache[ id ] = isNode ? {} : { toJSON: jQuery.noop };
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( typeof name === "string" ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
}
function internalRemoveData( elem, name, pvt ) {
if ( !acceptData( elem ) ) {
return;
}
var thisCache, i,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split( " " );
}
}
} else {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = name.concat( jQuery.map( name, jQuery.camelCase ) );
}
i = name.length;
while ( i-- ) {
delete thisCache[ name[ i ] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( pvt ? !isEmptyDataObject( thisCache ) : !jQuery.isEmptyObject( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
/* jshint eqeqeq: false */
} else if ( support.deleteExpando || cache != cache.window ) {
/* jshint eqeqeq: true */
delete cache[ id ];
// When all else fails, undefined
} else {
cache[ id ] = undefined;
}
}
jQuery.extend( {
cache: {},
// The following elements (space-suffixed to avoid Object.prototype collisions)
// throw uncatchable exceptions if you attempt to set expando properties
noData: {
"applet ": true,
"embed ": true,
// ...but Flash objects (which have this classid) *can* handle expandos
"object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[ jQuery.expando ] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( fullname, email, username ) {
return internalData( fullname, email, username );
},
removeData: function( elem, name ) {
return internalRemoveData( elem, name );
},
// For internal use only.
_data: function( elem, name, data ) {
return internalData( elem, name, data, true );
},
_removeData: function( elem, name ) {
return internalRemoveData( elem, name, true );
}
} );
jQuery.fn.extend( {
data: function( key, value ) {
var i, name, data,
elem = this[ 0 ],
attrs = elem && elem.attributes;
// Special expections of .data basically thwart jQuery.access,
// so implement the relevant behavior ourselves
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
i = attrs.length;
while ( i-- ) {
// Support: IE11+
// The attrs elements can be null (#14894)
if ( attrs[ i ] ) {
name = attrs[ i ].name;
if ( name.indexOf( "data-" ) === 0 ) {
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 arguments.length > 1 ?
// Sets one value
this.each( function() {
jQuery.data( this, key, value );
} ) :
// Gets one value
// Try to fetch any internally stored data first
elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined;
},
removeData: function( key ) {
return this.each( function() {
jQuery.removeData( this, key );
} );
}
} );
jQuery.extend( {
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray( data ) ) {
queue = jQuery._data( elem, type, jQuery.makeArray( data ) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object,
// or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks( "once memory" ).add( function() {
jQuery._removeData( elem, type + "queue" );
jQuery._removeData( elem, key );
} )
} );
}
} );
jQuery.fn.extend( {
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[ 0 ], type );
}
return data === undefined ?
this :
this.each( function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[ 0 ] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
} );
},
dequeue: function( type ) {
return this.each( function() {
jQuery.dequeue( this, type );
} );
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while ( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
} );
( function() {
var shrinkWrapBlocksVal;
support.shrinkWrapBlocks = function() {
if ( shrinkWrapBlocksVal != null ) {
return shrinkWrapBlocksVal;
}
// Will be changed later if needed.
shrinkWrapBlocksVal = false;
// Minified: var b,c,d
var div, body, container;
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body || !body.style ) {
// Test fired too early or in an unsupported environment, exit.
return;
}
// Setup
div = document.createElement( "div" );
container = document.createElement( "div" );
container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
body.appendChild( container ).appendChild( div );
// Support: IE6
// Check if elements with layout shrink-wrap their children
if ( typeof div.style.zoom !== "undefined" ) {
// Reset CSS: box-sizing; display; margin; border
div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
"box-sizing:content-box;display:block;margin:0;border:0;" +
"padding:1px;width:1px;zoom:1";
div.appendChild( document.createElement( "div" ) ).style.width = "5px";
shrinkWrapBlocksVal = div.offsetWidth !== 3;
}
body.removeChild( container );
return shrinkWrapBlocksVal;
};
} )();
var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source;
var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" );
var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
var isHidden = function( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" ||
!jQuery.contains( elem.ownerDocument, elem );
};
function adjustCSS( elem, prop, valueParts, tween ) {
var adjusted,
scale = 1,
maxIterations = 20,
currentValue = tween ?
function() { return tween.cur(); } :
function() { return jQuery.css( elem, prop, "" ); },
initial = currentValue(),
unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) &&
rcssNum.exec( jQuery.css( elem, prop ) );
if ( initialInUnit && initialInUnit[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || initialInUnit[ 3 ];
// Make sure we update the tween properties later on
valueParts = valueParts || [];
// Iteratively approximate from a nonzero starting point
initialInUnit = +initial || 1;
do {
// If previous iteration zeroed out, double until we get *something*.
// Use string for doubling so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
initialInUnit = initialInUnit / scale;
jQuery.style( elem, prop, initialInUnit + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// Break the loop if scale is unchanged or perfect, or if we've just had enough.
} while (
scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations
);
}
if ( valueParts ) {
initialInUnit = +initialInUnit || +initial || 0;
// Apply relative offset (+=/-=) if specified
adjusted = valueParts[ 1 ] ?
initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] :
+valueParts[ 2 ];
if ( tween ) {
tween.unit = unit;
tween.start = initialInUnit;
tween.end = adjusted;
}
}
return adjusted;
}
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var 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 ) {
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;
};
var rcheckableType = ( /^(?:checkbox|radio)$/i );
var rtagName = ( /<([\w:-]+)/ );
var rscriptType = ( /^$|\/(?:java|ecma)script/i );
var rleadingWhitespace = ( /^\s+/ );
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|" +
"details|dialog|figcaption|figure|footer|header|hgroup|main|" +
"mark|meter|nav|output|picture|progress|section|summary|template|time|video";
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
( function() {
var div = document.createElement( "div" ),
fragment = document.createDocumentFragment(),
input = document.createElement( "input" );
// Setup
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// IE strips leading whitespace when .innerHTML is used
support.leadingWhitespace = div.firstChild.nodeType === 3;
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
support.tbody = !div.getElementsByTagName( "tbody" ).length;
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
support.htmlSerialize = !!div.getElementsByTagName( "link" ).length;
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
support.html5Clone =
document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav></:nav>";
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
input.type = "checkbox";
input.checked = true;
fragment.appendChild( input );
support.appendChecked = input.checked;
// Make sure textarea (and checkbox) defaultValue is properly cloned
// Support: IE6-IE11+
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
// #11217 - WebKit loses check when the name is after the checked attribute
fragment.appendChild( div );
// Support: Windows Web Apps (WWA)
// `name` and `type` must use .setAttribute for WWA (#14901)
input = document.createElement( "input" );
input.setAttribute( "type", "radio" );
input.setAttribute( "checked", "checked" );
input.setAttribute( "name", "t" );
div.appendChild( input );
// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
// old WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<9
// Cloned elements keep attachEvent handlers, we use addEventListener on IE9+
support.noCloneEvent = !!div.addEventListener;
// Support: IE<9
// Since attributes and properties are the same in IE,
// cleanData must set properties to undefined rather than use removeAttribute
div[ jQuery.expando ] = 1;
support.attributes = !div.getAttribute( jQuery.expando );
} )();
// We have to close these tags to support XHTML (#13200)
var wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
area: [ 1, "<map>", "</map>" ],
// Support: IE8
param: [ 1, "<object>", "</object>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
_default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
};
// Support: IE8-IE9
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
function getAll( context, tag ) {
var elems, elem,
i = 0,
found = typeof context.getElementsByTagName !== "undefined" ?
context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== "undefined" ?
context.querySelectorAll( tag || "*" ) :
undefined;
if ( !found ) {
for ( found = [], elems = context.childNodes || context;
( elem = elems[ i ] ) != null;
i++
) {
if ( !tag || jQuery.nodeName( elem, tag ) ) {
found.push( elem );
} else {
jQuery.merge( found, getAll( elem, tag ) );
}
}
}
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], found ) :
found;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var elem,
i = 0;
for ( ; ( elem = elems[ i ] ) != null; i++ ) {
jQuery._data(
elem,
"globalEval",
!refElements || jQuery._data( refElements[ i ], "globalEval" )
);
}
}
var rhtml = /<|&#?\w+;/,
rtbody = /<tbody/i;
function fixDefaultChecked( elem ) {
if ( rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
function buildFragment( elems, context, scripts, selection, ignored ) {
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 ] + jQuery.htmlPrefilter( elem ) + 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 ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[ 0 ] ) );
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !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 ( !support.appendChecked ) {
jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
}
i = 0;
while ( ( elem = nodes[ i++ ] ) ) {
// Skip elements already in the context collection (trac-4087)
if ( selection && jQuery.inArray( elem, selection ) > -1 ) {
if ( ignored ) {
ignored.push( elem );
}
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;
}
( function() {
var i, eventName,
div = document.createElement( "div" );
// Support: IE<9 (lack submit/change bubble), Firefox (lack focus(in | out) events)
for ( i in { submit: true, change: true, focusin: true } ) {
eventName = "on" + i;
if ( !( support[ i ] = eventName in window ) ) {
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
div.setAttribute( eventName, "t" );
support[ i ] = div.attributes[ eventName ].expando === false;
}
}
// Null elements to avoid leaks in IE.
div = null;
} )();
var rformElems = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
// Support: IE9
// See #13393 for more info
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
function on( elem, types, selector, data, fn, one ) {
var origFn, type;
// 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 ) {
on( elem, type, selector, data, types[ type ], one );
}
return elem;
}
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 elem;
}
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 elem.each( function() {
jQuery.event.add( this, types, fn, data, selector );
} );
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var tmp, events, t, handleObjIn,
special, eventHandle, handleObj,
handlers, type, namespaces, origType,
elemData = jQuery._data( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !( events = elemData.events ) ) {
events = elemData.events = {};
}
if ( !( eventHandle = elemData.handle ) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" &&
( !e || jQuery.event.triggered !== e.type ) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak
// with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[ t ] ) || [];
type = origType = tmp[ 1 ];
namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend( {
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join( "." )
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !( handlers = events[ type ] ) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup ||
special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, handleObj, tmp,
origCount, t, events,
special, handlers, type,
namespaces, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !( events = elemData.events ) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[ t ] ) || [];
type = origType = tmp[ 1 ];
namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[ 2 ] &&
new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector ||
selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown ||
special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery._removeData( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var handle, ontype, cur,
bubbleType, special, tmp, i,
eventPath = [ elem || document ],
type = hasOwn.call( event, "type" ) ? event.type : event,
namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "." ) > -1 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split( "." );
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf( ":" ) < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join( "." );
event.rnamespace = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === ( elem.ownerDocument || document ) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] &&
jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && acceptData( cur ) ) {
event.result = handle.apply( cur, data );
if ( event.result === false ) {
event.preventDefault();
}
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if (
( !special._default ||
special._default.apply( eventPath.pop(), data ) === false
) && acceptData( elem )
) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
try {
elem[ type ]();
} catch ( e ) {
// IE<9 dies on focus/blur to hidden element (#1486,#12518)
// only reproducible on winXP IE8 native, not IE9 in IE8 mode
}
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, j, ret, matched, handleObj,
handlerQueue = [],
args = slice.call( arguments ),
handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[ 0 ] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( ( handleObj = matched.handlers[ j++ ] ) &&
!event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or 2) have namespace(s)
// a subset or equal to those in the bound event (both can have no namespace).
if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle ||
handleObj.handler ).apply( matched.elem, args );
if ( ret !== undefined ) {
if ( ( event.result = ret ) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var i, matches, sel, handleObj,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Support (at least): Chrome, IE9
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
//
// Support: Firefox<=42+
// Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343)
if ( delegateCount && cur.nodeType &&
( event.type !== "click" || isNaN( event.button ) || event.button < 1 ) ) {
/* jshint eqeqeq: false */
for ( ; cur != this; cur = cur.parentNode || this ) {
/* jshint eqeqeq: true */
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && ( cur.disabled !== true || event.type !== "click" ) ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) > -1 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push( { elem: cur, handlers: matches } );
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push( { elem: this, handlers: handlers.slice( delegateCount ) } );
}
return handlerQueue;
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: IE<9
// Fix target property (#1925)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Support: Safari 6-8+
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Support: IE<9
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
event.metaKey = !!event.metaKey;
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: ( "altKey bubbles cancelable ctrlKey currentTarget detail eventPhase " +
"metaKey relatedTarget shiftKey target timeStamp view which" ).split( " " ),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split( " " ),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: ( "button buttons clientX clientY fromElement offsetX offsetY " +
"pageX pageY screenX screenY toElement" ).split( " " ),
filter: function( event, original ) {
var body, eventDoc, doc,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX +
( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY +
( doc && doc.scrollTop || body && body.scrollTop || 0 ) -
( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ?
original.toElement :
fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
try {
this.focus();
return false;
} catch ( e ) {
// Support: IE<9
// If we error on focus to hidden element (#1486, #12518),
// let .trigger() run the handlers
}
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Support: Firefox 20+
// Firefox doesn't alert if the returnValue field is not set.
if ( event.result !== undefined && event.originalEvent ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
// Piggyback on a donor event to simulate a different one
simulate: function( type, elem, event ) {
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true
// Previously, `originalEvent: {}` was set here, so stopPropagation call
// would not be triggered on donor event, since in our own
// jQuery.event.stopPropagation function we had a check for existence of
// originalEvent.stopPropagation method, so, consequently it would be a noop.
//
// Guard for simulated events was moved to jQuery.event.stopPropagation function
// since `originalEvent` should point to the original event for the
// constancy with other events and for more focused logic
}
);
jQuery.event.trigger( e, null, elem );
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
// This "if" is needed for plain objects
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event,
// to properly expose it to GC
if ( typeof elem[ name ] === "undefined" ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !( this instanceof jQuery.Event ) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = src.defaultPrevented ||
src.defaultPrevented === undefined &&
// Support: IE < 9, Android < 4.0
src.returnValue === false ?
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.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
constructor: jQuery.Event,
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
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;
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( !e || this.isSimulated ) {
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;
},
stopImmediatePropagation: function() {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
if ( e && e.stopImmediatePropagation ) {
e.stopImmediatePropagation();
}
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
// so that event delegation works in jQuery.
// Do the same for pointerenter/pointerleave and pointerover/pointerout
//
// Support: Safari 7 only
// Safari sends mouseenter too often; see:
// https://code.google.com/p/chromium/issues/detail?id=470258
// for the description of the bug (it existed in older Chrome versions as well).
jQuery.each( {
mouseenter: "mouseover",
mouseleave: "mouseout",
pointerenter: "pointerover",
pointerleave: "pointerout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mouseenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
} );
// IE submit delegation
if ( !support.submit ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ?
// Support: IE <=8
// We use jQuery.prop instead of elem.form
// to allow fixing the IE8 delegated submit issue (gh-2332)
// by 3rd party polyfills/workarounds.
jQuery.prop( elem, "form" ) :
undefined;
if ( form && !jQuery._data( form, "submit" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submitBubble = true;
} );
jQuery._data( form, "submit", true );
}
} );
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submitBubble ) {
delete event._submitBubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !support.change ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._justChanged = true;
}
} );
jQuery.event.add( this, "click._change", function( event ) {
if ( this._justChanged && !event.isTrigger ) {
this._justChanged = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event );
} );
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "change" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event );
}
} );
jQuery._data( elem, "change", true );
}
} );
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger ||
( elem.type !== "radio" && elem.type !== "checkbox" ) ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Support: Firefox
// Firefox doesn't have focus(in | out) events
// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787
//
// Support: Chrome, Safari
// focus(in | out) events fire after focus & blur events,
// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order
// Related ticket - https://code.google.com/p/chromium/issues/detail?id=449857
if ( !support.focusin ) {
jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler on the document while someone wants focusin/focusout
var handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) );
};
jQuery.event.special[ fix ] = {
setup: function() {
var doc = this.ownerDocument || this,
attaches = jQuery._data( doc, fix );
if ( !attaches ) {
doc.addEventListener( orig, handler, true );
}
jQuery._data( doc, fix, ( attaches || 0 ) + 1 );
},
teardown: function() {
var doc = this.ownerDocument || this,
attaches = jQuery._data( doc, fix ) - 1;
if ( !attaches ) {
doc.removeEventListener( orig, handler, true );
jQuery._removeData( doc, fix );
} else {
jQuery._data( doc, fix, attaches );
}
}
};
} );
}
jQuery.fn.extend( {
on: function( types, selector, data, fn ) {
return on( this, types, selector, data, fn );
},
one: function( types, selector, data, fn ) {
return on( this, types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ?
handleObj.origType + "." + handleObj.namespace :
handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each( function() {
jQuery.event.remove( this, types, fn, selector );
} );
},
trigger: function( type, data ) {
return this.each( function() {
jQuery.event.trigger( type, data, this );
} );
},
triggerHandler: function( type, data ) {
var elem = this[ 0 ];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
} );
var rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rnoshimcache = new RegExp( "<(?:" + nodeNames + ")[\\s/>]", "i" ),
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,
// Support: IE 10-11, Edge 10240+
// In IE/Edge using regex groups here causes severe slowdowns.
// See https://connect.microsoft.com/IE/feedback/details/1736512/
rnoInnerhtml = /<script|<style|<link/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement( "div" ) );
// Support: IE<8
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName( "tbody" )[ 0 ] ||
elem.appendChild( elem.ownerDocument.createElement( "tbody" ) ) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = ( jQuery.find.attr( elem, "type" ) !== null ) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[ 1 ];
} else {
elem.removeAttribute( "type" );
}
return elem;
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function fixCloneNodeIssues( src, dest ) {
var nodeName, e, data;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 copies events bound via attachEvent when using cloneNode.
if ( !support.noCloneEvent && dest[ jQuery.expando ] ) {
data = jQuery._data( dest );
for ( e in data.events ) {
jQuery.removeEvent( dest, e, data.handle );
}
// Event data gets referenced instead of copied if the expando gets copied too
dest.removeAttribute( jQuery.expando );
}
// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
if ( nodeName === "script" && dest.text !== src.text ) {
disableScript( dest ).text = src.text;
restoreScript( dest );
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
} else if ( nodeName === "object" ) {
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( support.html5Clone && ( src.innerHTML && !jQuery.trim( dest.innerHTML ) ) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.defaultSelected = dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
function domManip( collection, args, callback, ignored ) {
// Flatten any nested arrays
args = concat.apply( [], args );
var first, node, hasScripts,
scripts, doc, fragment,
i = 0,
l = collection.length,
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" &&
!support.checkClone && rchecked.test( value ) ) ) {
return collection.each( function( index ) {
var self = collection.eq( index );
if ( isFunction ) {
args[ 0 ] = value.call( this, index, self.html() );
}
domManip( self, args, callback, ignored );
} );
}
if ( l ) {
fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
// Require either new content or an interest in ignored elements to invoke the callback
if ( first || ignored ) {
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 ) {
// Support: Android<4.1, PhantomJS<2
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( collection[ 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 ) {
// Optional AJAX dependency, but won't run scripts if not present
if ( jQuery._evalUrl ) {
jQuery._evalUrl( node.src );
}
} else {
jQuery.globalEval(
( node.text || node.textContent || node.innerHTML || "" )
.replace( rcleanScript, "" )
);
}
}
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
}
}
return collection;
}
function remove( elem, selector, keepData ) {
var node,
elems = selector ? jQuery.filter( selector, elem ) : elem,
i = 0;
for ( ; ( node = elems[ i ] ) != null; i++ ) {
if ( !keepData && node.nodeType === 1 ) {
jQuery.cleanData( getAll( node ) );
}
if ( node.parentNode ) {
if ( keepData && jQuery.contains( node.ownerDocument, node ) ) {
setGlobalEval( getAll( node, "script" ) );
}
node.parentNode.removeChild( node );
}
}
return elem;
}
jQuery.extend( {
htmlPrefilter: function( html ) {
return html.replace( rxhtmlTag, "<$1></$2>" );
},
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var destElements, node, clone, i, srcElements,
inPage = jQuery.contains( elem.ownerDocument, elem );
if ( 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 ( ( !support.noCloneEvent || !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;
},
cleanData: function( elems, /* internal */ forceAcceptData ) {
var elem, type, id, data,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
attributes = support.attributes,
special = jQuery.event.special;
for ( ; ( elem = elems[ i ] ) != null; i++ ) {
if ( forceAcceptData || 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 ];
// Support: IE<9
// IE does not allow us to delete expando properties from nodes
// IE creates expando attributes along with the property
// IE does not have a removeAttribute function on Document nodes
if ( !attributes && typeof elem.removeAttribute !== "undefined" ) {
elem.removeAttribute( internalKey );
// Webkit & Blink performance suffers when deleting properties
// from DOM nodes, so set to undefined instead
// https://code.google.com/p/chromium/issues/detail?id=378607
} else {
elem[ internalKey ] = undefined;
}
deletedIds.push( id );
}
}
}
}
}
} );
jQuery.fn.extend( {
// Keep domManip exposed until 3.0 (gh-2225)
domManip: domManip,
detach: function( selector ) {
return remove( this, selector, true );
},
remove: function( selector ) {
return remove( this, selector );
},
text: function( value ) {
return 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 );
},
append: function() {
return domManip( this, arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
} );
},
prepend: function() {
return domManip( this, arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
} );
},
before: function() {
return domManip( this, arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
} );
},
after: function() {
return domManip( this, arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
} );
},
empty: function() {
var elem,
i = 0;
for ( ; ( elem = this[ i ] ) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( 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;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function() {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
} );
},
html: function( value ) {
return 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 ) &&
( support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
value = jQuery.htmlPrefilter( value );
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 );
},
replaceWith: function() {
var ignored = [];
// Make the changes, replacing each non-ignored context element with the new content
return domManip( this, arguments, function( elem ) {
var parent = this.parentNode;
if ( jQuery.inArray( this, ignored ) < 0 ) {
jQuery.cleanData( getAll( this ) );
if ( parent ) {
parent.replaceChild( elem, this );
}
}
// Force callback invocation
}, ignored );
}
} );
jQuery.each( {
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
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()
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
} );
var iframe,
elemdisplay = {
// Support: Firefox
// We have to pre-define these values for FF (#10227)
HTML: "block",
BODY: "block"
};
/**
* Retrieve the actual display of a element
* @param {String} name nodeName of the element
* @param {Object} doc Document object
*/
// Called only from within defaultDisplay
function actualDisplay( name, doc ) {
var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
display = jQuery.css( elem[ 0 ], "display" );
// We don't have any data stored on the element,
// so use "detach" method as fast way to get rid of the element
elem.detach();
return display;
}
/**
* Try to determine the default display value of an element
* @param {String} nodeName
*/
function defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = ( iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" ) )
.appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[ 0 ].contentWindow || iframe[ 0 ].contentDocument ).document;
// Support: IE
doc.write();
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
var rmargin = ( /^margin/ );
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
var 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;
};
var documentElement = document.documentElement;
( function() {
var pixelPositionVal, pixelMarginRightVal, boxSizingReliableVal,
reliableHiddenOffsetsVal, reliableMarginRightVal, reliableMarginLeftVal,
container = document.createElement( "div" ),
div = document.createElement( "div" );
// Finish early in limited (non-browser) environments
if ( !div.style ) {
return;
}
div.style.cssText = "float:left;opacity:.5";
// Support: IE<9
// Make sure that element opacity exists (as opposed to filter)
support.opacity = div.style.opacity === "0.5";
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
support.cssFloat = !!div.style.cssFloat;
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
container = document.createElement( "div" );
container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" +
"padding:0;margin-top:1px;position:absolute";
div.innerHTML = "";
container.appendChild( div );
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
support.boxSizing = div.style.boxSizing === "" || div.style.MozBoxSizing === "" ||
div.style.WebkitBoxSizing === "";
jQuery.extend( support, {
reliableHiddenOffsets: function() {
if ( pixelPositionVal == null ) {
computeStyleTests();
}
return reliableHiddenOffsetsVal;
},
boxSizingReliable: function() {
// We're checking for pixelPositionVal here instead of boxSizingReliableVal
// since that compresses better and they're computed together anyway.
if ( pixelPositionVal == null ) {
computeStyleTests();
}
return boxSizingReliableVal;
},
pixelMarginRight: function() {
// Support: Android 4.0-4.3
if ( pixelPositionVal == null ) {
computeStyleTests();
}
return pixelMarginRightVal;
},
pixelPosition: function() {
if ( pixelPositionVal == null ) {
computeStyleTests();
}
return pixelPositionVal;
},
reliableMarginRight: function() {
// Support: Android 2.3
if ( pixelPositionVal == null ) {
computeStyleTests();
}
return reliableMarginRightVal;
},
reliableMarginLeft: function() {
// Support: IE <=8 only, Android 4.0 - 4.3 only, Firefox <=3 - 37
if ( pixelPositionVal == null ) {
computeStyleTests();
}
return reliableMarginLeftVal;
}
} );
function computeStyleTests() {
var contents, divStyle,
documentElement = document.documentElement;
// Setup
documentElement.appendChild( container );
div.style.cssText =
// Support: Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:border-box;box-sizing:border-box;" +
"position:relative;display:block;" +
"margin:auto;border:1px;padding:1px;" +
"top:1%;width:50%";
// Support: IE<9
// Assume reasonable values in the absence of getComputedStyle
pixelPositionVal = boxSizingReliableVal = reliableMarginLeftVal = false;
pixelMarginRightVal = reliableMarginRightVal = true;
// Check for getComputedStyle so that this code is not run in IE<9.
if ( window.getComputedStyle ) {
divStyle = window.getComputedStyle( div );
pixelPositionVal = ( divStyle || {} ).top !== "1%";
reliableMarginLeftVal = ( divStyle || {} ).marginLeft === "2px";
boxSizingReliableVal = ( divStyle || { width: "4px" } ).width === "4px";
// Support: Android 4.0 - 4.3 only
// Some styles come back with percentage values, even though they shouldn't
div.style.marginRight = "50%";
pixelMarginRightVal = ( divStyle || { marginRight: "4px" } ).marginRight === "4px";
// Support: Android 2.3 only
// Div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container (#3333)
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
contents = div.appendChild( document.createElement( "div" ) );
// Reset CSS: box-sizing; display; margin; border; padding
contents.style.cssText = div.style.cssText =
// Support: Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
"box-sizing:content-box;display:block;margin:0;border:0;padding:0";
contents.style.marginRight = contents.style.width = "0";
div.style.width = "1px";
reliableMarginRightVal =
!parseFloat( ( window.getComputedStyle( contents ) || {} ).marginRight );
div.removeChild( contents );
}
// Support: IE6-8
// First check that getClientRects works as expected
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
div.style.display = "none";
reliableHiddenOffsetsVal = div.getClientRects().length === 0;
if ( reliableHiddenOffsetsVal ) {
div.style.display = "";
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
div.childNodes[ 0 ].style.borderCollapse = "separate";
contents = div.getElementsByTagName( "td" );
contents[ 0 ].style.cssText = "margin:0;border:0;padding:0;display:none";
reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0;
if ( reliableHiddenOffsetsVal ) {
contents[ 0 ].style.display = "";
contents[ 1 ].style.display = "none";
reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0;
}
}
// Teardown
documentElement.removeChild( container );
}
} )();
var getStyles, curCSS,
rposition = /^(top|right|bottom|left)$/;
if ( window.getComputedStyle ) {
getStyles = function( elem ) {
// Support: IE<=11+, Firefox<=30+ (#15098, #14150)
// IE throws on elements created in popups
// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
var view = elem.ownerDocument.defaultView;
if ( !view || !view.opener ) {
view = window;
}
return view.getComputedStyle( elem );
};
curCSS = function( elem, name, computed ) {
var width, minWidth, maxWidth, ret,
style = elem.style;
computed = computed || getStyles( elem );
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined;
// Support: Opera 12.1x only
// Fall back to style even without computed
// computed is undefined for elems on document fragments
if ( ( ret === "" || ret === undefined ) && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
if ( computed ) {
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value"
// instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values,
// but width seems to be reliably pixels
// this is against the CSSOM draft spec:
// http://dev.w3.org/csswg/cssom/#resolved-values
if ( !support.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
// Support: IE
// IE returns zIndex value as an integer.
return ret === undefined ?
ret :
ret + "";
};
} else if ( documentElement.currentStyle ) {
getStyles = function( elem ) {
return elem.currentStyle;
};
curCSS = function( elem, name, computed ) {
var left, rs, rsLeft, ret,
style = elem.style;
computed = computed || getStyles( elem );
ret = computed ? computed[ name ] : undefined;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are
// proportional to the parent element instead
// and we can't measure the parent instead because it
// might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rs = elem.runtimeStyle;
rsLeft = rs && rs.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
rs.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
rs.left = rsLeft;
}
}
// Support: IE
// IE returns zIndex value as an integer.
return ret === undefined ?
ret :
ret + "" || "auto";
};
}
function addGetHookIf( conditionFn, hookFn ) {
// Define the hook, we'll check on the first run if it's really needed.
return {
get: function() {
if ( conditionFn() ) {
// Hook not needed (or it's not possible to use it due
// to missing dependency), remove it.
delete this.get;
return;
}
// Hook needed; redefine it so that the support test is not executed again.
return ( this.get = hookFn ).apply( this, arguments );
}
};
}
var
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity\s*=\s*([^)]*)/i,
// swappable if display is none or starts with table except
// "table", "table-cell", or "table-caption"
// see here for display values:
// https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: "0",
fontWeight: "400"
},
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ],
emptyStyle = document.createElement( "div" ).style;
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( name ) {
// shortcut for names that are not vendor prefixed
if ( name in emptyStyle ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt( 0 ).toUpperCase() + name.slice( 1 ),
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in emptyStyle ) {
return name;
}
}
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] =
jQuery._data( elem, "olddisplay", defaultDisplay( elem.nodeName ) );
}
} else {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
jQuery._data(
elem,
"olddisplay",
hidden ? display : jQuery.css( elem, "display" )
);
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = support.boxSizing &&
jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test( val ) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox &&
( support.boxSizingReliable() || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
jQuery.extend( {
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"animationIterationCount": true,
"columnCount": true,
"fillOpacity": true,
"flexGrow": true,
"flexShrink": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"order": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] ||
( jQuery.cssProps[ origName ] = vendorPropName( origName ) || 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 "+=" or "-=" to relative numbers (#7345)
if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) {
value = adjustCSS( elem, name, ret );
// Fixes bug #9237
type = "number";
}
// Make sure that null and NaN values aren't set. See: #7116
if ( value == null || value !== value ) {
return;
}
// If a number was passed in, add the unit (except for certain CSS properties)
if ( type === "number" ) {
value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "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 ( !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 ) {
// Support: IE
// Swallow errors from 'invalid' CSS values (#5509)
try {
style[ name ] = value;
} catch ( e ) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks &&
( ret = hooks.get( elem, false, extra ) ) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, 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( origName ) || 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 || isFinite( num ) ? num || 0 : val;
}
return val;
}
} );
jQuery.each( [ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return rdisplayswap.test( jQuery.css( elem, "display" ) ) &&
elem.offsetWidth === 0 ?
swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
} ) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
support.boxSizing &&
jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
} );
if ( !support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( ( computed && elem.currentStyle ?
elem.currentStyle.filter :
elem.style.filter ) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist -
// attempt to remove filter attribute #6652
// if value === "", then remove inline opacity #12685
if ( ( value >= 1 || value === "" ) &&
jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there is no filter style applied in a css rule
// or unset inline opacity, we are done
if ( value === "" || currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
function( elem, computed ) {
if ( computed ) {
return swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
);
jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft,
function( elem, computed ) {
if ( computed ) {
return (
parseFloat( curCSS( elem, "marginLeft" ) ) ||
// Support: IE<=11+
// Running getBoundingClientRect on a disconnected node in IE throws an error
// Support: IE8 only
// getClientRects() errors on disconnected elems
( jQuery.contains( elem.ownerDocument, elem ) ?
elem.getBoundingClientRect().left -
swap( elem, { marginLeft: 0 }, function() {
return elem.getBoundingClientRect().left;
} ) :
0
)
) + "px";
}
}
);
// These hooks are used by animate to expand properties
jQuery.each( {
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split( " " ) : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
} );
jQuery.fn.extend( {
css: function( name, value ) {
return access( this, function( elem, name, value ) {
var styles, len,
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 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
if ( typeof state === "boolean" ) {
return state ? this.show() : this.hide();
}
return this.each( function() {
if ( isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
} );
}
} );
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || jQuery.easing._default;
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
// Use a property on the element directly when it is not a DOM element,
// or when there is no matching style property that exists.
if ( tween.elem.nodeType !== 1 ||
tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) {
return tween.elem[ tween.prop ];
}
// passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.nodeType === 1 &&
( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null ||
jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Support: IE <=9
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p * Math.PI ) / 2;
},
_default: "swing"
};
jQuery.fx = Tween.prototype.init;
// Back Compat <1.8 extension point
jQuery.fx.step = {};
var
fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rrun = /queueHooks$/;
// Animations created synchronously will run synchronously
function createFxNow() {
window.setTimeout( function() {
fxNow = undefined;
} );
return ( fxNow = jQuery.now() );
}
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth ? 1 : 0;
for ( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
function createTween( value, prop, animation ) {
var tween,
collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) {
// we're done with this property
return tween;
}
}
}
function defaultPrefilter( elem, props, opts ) {
/* jshint validthis: true */
var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHidden( elem ),
dataShow = jQuery._data( elem, "fxshow" );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always( function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always( function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
} );
} );
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
display = jQuery.css( elem, "display" );
// Test default display if display is currently "none"
checkDisplay = display === "none" ?
jQuery._data( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display;
if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !support.inlineBlockNeedsLayout || defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !support.shrinkWrapBlocks() ) {
anim.always( function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
} );
}
}
// show/hide pass
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.exec( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
// If there is dataShow left over from a stopped hide or show
// and we are going to proceed with show, we should pretend to be hidden
if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
hidden = true;
} else {
continue;
}
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
// Any non-fx value stops us from restoring the original display value
} else {
display = undefined;
}
}
if ( !jQuery.isEmptyObject( orig ) ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = jQuery._data( elem, "fxshow", {} );
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done( function() {
jQuery( elem ).hide();
} );
}
anim.done( function() {
var prop;
jQuery._removeData( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
} );
for ( prop in orig ) {
tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
// If this is a noop like .hide().hide(), restore an overwritten display value
} else if ( ( display === "none" ? defaultDisplay( elem.nodeName ) : display ) === "inline" ) {
style.display = display;
}
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = Animation.prefilters.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 ),
// Support: Android 2.3
// 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: {},
easing: jQuery.easing._default
}, 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.notifyWith( elem, [ animation, 1, 0 ] );
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 = Animation.prefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
if ( jQuery.isFunction( result.stop ) ) {
jQuery._queueHooks( animation.elem, animation.opts.queue ).stop =
jQuery.proxy( result.stop, result );
}
return result;
}
}
jQuery.map( props, createTween, animation );
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.Animation = jQuery.extend( Animation, {
tweeners: {
"*": [ function( prop, value ) {
var tween = this.createTween( prop, value );
adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween );
return tween;
} ]
},
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.match( rnotwhite );
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || [];
Animation.tweeners[ prop ].unshift( callback );
}
},
prefilters: [ defaultPrefilter ],
prefilter: function( callback, prepend ) {
if ( prepend ) {
Animation.prefilters.unshift( callback );
} else {
Animation.prefilters.push( callback );
}
}
} );
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.fn.extend( {
fadeTo: function( speed, to, easing, callback ) {
// 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 );
},
animate: function( prop, speed, easing, callback ) {
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 );
// 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 );
},
stop: function( type, clearQueue, gotoEnd ) {
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 );
}
} );
},
finish: function( type ) {
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.stop ) {
hooks.stop.call( this, true );
}
// 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.each( [ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
} );
// Generate shortcuts for custom animations
jQuery.each( {
slideDown: genFx( "show" ),
slideUp: genFx( "hide" ),
slideToggle: genFx( "toggle" ),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
} );
jQuery.timers = [];
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
jQuery.timers.push( timer );
if ( timer() ) {
jQuery.fx.start();
} else {
jQuery.timers.pop();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = window.setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
window.clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Based off of the plugin by Clint Helfers, with permission.
// http://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.delay = function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = window.setTimeout( next, time );
hooks.stop = function() {
window.clearTimeout( timeout );
};
} );
};
( function() {
var a,
input = document.createElement( "input" ),
div = document.createElement( "div" ),
select = document.createElement( "select" ),
opt = select.appendChild( document.createElement( "option" ) );
// Setup
div = document.createElement( "div" );
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
a = div.getElementsByTagName( "a" )[ 0 ];
// Support: Windows Web Apps (WWA)
// `type` must use .setAttribute for WWA (#14901)
input.setAttribute( "type", "checkbox" );
div.appendChild( input );
a = div.getElementsByTagName( "a" )[ 0 ];
// First batch of tests.
a.style.cssText = "top:1px";
// Test setAttribute on camelCase class.
// If it works, we need attrFixes when doing get/setAttribute (ie6/7)
support.getSetAttribute = div.className !== "t";
// Get the style information from getAttribute
// (IE uses .cssText instead)
support.style = /top/.test( a.getAttribute( "style" ) );
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
support.hrefNormalized = a.getAttribute( "href" ) === "/a";
// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
support.checkOn = !!input.value;
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
support.optSelected = opt.selected;
// Tests for enctype support on a form (#6743)
support.enctype = !!document.createElement( "form" ).enctype;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE8 only
// Check if we can trust getAttribute("value")
input = document.createElement( "input" );
input.setAttribute( "value", "" );
support.input = input.getAttribute( "value" ) === "";
// Check if an input maintains its value after becoming a radio
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
} )();
var rreturn = /\r/g,
rspaces = /[\x20\t\r\n\f]+/g;
jQuery.fn.extend( {
val: function( value ) {
var hooks, ret, isFunction,
elem = this[ 0 ];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] ||
jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if (
hooks &&
"get" in hooks &&
( ret = hooks.get( elem, "value" ) ) !== undefined
) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace( rreturn, "" ) :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each( function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map( val, function( value ) {
return value == null ? "" : value + "";
} );
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
} );
}
} );
jQuery.extend( {
valHooks: {
option: {
get: function( elem ) {
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
// Support: IE10-11+
// option.text throws exceptions (#14686, #14858)
// Strip and collapse whitespace
// https://html.spec.whatwg.org/#strip-and-collapse-whitespace
jQuery.trim( jQuery.text( elem ) ).replace( rspaces, " " );
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( support.optDisabled ?
!option.disabled :
option.getAttribute( "disabled" ) === null ) &&
( !option.parentNode.disabled ||
!jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 ) {
// Support: IE6
// When new option element is added to select box we need to
// force reflow of newly added node in order to workaround delay
// of initialization properties
try {
option.selected = optionSet = true;
} catch ( _ ) {
// Will be executed only in IE6
option.scrollHeight;
}
} else {
option.selected = false;
}
}
// Force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return options;
}
}
}
} );
// Radios and checkboxes getter/setter
jQuery.each( [ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 );
}
}
};
if ( !support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
return elem.getAttribute( "value" ) === null ? "on" : elem.value;
};
}
} );
var nodeHook, boolHook,
attrHandle = jQuery.expr.attrHandle,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = support.getSetAttribute,
getSetInput = support.input;
jQuery.fn.extend( {
attr: function( name, value ) {
return access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each( function() {
jQuery.removeAttr( this, name );
} );
}
} );
jQuery.extend( {
attr: function( elem, name, value ) {
var ret, hooks,
nType = elem.nodeType;
// Don't get/set attributes on text, comment and attribute nodes
if ( nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
}
if ( hooks && "set" in hooks &&
( ret = hooks.set( elem, value, name ) ) !== undefined ) {
return ret;
}
elem.setAttribute( name, value + "" );
return value;
}
if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
return ret;
}
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ? undefined : ret;
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !support.radioValue && value === "radio" &&
jQuery.nodeName( elem, "input" ) ) {
// Setting the type on a radio button after the value resets the value in IE8-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( ( name = attrNames[ i++ ] ) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
elem[ propName ] = false;
// Support: IE<9
// Also clear defaultChecked/defaultSelected (if appropriate)
} else {
elem[ jQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
}
} );
// Hooks for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
// IE<8 needs the *property* name
elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
} else {
// Support: IE<9
// Use defaultChecked and defaultSelected for oldIE
elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = attrHandle[ name ] || jQuery.find.attr;
if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
attrHandle[ name ] = function( elem, name, isXML ) {
var ret, handle;
if ( !isXML ) {
// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[ name ];
attrHandle[ name ] = ret;
ret = getter( elem, name, isXML ) != null ?
name.toLowerCase() :
null;
attrHandle[ name ] = handle;
}
return ret;
};
} else {
attrHandle[ name ] = function( elem, name, isXML ) {
if ( !isXML ) {
return elem[ jQuery.camelCase( "default-" + name ) ] ?
name.toLowerCase() :
null;
}
};
}
} );
// fix oldIE attroperties
if ( !getSetInput || !getSetAttribute ) {
jQuery.attrHooks.value = {
set: function( elem, value, name ) {
if ( jQuery.nodeName( elem, "input" ) ) {
// Does not return so that setAttribute is also used
elem.defaultValue = value;
} else {
// Use nodeHook if defined (#1954); otherwise setAttribute is fine
return nodeHook && nodeHook.set( elem, value, name );
}
}
};
}
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = {
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
elem.setAttributeNode(
( ret = elem.ownerDocument.createAttribute( name ) )
);
}
ret.value = value += "";
// Break association with cloned elements by also using setAttribute (#9646)
if ( name === "value" || value === elem.getAttribute( name ) ) {
return value;
}
}
};
// Some attributes are constructed with empty-string values when not defined
attrHandle.id = attrHandle.name = attrHandle.coords =
function( elem, name, isXML ) {
var ret;
if ( !isXML ) {
return ( ret = elem.getAttributeNode( name ) ) && ret.value !== "" ?
ret.value :
null;
}
};
// Fixing value retrieval on a button requires this module
jQuery.valHooks.button = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
if ( ret && ret.specified ) {
return ret.value;
}
},
set: nodeHook.set
};
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
set: function( elem, value, name ) {
nodeHook.set( elem, value === "" ? false : value, name );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each( [ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
};
} );
}
if ( !support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Note: IE uppercases css property names, but if we were to .toLowerCase()
// .cssText, that would destroy case sensitivity in URL's, like in "background"
return elem.style.cssText || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
var rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i;
jQuery.fn.extend( {
prop: function( name, value ) {
return access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each( function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch ( e ) {}
} );
}
} );
jQuery.extend( {
prop: function( elem, name, value ) {
var ret, hooks,
nType = elem.nodeType;
// Don't get/set properties on text, comment and attribute nodes
if ( nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
// 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;
}
return ( elem[ name ] = value );
}
if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
return ret;
}
return elem[ name ];
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the
// correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr( elem, "tabindex" );
return tabindex ?
parseInt( tabindex, 10 ) :
rfocusable.test( elem.nodeName ) ||
rclickable.test( elem.nodeName ) && elem.href ?
0 :
-1;
}
}
},
propFix: {
"for": "htmlFor",
"class": "className"
}
} );
// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !support.hrefNormalized ) {
// href/src property should get the full normalized URL (#10299/#12915)
jQuery.each( [ "href", "src" ], function( i, name ) {
jQuery.propHooks[ name ] = {
get: function( elem ) {
return elem.getAttribute( name, 4 );
}
};
} );
}
// Support: Safari, IE9+
// Accessing the selectedIndex property
// forces the browser to respect setting selected
// on the option
// The getter ensures a default option is selected
// when in an optgroup
if ( !support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
},
set: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
}
};
}
jQuery.each( [
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
} );
// IE6/7 call enctype encoding
if ( !support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
var rclass = /[\t\r\n\f]/g;
function getClass( elem ) {
return jQuery.attr( elem, "class" ) || "";
}
jQuery.fn.extend( {
addClass: function( value ) {
var classes, elem, cur, curValue, clazz, j, finalValue,
i = 0;
if ( jQuery.isFunction( value ) ) {
return this.each( function( j ) {
jQuery( this ).addClass( value.call( this, j, getClass( this ) ) );
} );
}
if ( typeof value === "string" && value ) {
classes = value.match( rnotwhite ) || [];
while ( ( elem = this[ i++ ] ) ) {
curValue = getClass( elem );
cur = elem.nodeType === 1 &&
( " " + curValue + " " ).replace( rclass, " " );
if ( cur ) {
j = 0;
while ( ( clazz = classes[ j++ ] ) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
// only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim( cur );
if ( curValue !== finalValue ) {
jQuery.attr( elem, "class", finalValue );
}
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, curValue, clazz, j, finalValue,
i = 0;
if ( jQuery.isFunction( value ) ) {
return this.each( function( j ) {
jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) );
} );
}
if ( !arguments.length ) {
return this.attr( "class", "" );
}
if ( typeof value === "string" && value ) {
classes = value.match( rnotwhite ) || [];
while ( ( elem = this[ i++ ] ) ) {
curValue = getClass( elem );
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 &&
( " " + curValue + " " ).replace( rclass, " " );
if ( cur ) {
j = 0;
while ( ( clazz = classes[ j++ ] ) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) > -1 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
// Only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim( cur );
if ( curValue !== finalValue ) {
jQuery.attr( elem, "class", finalValue );
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value;
if ( typeof stateVal === "boolean" && type === "string" ) {
return stateVal ? this.addClass( value ) : this.removeClass( value );
}
if ( jQuery.isFunction( value ) ) {
return this.each( function( i ) {
jQuery( this ).toggleClass(
value.call( this, i, getClass( this ), stateVal ),
stateVal
);
} );
}
return this.each( function() {
var className, i, self, classNames;
if ( type === "string" ) {
// Toggle individual class names
i = 0;
self = jQuery( this );
classNames = value.match( rnotwhite ) || [];
while ( ( className = classNames[ i++ ] ) ) {
// Check each className given, space separated list
if ( self.hasClass( className ) ) {
self.removeClass( className );
} else {
self.addClass( className );
}
}
// Toggle whole class name
} else if ( value === undefined || type === "boolean" ) {
className = getClass( this );
if ( className ) {
// store className if set
jQuery._data( this, "__className__", 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.
jQuery.attr( this, "class",
className || value === false ?
"" :
jQuery._data( this, "__className__" ) || ""
);
}
} );
},
hasClass: function( selector ) {
var className, elem,
i = 0;
className = " " + selector + " ";
while ( ( elem = this[ i++ ] ) ) {
if ( elem.nodeType === 1 &&
( " " + getClass( elem ) + " " ).replace( rclass, " " )
.indexOf( className ) > -1
) {
return true;
}
}
return false;
}
} );
// Return jQuery for attributes-only inclusion
jQuery.each( ( "blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu" ).split( " " ),
function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
} );
jQuery.fn.extend( {
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
} );
var location = window.location;
var nonce = jQuery.now();
var rquery = ( /\?/ );
var rvalidtokens = /(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;
jQuery.parseJSON = function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
// Support: Android 2.3
// Workaround failure to string-cast null input
return window.JSON.parse( data + "" );
}
var requireNonComma,
depth = null,
str = jQuery.trim( data + "" );
// Guard against invalid (and possibly dangerous) input by ensuring that nothing remains
// after removing valid tokens
return str && !jQuery.trim( str.replace( rvalidtokens, function( token, comma, open, close ) {
// Force termination if we see a misplaced comma
if ( requireNonComma && comma ) {
depth = 0;
}
// Perform no more replacements after returning to outermost depth
if ( depth === 0 ) {
return token;
}
// Commas must not follow "[", "{", or ","
requireNonComma = open || comma;
// Determine new depth
// array/object open ("[" or "{"): depth += true - false (increment)
// array/object close ("]" or "}"): depth += false - true (decrement)
// other cases ("," or primitive): depth += true - true (numeric cast)
depth += !close - !open;
// Remove this token
return "";
} ) ) ?
( Function( "return " + str ) )() :
jQuery.error( "Invalid JSON: " + data );
};
// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new window.DOMParser();
xml = tmp.parseFromString( data, "text/xml" );
} else { // IE
xml = new window.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;
};
var
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
// IE leaves an \r character at EOL
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat( "*" ),
// Document location
ajaxLocation = location.href,
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( ( dataType = dataTypes[ i++ ] ) ) {
// Prepend if requested
if ( dataType.charAt( 0 ) === "+" ) {
dataType = dataType.slice( 1 ) || "*";
( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func );
// Otherwise append
} else {
( structure[ dataType ] = structure[ dataType ] || [] ).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if ( typeof dataTypeOrTransport === "string" &&
!seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
} );
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var deep, key,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var firstDataType, ct, finalDataType, type,
contents = s.contents,
dataTypes = s.dataTypes;
// Remove auto dataType and get content-type in the process
while ( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
/* Chain conversions given the request and the original response
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while ( current ) {
if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}
// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
prev = current;
current = dataTypes.shift();
if ( current ) {
// There's only work to do if current dataType is non-auto
if ( current === "*" ) {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split( " " );
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.unshift( tmp[ 1 ] );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s[ "throws" ] ) { // jscs:ignore requireDotNotation
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return {
state: "parsererror",
error: conv ? e : "No conversion from " + prev + " to " + current
};
}
}
}
}
}
}
return { state: "success", data: response };
}
jQuery.extend( {
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /\bxml\b/,
html: /\bhtml/,
json: /\bjson\b/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var
// 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( 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
// Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
fireGlobals = jQuery.event && 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 += ( 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_=" + nonce++ ) :
// Otherwise add one to the end
cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + 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 ] );
}
// If request was aborted inside ajaxSend, stop there
if ( state === 2 ) {
return jqXHR;
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = window.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 ) {
window.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;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert( s, response, jqXHR, isSuccess );
// If successful, handle type chaining
if ( isSuccess ) {
// 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 || s.type === "HEAD" ) {
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.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;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
} );
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
// The url can be an options object (which then must have .url)
return jQuery.ajax( jQuery.extend( {
url: url,
type: method,
dataType: type,
data: data,
success: callback
}, jQuery.isPlainObject( url ) && url ) );
};
} );
jQuery._evalUrl = function( url ) {
return jQuery.ajax( {
url: url,
// Make this explicit, since user can override this through ajaxSetup (#11264)
type: "GET",
dataType: "script",
cache: true,
async: false,
global: false,
"throws": true
} );
};
jQuery.fn.extend( {
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each( function( i ) {
jQuery( this ).wrapAll( html.call( this, i ) );
} );
}
if ( this[ 0 ] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );
if ( this[ 0 ].parentNode ) {
wrap.insertBefore( this[ 0 ] );
}
wrap.map( function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
} ).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each( function( i ) {
jQuery( this ).wrapInner( html.call( this, i ) );
} );
}
return this.each( function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
} );
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each( function( i ) {
jQuery( this ).wrapAll( isFunction ? html.call( this, i ) : html );
} );
},
unwrap: function() {
return this.parent().each( function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
} ).end();
}
} );
function getDisplay( elem ) {
return elem.style && elem.style.display || jQuery.css( elem, "display" );
}
function filterHidden( elem ) {
// Disconnected elements are considered hidden
if ( !jQuery.contains( elem.ownerDocument || document, elem ) ) {
return true;
}
while ( elem && elem.nodeType === 1 ) {
if ( getDisplay( elem ) === "none" || elem.type === "hidden" ) {
return true;
}
elem = elem.parentNode;
}
return false;
}
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return support.reliableHiddenOffsets() ?
( elem.offsetWidth <= 0 && elem.offsetHeight <= 0 &&
!elem.getClientRects().length ) :
filterHidden( elem );
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams(
prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]",
v,
traditional,
add
);
}
} );
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
} );
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
jQuery.fn.extend( {
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
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 || !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();
}
} );
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject !== undefined ?
// Support: IE6-IE8
function() {
// XHR cannot access local files, always use ActiveX for that case
if ( this.isLocal ) {
return createActiveXHR();
}
// Support: IE 9-11
// IE seems to error on cross-domain PATCH requests when ActiveX XHR
// is used. In IE 9+ always use the native XHR.
// Note: this condition won't catch Edge as it doesn't define
// document.documentMode but it also doesn't support ActiveX so it won't
// reach this code.
if ( document.documentMode > 8 ) {
return createStandardXHR();
}
// Support: IE<9
// oldIE XHR does not support non-RFC2616 methods (#13240)
// See http://msdn.microsoft.com/en-us/library/ie/ms536648(v=vs.85).aspx
// and http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9
// Although this check for six methods instead of eight
// since IE also does not support "trace" and "connect"
return /^(get|post|head|put|delete|options)$/i.test( this.type ) &&
createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
var xhrId = 0,
xhrCallbacks = {},
xhrSupported = jQuery.ajaxSettings.xhr();
// Support: IE<10
// Open requests must be manually aborted on unload (#5280)
// See https://support.microsoft.com/kb/2856746 for more info
if ( window.attachEvent ) {
window.attachEvent( "onunload", function() {
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( undefined, true );
}
} );
}
// Determine support properties
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
xhrSupported = support.ajax = !!xhrSupported;
// Create transport if the browser can provide an xhr
if ( xhrSupported ) {
jQuery.ajaxTransport( function( options ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !options.crossDomain || support.cors ) {
var callback;
return {
send: function( headers, complete ) {
var i,
xhr = options.xhr(),
id = ++xhrId;
// Open the socket
xhr.open(
options.type,
options.url,
options.async,
options.username,
options.password
);
// Apply custom fields if provided
if ( options.xhrFields ) {
for ( i in options.xhrFields ) {
xhr[ i ] = options.xhrFields[ i ];
}
}
// Override mime type if needed
if ( options.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( options.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Set headers
for ( i in headers ) {
// Support: IE<9
// IE's ActiveXObject throws a 'Type Mismatch' exception when setting
// request header to a null-value.
//
// To keep consistent with other XHR implementations, cast the value
// to string and ignore `undefined`.
if ( headers[ i ] !== undefined ) {
xhr.setRequestHeader( i, headers[ i ] + "" );
}
}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( options.hasContent && options.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status, statusText, responses;
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Clean up
delete xhrCallbacks[ id ];
callback = undefined;
xhr.onreadystatechange = jQuery.noop;
// Abort manually if needed
if ( isAbort ) {
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
responses = {};
status = xhr.status;
// Support: IE<10
// Accessing binary-data responseText throws an exception
// (#11426)
if ( typeof xhr.responseText === "string" ) {
responses.text = xhr.responseText;
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch ( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && options.isLocal && !options.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, xhr.getAllResponseHeaders() );
}
};
// Do send the request
// `xhr.send` may raise an exception, but it will be
// handled in jQuery.ajax (so no try/catch here)
if ( !options.async ) {
// If we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
window.setTimeout( callback );
} else {
// Register the callback, but delay it in case `xhr.send` throws
// Add to the list of active xhr callbacks
xhr.onreadystatechange = xhrCallbacks[ id ] = callback;
}
},
abort: function() {
if ( callback ) {
callback( undefined, true );
}
}
};
}
} );
}
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch ( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch ( e ) {}
}
// Install script dataType
jQuery.ajaxSetup( {
accepts: {
script: "text/javascript, application/javascript, " +
"application/ecmascript, application/x-ecmascript"
},
contents: {
script: /\b(?:java|ecma)script\b/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
} );
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
} );
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function( s ) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || jQuery( "head" )[ 0 ] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement( "script" );
script.async = true;
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( script.parentNode ) {
script.parentNode.removeChild( script );
}
// Dereference the script
script = null;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
// Use native DOM manipulation to avoid our domManip AJAX trickery
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( undefined, true );
}
}
};
}
} );
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup( {
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
} );
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" &&
( s.contentType || "" )
.indexOf( "application/x-www-form-urlencoded" ) === 0 &&
rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters[ "script json" ] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always( function() {
// If previous value didn't exist - remove it
if ( overwritten === undefined ) {
jQuery( window ).removeProp( callbackName );
// Otherwise restore preexisting value
} else {
window[ callbackName ] = overwritten;
}
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
} );
// Delegate to script
return "script";
}
} );
// data: string of html
// context (optional): If specified, the fragment will be created in this context,
// defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function( data, context, keepScripts ) {
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 = buildFragment( [ data ], context, scripts );
if ( scripts && scripts.length ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
};
// Keep a copy of the old load method
var _load = jQuery.fn.load;
/**
* Load a url into a page
*/
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, type, response,
self = this,
off = url.indexOf( " " );
if ( off > -1 ) {
selector = jQuery.trim( 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.
// Make value of this field explicit since
// user can override it through ajaxSetup method
type: type || "GET",
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 );
// If the request succeeds, this function gets "data", "status", "jqXHR"
// but they are ignored because response was set above.
// If it fails, this function gets "jqXHR", "status", "error"
} ).always( callback && function( jqXHR, status ) {
self.each( function() {
callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] );
} );
} );
}
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [
"ajaxStart",
"ajaxStop",
"ajaxComplete",
"ajaxError",
"ajaxSuccess",
"ajaxSend"
], function( i, type ) {
jQuery.fn[ type ] = function( fn ) {
return this.on( type, fn );
};
} );
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep( jQuery.timers, function( fn ) {
return elem === fn.elem;
} ).length;
};
/**
* Gets a window from an element
*/
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
jQuery.offset = {
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),
curElem = jQuery( elem ),
props = {};
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) &&
jQuery.inArray( "auto", [ curCSSTop, curCSSLeft ] ) > -1;
// need to be able to calculate position if either top or left
// is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
// Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
options = options.call( elem, i, jQuery.extend( {}, curOffset ) );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend( {
offset: function( options ) {
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 !== "undefined" ) {
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 )
};
},
position: function() {
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 its 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 )
};
},
offsetParent: function() {
return this.map( function() {
var offsetParent = this.offsetParent;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) &&
jQuery.css( offsetParent, "position" ) === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || documentElement;
} );
}
} );
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return 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 );
};
} );
// Support: Safari<7-8+, Chrome<37-44+
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
);
} );
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name },
function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return 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.fn.extend( {
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ?
this.off( selector, "**" ) :
this.off( types, selector || "**", fn );
}
} );
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
// Note that for maximum portability, libraries that are not jQuery should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. jQuery is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function() {
return jQuery;
} );
}
var
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$;
jQuery.noConflict = function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
};
// Expose jQuery and $ identifiers, even in
// AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( !noGlobal ) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
}));
|
module.exports = {
serverSchema: require('./server.schema')
}
|
/***
* The main menu wrapper which takes your project as a child
* @patr -- patrick@quantfive.org
*/
import React from 'react';
// Components
import Nav from './components/Nav';
// NPM Modules
import { StyleSheet, css } from 'aphrodite/no-important';
export default class Menu extends React.Component {
/***
* Renders the app, normally if the menu isn't active otherwise scaled
*/
renderChildren = () => {
return React.Children.map(this.props.children, (child, index) => {
if (index === 0) {
var classes = child.props.className;
var activeClass = css(styles.app, this.props.active && styles.appScale);
var propsClass = this.props.active && this.props.appClassName ? this.props.appClassName : '';
return React.cloneElement(child, {
className: `${classes} ${activeClass} ${propsClass}`,
});
} else {
return child;
}
});
}
render() {
return (
<div
className={css(styles.menu, this.props.active && styles.menuActive) + ` ${this.props.menuClassName ? this.props.menuClassName : ''}`}>
<div className={` ${this.props.navWrapperClassName ? this.props.navWrapperClassName : ''} ` + css(styles.navWrapper, this.props.active && styles.navActive)}>
<Nav
nav={this.props.nav}
navItemClassName={this.props.navItemClassName}
linkClassName={this.props.linkClassName}
reactRouter={this.props.reactRouter}
closeMenu={this.props.closeMenu}
navClassName={this.props.navClassName}
tagLine={this.props.tagLine}
extraComponentBottom={this.props.extraComponentBottom}
extraComponentTop={this.props.extraComponentTop}
navLinkStyle={this.props.navLinkStyle}
/>
</div>
{ this.renderChildren() }
</div>
);
}
}
const TRANSLATE = 230; // the translation amount
var styles = StyleSheet.create({
menu: {
position: 'relative',
height: '100%',
},
menuActive: {
overflow: 'hidden',
},
app: {
transition: 'all .4s cubic-bezier(.94,.06,.32,.95)',
'-webkit-font-smoothing': 'subpixel-antialiased',
},
navWrapper: {
display: 'flex',
alignItems: 'center',
height: '100%',
width: '230px',
minHeight: '100vh',
position: 'fixed',
top: '0',
left: '0',
zIndex: '-1',
background: '#272d34',
},
navActive: {
zIndex: '0',
},
appScale: {
transform: `translateX(${TRANSLATE}px)`,
}
});
|
(function(a) {
a.fn.smartWizard = function(m) {
var c = a.extend({}, a.fn.smartWizard.defaults, m),
x = arguments;
return this.each(function() {
function C() {
var e = b.children("div");
b.children("ul").addClass("anchor");
e.addClass("content");
n = a("<div>Loading</div>").addClass("loader");
k = a("<div></div>").addClass("action-bar");
p = a("<div></div>").addClass("step-container");
q = a("<a>" + c.labelNext + "</a>").attr("href", "#").addClass("btn btn-primary");
r = a("<a>" + c.labelPrevious + "</a>").attr("href", "#").addClass("btn btn-primary");
s = a("<a>" + c.labelFinish + "</a>").attr("href", "#").addClass("btn btn-primary");
c.errorSteps && 0 < c.errorSteps.length && a.each(c.errorSteps, function(a, b) {
y(b, !0)
});
p.append(e);
k.append(n);
b.append(p);
b.append(k);
c.includeFinishButton && k.append(s);
k.append(q).append(r);
z = p.width();
a(q).click(function() {
if (a(this).hasClass("buttonDisabled")) return !1;
A();
return !1
});
a(r).click(function() {
if (a(this).hasClass("buttonDisabled")) return !1;
B();
return !1
});
a(s).click(function() {
if (!a(this).hasClass("buttonDisabled"))
if (a.isFunction(c.onFinish)) c.onFinish.call(this,
a(f));
else {
var d = b.parents("form");
d && d.length && d.submit()
}
return !1
});
a(f).bind("click", function(a) {
if (f.index(this) == h) return !1;
a = f.index(this);
1 == f.eq(a).attr("isDone") - 0 && t(a);
return !1
});
c.keyNavigation && a(document).keyup(function(a) {
39 == a.which ? A() : 37 == a.which && B()
});
D();
t(h)
}
function D() {
c.enableAllSteps ? (a(f, b).removeClass("selected").removeClass("disabled").addClass("done"), a(f, b).attr("isDone", 1)) : (a(f, b).removeClass("selected").removeClass("done").addClass("disabled"), a(f, b).attr("isDone",
0));
a(f, b).each(function(e) {
a(a(this).attr("href"), b).hide();
a(this).attr("rel", e + 1)
})
}
function t(e) {
var d = f.eq(e),
g = c.contentURL,
h = d.data("hasContent");
stepNum = e + 1;
g && 0 < g.length ? c.contentCache && h ? w(e) : a.ajax({
url: g,
type: "POST",
data: {
step_number: stepNum
},
dataType: "text",
beforeSend: function() {
n.show()
},
error: function() {
n.hide()
},
success: function(c) {
n.hide();
c && 0 < c.length && (d.data("hasContent", !0), a(a(d, b).attr("href"), b).html(c), w(e))
}
}) : w(e)
}
function w(e) {
var d = f.eq(e),
g = f.eq(h);
if (e != h && a.isFunction(c.onLeaveStep) &&
!c.onLeaveStep.call(this, a(g))) return !1;
c.updateHeight && p.height(a(a(d, b).attr("href"), b).outerHeight());
if ("slide" == c.transitionEffect) a(a(g, b).attr("href"), b).slideUp("fast", function(c) {
a(a(d, b).attr("href"), b).slideDown("fast");
h = e;
u(g, d)
});
else if ("fade" == c.transitionEffect) a(a(g, b).attr("href"), b).fadeOut("fast", function(c) {
a(a(d, b).attr("href"), b).fadeIn("fast");
h = e;
u(g, d)
});
else if ("slideleft" == c.transitionEffect) {
var k = 0;
e > h ? (nextElmLeft1 = z + 10, nextElmLeft2 = 0, k = 0 - a(a(g, b).attr("href"), b).outerWidth()) :
(nextElmLeft1 = 0 - a(a(d, b).attr("href"), b).outerWidth() + 20, nextElmLeft2 = 0, k = 10 + a(a(g, b).attr("href"), b).outerWidth());
e == h ? (nextElmLeft1 = a(a(d, b).attr("href"), b).outerWidth() + 20, nextElmLeft2 = 0, k = 0 - a(a(g, b).attr("href"), b).outerWidth()) : a(a(g, b).attr("href"), b).animate({
left: k
}, "fast", function(e) {
a(a(g, b).attr("href"), b).hide()
});
a(a(d, b).attr("href"), b).css("left", nextElmLeft1);
a(a(d, b).attr("href"), b).show();
a(a(d, b).attr("href"), b).animate({
left: nextElmLeft2
}, "fast", function(a) {
h = e;
u(g, d)
})
} else a(a(g,
b).attr("href"), b).hide(), a(a(d, b).attr("href"), b).show(), h = e, u(g, d);
return !0
}
function u(e, d) {
a(e, b).removeClass("selected");
a(e, b).addClass("done");
a(d, b).removeClass("disabled");
a(d, b).removeClass("done");
a(d, b).addClass("selected");
a(d, b).attr("isDone", 1);
c.cycleSteps || (0 >= h ? a(r).addClass("buttonDisabled") : a(r).removeClass("buttonDisabled"), f.length - 1 <= h ? a(q).addClass("buttonDisabled") : a(q).removeClass("buttonDisabled"));
!f.hasClass("disabled") || c.enableFinishButton ? a(s).removeClass("buttonDisabled") :
a(s).addClass("buttonDisabled");
if (a.isFunction(c.onShowStep) && !c.onShowStep.call(this, a(d))) return !1
}
function A() {
var a = h + 1;
if (f.length <= a) {
if (!c.cycleSteps) return !1;
a = 0
}
t(a)
}
function B() {
var a = h - 1;
if (0 > a) {
if (!c.cycleSteps) return !1;
a = f.length - 1
}
t(a)
}
function E(b) {
a(".content", l).html(b);
l.show()
}
function y(c, d) {
d ? a(f.eq(c - 1), b).addClass("error") : a(f.eq(c - 1), b).removeClass("error")
}
var b = a(this),
h = c.selected,
f = a("ul > li > a[href^='#step-']", b),
z = 0,
n, l, k, p, q, r, s;
k = a(".action-bar", b);
0 == k.length && (k =
a("<div></div>").addClass("action-bar"));
l = a(".msg-box", b);
0 == l.length && (l = a('<div class="msg-box"><div class="content"></div><a href="#" class="close"><i class="icofont icofont-close-line-circled"></i></a></div>'), k.append(l));
a(".close", l).click(function() {
l.fadeOut("normal");
return !1
});
if (m && "init" !== m && "object" !== typeof m) {
if ("showMessage" === m) {
var v = Array.prototype.slice.call(x, 1);
E(v[0]);
return !0
}
if ("setError" === m) return v = Array.prototype.slice.call(x, 1), y(v[0].stepnum, v[0].iserror), !0;
a.error("Method " + m + " does not exist")
} else C()
})
};
a.fn.smartWizard.defaults = {
selected: 0,
keyNavigation: !0,
enableAllSteps: !1,
updateHeight: !0,
transitionEffect: "fade",
contentURL: null,
contentCache: !0,
cycleSteps: !1,
includeFinishButton: !0,
enableFinishButton: !1,
errorSteps: [],
labelNext: "Next",
labelPrevious: "Previous",
labelFinish: "Finish",
onLeaveStep: null,
onShowStep: null,
onFinish: null
}
})(jQuery);
(function($) {
"use strict";
$('#wizard').smartWizard({
transitionEffect: 'slideleft',
onFinish: onFinishCallback
});
function onFinishCallback() {
$('#wizard').smartWizard('showMessage', 'All Step Done.. !!!');
}
})(jQuery);
|
var transform = require('sdp-transform');
exports.write = function(session, opts) {
if (typeof session !== 'undefined' &&
typeof session.media !== 'undefined' &&
Array.isArray(session.media)) {
session.media.forEach(function (mLine) {
// expand sources to ssrcs
if (typeof mLine.sources !== 'undefined' &&
Object.keys(mLine.sources).length !== 0) {
mLine.ssrcs = [];
Object.keys(mLine.sources).forEach(function (ssrc) {
var source = mLine.sources[ssrc];
Object.keys(source).forEach(function (attribute) {
mLine.ssrcs.push({
id: ssrc,
attribute: attribute,
value: source[attribute]
});
});
});
delete mLine.sources;
}
// join ssrcs in ssrc groups
if (typeof mLine.ssrcGroups !== 'undefined' &&
Array.isArray(mLine.ssrcGroups)) {
mLine.ssrcGroups.forEach(function (ssrcGroup) {
if (typeof ssrcGroup.ssrcs !== 'undefined' &&
Array.isArray(ssrcGroup.ssrcs)) {
ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
}
});
}
});
}
// join group mids
if (typeof session !== 'undefined' &&
typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
session.groups.forEach(function (g) {
if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
g.mids = g.mids.join(' ');
}
});
}
return transform.write(session, opts);
};
exports.parse = function(sdp) {
var session = transform.parse(sdp);
if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
Array.isArray(session.media)) {
session.media.forEach(function (mLine) {
// group sources attributes by ssrc
if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
mLine.sources = {};
mLine.ssrcs.forEach(function (ssrc) {
if (!mLine.sources[ssrc.id])
mLine.sources[ssrc.id] = {};
mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
});
delete mLine.ssrcs;
}
// split ssrcs in ssrc groups
if (typeof mLine.ssrcGroups !== 'undefined' &&
Array.isArray(mLine.ssrcGroups)) {
mLine.ssrcGroups.forEach(function (ssrcGroup) {
if (typeof ssrcGroup.ssrcs === 'string') {
ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
}
});
}
});
}
// split group mids
if (typeof session !== 'undefined' &&
typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
session.groups.forEach(function (g) {
if (typeof g.mids === 'string') {
g.mids = g.mids.split(' ');
}
});
}
return session;
};
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import division # Standardmäßig float division - Ganzzahldivision kann man explizit mit '//' durchführen
from __future__ import absolute_import
from pyecs import *
# from pyecs.components import *
from time import time
class Selectable(Component):
selected_component = None
@classmethod
def _reset_global(CLS):
Selectable.selected_component = None
"""docstring for Selectable"""
def __init__(self, *args,**kwargs):
super(Selectable, self).__init__(*args,**kwargs)
self._selected = False
@property
def selected(self):
return self._selected
@selected.setter
def selected(self, value):
if value and not self._selected:
self._selected = value
self._select()
elif self._selected and not value:
self._selected = value
self._deselect()
def select(self):
self.selected = True
def deselect(self):
self.selected = False
def _select(self):
# if not self.selected:
if Selectable.selected_component is not None:
Selectable.selected_component.deselect()
Selectable.selected_component = self
self.entity.fire_callbacks("selected", self)
def _deselect(self):
# if self.selected:
Selectable.selected_component = None
self.entity.fire_callbacks("deselected", self)
|
const Base = require('./base.js');
const Sequelize = require('sequelize');
const mapper = require('object-mapper');
module.exports = class Member extends Base {
constructor(githubClient, databaseClient) {
super(githubClient, databaseClient);
this.schema = {
id: {
type: Sequelize.BIGINT,
primaryKey: true
},
avatar: Sequelize.STRING(400),
login: Sequelize.STRING(100),
url: Sequelize.STRING,
employee_id: Sequelize.BIGINT,
employee_login: Sequelize.STRING,
employee_title: Sequelize.STRING,
name: Sequelize.STRING,
email: Sequelize.STRING,
department: Sequelize.STRING,
team: Sequelize.STRING
};
this.map = {
id: 'id',
avatar_url: 'avatar',
html_url: 'url',
login: 'login'
};
// this is still fairly lowlevel - if you need to instatiate this,
// the org client needs to be loaded
// first, otherwise this will fail
this.name = 'Member';
}
sync(force) {
this.model.belongsToMany(this.dbClient.models.Organisation, {
through: 'MemberOrganisation'
});
super.sync(force);
}
async getAll(orgName, logger) {
try {
return await this.ghClient.getMembers(orgName, logger);
} catch (ex) {
console.error(ex);
}
return [];
}
async saveOrUpdate(member, organisation) {
const dbMember = mapper(member, this.map);
await this.model.findOrCreate({ where: dbMember }).spread(createdMember => {
return organisation.addMember(createdMember);
});
}
async bulkCreate(members, organisation) {
for (const member of members) {
await this.saveOrUpdate(member, organisation);
}
}
};
|
import Ember from 'ember';
const {Mixin} = Ember;
export default Mixin.create({
/**
* Get Value
*
* Get the full contents of the textarea
*
* @returns {String}
*/
getValue() {
return this.$().val();
},
/**
* Get Selection
*
* Return the currently selected text from the textarea
*
* @returns {Selection}
*/
getSelection() {
return this.$().getSelection();
},
/**
* Get Line To Cursor
*
* Fetch the string of characters from the start of the given line up to the cursor
* @returns {{text: string, start: number}}
*/
getLineToCursor() {
let selection = this.$().getSelection();
let value = this.getValue();
let lineStart;
// Normalise newlines
value = value.replace('\r\n', '\n');
// We want to look at the characters behind the cursor
lineStart = value.lastIndexOf('\n', selection.start - 1) + 1;
return {
text: value.substring(lineStart, selection.start),
start: lineStart
};
},
/**
* Get Line
*
* Return the string of characters for the line the cursor is currently on
*
* @returns {{text: string, start: number, end: number}}
*/
getLine() {
let selection = this.$().getSelection();
let value = this.getValue();
let lineStart,
lineEnd;
// Normalise newlines
value = value.replace('\r\n', '\n');
// We want to look at the characters behind the cursor
lineStart = value.lastIndexOf('\n', selection.start - 1) + 1;
lineEnd = value.indexOf('\n', selection.start);
lineEnd = lineEnd === -1 ? value.length - 1 : lineEnd;
return {
// jscs:disable
text: value.substring(lineStart, lineEnd).replace(/^\n/, ''),
// jscs:enable
start: lineStart,
end: lineEnd
};
},
/**
* Set Selection
*
* Set the section of text in the textarea that should be selected by the cursor
*
* @param {number} start
* @param {number} end
*/
setSelection(start, end) {
let $textarea = this.$();
if (start === 'end') {
start = $textarea.val().length;
}
end = end || start;
$textarea.setSelection(start, end);
},
/**
* Replace Selection
*
* @param {String} replacement - the string to replace with
* @param {number} replacementStart - where to start replacing
* @param {number} [replacementEnd] - when to stop replacing, defaults to replacementStart
* @param {String|boolean|Object} [cursorPosition] - where to put the cursor after replacing
*
* Cursor position after replacement defaults to the end of the replacement.
* Providing selectionStart only will cause the cursor to be placed there, or alternatively a range can be selected
* by providing selectionEnd.
*/
replaceSelection(replacement, replacementStart, replacementEnd, cursorPosition) {
let $textarea = this.$();
cursorPosition = cursorPosition || 'collapseToEnd';
replacementEnd = replacementEnd || replacementStart;
$textarea.setSelection(replacementStart, replacementEnd);
if (['select', 'collapseToStart', 'collapseToEnd'].indexOf(cursorPosition) !== -1) {
$textarea.replaceSelectedText(replacement, cursorPosition);
} else {
$textarea.replaceSelectedText(replacement);
if (cursorPosition.hasOwnProperty('start')) {
$textarea.setSelection(cursorPosition.start, cursorPosition.end);
} else {
$textarea.setSelection(cursorPosition, cursorPosition);
}
}
$textarea.focus();
// Tell the editor it has changed, as programmatic replacements won't trigger this automatically
this._elementValueDidChange();
this.sendAction('onChange');
}
});
|
var Employee = require("./Employee.js")
class Manager extends Employee {
constructor (name, id, email, officeNumber){
super(name,id,email)
this.officeNumber = officeNumber;
}
getRole(){
return "Manager"
}
getOfficeNumber(){
return this.officeNumber
}
}
module.exports = Manager
|
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} target
* @param {?} prop
* @return {?}
*/
export default function locale(target, prop) {
/** @type {?} */
var validLocales = ['en', 'af', 'ar-dz', 'ar-kw', 'ar-ly', 'ar-ma', 'ar-sa', 'ar-tn', 'ar', 'az', 'be',
'bg', 'bm', 'bn', 'bo', 'br', 'bs', 'ca', 'cs', 'cv', 'cy', 'da', 'de-at', 'de-ch', 'de', 'dv', 'el',
'en-au', 'en-ca', 'en-gb', 'en-ie', 'en-nz', 'eo', 'es-do', 'es-us', 'es', 'et', 'eu', 'fa', 'fi',
'fo', 'fr-ca', 'fr-ch', 'fr', 'fy', 'gd', 'gl', 'gom-latn', 'gu', 'he', 'hi', 'hr', 'hu', 'hy-am',
'id', 'is', 'it', 'ja', 'jv', 'ka', 'kk', 'km', 'kn', 'ko', 'ky', 'lb', 'lo', 'lt', 'lv', 'me',
'mi', 'mk', 'ml', 'mr', 'ms-my', 'ms', 'mt', 'my', 'nb', 'ne', 'nl-be', 'nl', 'nn', 'pa-in', 'pl',
'pt-br', 'pt', 'ro', 'ru', 'sd', 'se', 'si', 'sk', 'sl', 'sq', 'sr-cyrl', 'sr', 'ss', 'sv', 'sw',
'ta', 'te', 'tet', 'th', 'tl-ph', 'tlh', 'tr', 'tzl', 'tzm-latn', 'tzm', 'uk', 'ur', 'uz-latn', 'uz',
'vi', 'x-pseudo', 'yo', 'zh-cn', 'zh-hk', 'zh-tw'];
/** @type {?} */
var NG_ON_ONIT_NAME = 'ngOnInit';
/**
* ngOnInit might not be implemented by this component
* @type {?}
*/
var ngOnInitClone = target[NG_ON_ONIT_NAME];
Object.defineProperty(target, NG_ON_ONIT_NAME, {
value: (/**
* @return {?}
*/
function () {
if (this[prop]) {
this[prop] = this[prop];
if (validLocales.indexOf(this[prop]) === -1) {
console.error(target.constructor.name +
(": " + this[prop] + " is not valid locale value\nvalid values:\nen = English\naf = Afrikaans\nar-dz = Arabic (Algeria)\nar-kw = Arabic (Kuwait)\nar-ly = Arabic (Libya)\nar-ma = Arabic (Morocco)\nar-sa = Arabic (Saudi Arabia)\nar-tn = Arabic (Tunisia)\nar = Arabic\naz = Azerbaijani\nbe = Belarusian\nbg = Bulgarian\nbm = Bambara\nbn = Bengali\nbo = Tibetan\nbr = Breton\nbs = Bosnian\nca = Catalan\ncs = Czech\ncv = Chuvash\ncy = Welsh\nda = Danish\nde-at = German (Austria)\nde-ch = German (Switzerland)\nde = German\ndv = Divehi\nel = Greek\nen-au = English (Australia)\nen-ca = English (Canada)\nen-gb = English (United Kingdom)\nen-ie = English (Ireland)\nen-nz = English (New Zealand)\neo = Esperanto\nes-do = Spanish (Dominican Republic)\nes-us = Spanish (United States)\nes = Spanish\net = Estonian\neu = Basque\nfa = Persian\nfi = Finnish\nfo = Faroese\nfr-ca = French (Canada)\nfr-ch = French (Switzerland)\nfr = French\nfy = Western Frisian\ngd = Scottish Gaelic\ngl = Galician\ngom-latn = gom (Latin)\ngu = Gujarati\nhe = Hebrew\nhi = Hindi\nhr = Croatian\nhu = Hungarian\nhy-am = Armenian (Armenia)\nid = Indonesian\nis = Icelandic\nit = Italian\nja = Japanese\njv = Javanese\nka = Georgian\nkk = Kazakh\nkm = Khmer\nkn = Kannada\nko = Korean\nky = Kirghiz\nlb = Luxembourgish\nlo = Lao\nlt = Lithuanian\nlv = Latvian\nme = me\nmi = Maori\nmk = Macedonian\nml = Malayalam\nmr = Marathi\nms-my = Malay (Malaysia)\nms = Malay\nmt = Maltese\nmy = Burmese\nnb = Norwegian Bokm\u00E5l\nne = Nepali\nnl-be = Dutch (Belgium)\nnl = Dutch\nnn = Norwegian Nynorsk\npa-in = Punjabi (India)\npl = Polish\npt-br = Portuguese (Brazil)\npt = Portuguese\nro = Romanian\nru = Russian\nsd = Sindhi\nse = Northern Sami\nsi = Sinhala\nsk = Slovak\nsl = Slovenian\nsq = Albanian\nsr-cyrl = Serbian (Cyrillic)\nsr = Serbian\nss = Swati\nsv = Swedish\nsw = Swahili\nta = Tamil\nte = Telugu\ntet = Tetum\nth = Thai\ntl-ph = Tagalog (Philippines)\ntlh = Klingon\ntr = Turkish\ntzl = tzl\ntzm-latn = tzm (Latin)\ntzm = tzm\nuk = Ukrainian\nur = Urdu\nuz-latn = Uzbek (Latin)\nuz = Uzbek\nvi = Vietnamese\nx-pseudo = x-pseudo\nyo = Yoruba\nzh-cn = Chinese (China)\nzh-hk = Chinese (Hong Kong SAR China)\nzh-tw = Chinese (Taiwan)"));
this[prop] = 'en-us';
}
}
else {
this[prop] = 'en-us';
}
// Calling the original ngOnInit with its original context
if (ngOnInitClone) {
ngOnInitClone.call(this);
}
})
});
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibG9jYWxlLWRlY29yYXRvci5qcyIsInNvdXJjZVJvb3QiOiJuZzovL253LWNhbGVuZGFyLyIsInNvdXJjZXMiOlsibGliL2RlY29yYXRvcnMvbG9jYWxlLWRlY29yYXRvci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7QUFBQSxNQUFNLENBQUMsT0FBTyxVQUFVLE1BQU0sQ0FBQyxNQUFXLEVBQUUsSUFBWTs7UUFFaEQsWUFBWSxHQUFHLENBQUMsSUFBSSxFQUFHLElBQUksRUFBRyxPQUFPLEVBQUcsT0FBTyxFQUFHLE9BQU8sRUFBRyxPQUFPLEVBQUcsT0FBTyxFQUFHLE9BQU8sRUFBRyxJQUFJLEVBQUcsSUFBSSxFQUFHLElBQUk7UUFDaEgsSUFBSSxFQUFHLElBQUksRUFBRyxJQUFJLEVBQUcsSUFBSSxFQUFHLElBQUksRUFBRyxJQUFJLEVBQUcsSUFBSSxFQUFHLElBQUksRUFBRyxJQUFJLEVBQUcsSUFBSSxFQUFHLElBQUksRUFBRyxPQUFPLEVBQUcsT0FBTyxFQUFHLElBQUksRUFBRyxJQUFJLEVBQUcsSUFBSTtRQUNuSCxPQUFPLEVBQUcsT0FBTyxFQUFHLE9BQU8sRUFBRyxPQUFPLEVBQUcsT0FBTyxFQUFFLElBQUksRUFBRyxPQUFPLEVBQUcsT0FBTyxFQUFHLElBQUksRUFBRyxJQUFJLEVBQUcsSUFBSSxFQUFHLElBQUksRUFBRyxJQUFJO1FBQzVHLElBQUksRUFBRyxPQUFPLEVBQUcsT0FBTyxFQUFHLElBQUksRUFBRyxJQUFJLEVBQUcsSUFBSSxFQUFHLElBQUksRUFBRyxVQUFVLEVBQUcsSUFBSSxFQUFHLElBQUksRUFBRSxJQUFJLEVBQUcsSUFBSSxFQUFHLElBQUksRUFBRyxPQUFPO1FBQzdHLElBQUksRUFBRyxJQUFJLEVBQUcsSUFBSSxFQUFHLElBQUksRUFBRyxJQUFJLEVBQUcsSUFBSSxFQUFHLElBQUksRUFBRyxJQUFJLEVBQUcsSUFBSSxFQUFHLElBQUksRUFBRyxJQUFJLEVBQUcsSUFBSSxFQUFHLElBQUksRUFBRyxJQUFJLEVBQUcsSUFBSSxFQUFHLElBQUk7UUFDN0csSUFBSSxFQUFFLElBQUksRUFBRyxJQUFJLEVBQUcsSUFBSSxFQUFHLE9BQU8sRUFBRyxJQUFJLEVBQUcsSUFBSSxFQUFHLElBQUksRUFBRyxJQUFJLEVBQUcsSUFBSSxFQUFHLE9BQU8sRUFBRyxJQUFJLEVBQUcsSUFBSSxFQUFHLE9BQU8sRUFBRyxJQUFJO1FBQzlHLE9BQU8sRUFBRyxJQUFJLEVBQUcsSUFBSSxFQUFHLElBQUksRUFBRyxJQUFJLEVBQUUsSUFBSSxFQUFHLElBQUksRUFBRyxJQUFJLEVBQUcsSUFBSSxFQUFHLElBQUksRUFBRyxTQUFTLEVBQUcsSUFBSSxFQUFHLElBQUksRUFBRyxJQUFJLEVBQUcsSUFBSTtRQUM3RyxJQUFJLEVBQUcsSUFBSSxFQUFHLEtBQUssRUFBRyxJQUFJLEVBQUcsT0FBTyxFQUFHLEtBQUssRUFBRyxJQUFJLEVBQUcsS0FBSyxFQUFFLFVBQVUsRUFBRyxLQUFLLEVBQUcsSUFBSSxFQUFHLElBQUksRUFBRyxTQUFTLEVBQUcsSUFBSTtRQUNoSCxJQUFJLEVBQUcsVUFBVSxFQUFHLElBQUksRUFBRyxPQUFPLEVBQUcsT0FBTyxFQUFHLE9BQU8sQ0FBQzs7UUFDbkQsZUFBZSxHQUFHLFVBQVU7Ozs7O1FBRzVCLGFBQWEsR0FBa0IsTUFBTSxDQUFDLGVBQWUsQ0FBQztJQUU1RCxNQUFNLENBQUMsY0FBYyxDQUFDLE1BQU0sRUFBRSxlQUFlLEVBQUU7UUFDN0MsS0FBSzs7O1FBQUU7WUFDTCxJQUFJLElBQUksQ0FBQyxJQUFJLENBQUMsRUFBRTtnQkFDZCxJQUFJLENBQUMsSUFBSSxDQUFDLEdBQUcsSUFBSSxDQUFDLElBQUksQ0FBQyxDQUFDO2dCQUN4QixJQUFJLFlBQVksQ0FBQyxPQUFPLENBQUMsSUFBSSxDQUFDLElBQUksQ0FBQyxDQUFDLEtBQUssQ0FBQyxDQUFDLEVBQUU7b0JBQzNDLE9BQU8sQ0FBQyxLQUFLLENBQ1gsTUFBTSxDQUFDLFdBQVcsQ0FBQyxJQUFJO3lCQUNuQyxPQUFLLElBQUksQ0FBQyxJQUFJLENBQUMscXBFQXdIVSxDQUFBLENBQ2QsQ0FBQztvQkFDRixJQUFJLENBQUMsSUFBSSxDQUFDLEdBQUcsT0FBTyxDQUFDO2lCQUN0QjthQUNGO2lCQUFNO2dCQUNMLElBQUksQ0FBQyxJQUFJLENBQUMsR0FBRyxPQUFPLENBQUM7YUFDdEI7WUFDRCwwREFBMEQ7WUFDMUQsSUFBSyxhQUFhLEVBQUc7Z0JBQ25CLGFBQWEsQ0FBQyxJQUFJLENBQUMsSUFBSSxDQUFDLENBQUM7YUFDMUI7UUFDSCxDQUFDLENBQUE7S0FDRixDQUFDLENBQUM7QUFDTCxDQUFDIiwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0IGRlZmF1bHQgZnVuY3Rpb24gbG9jYWxlKHRhcmdldDogYW55LCBwcm9wOiBzdHJpbmcpIHtcclxuXHJcbiAgY29uc3QgdmFsaWRMb2NhbGVzID0gWydlbicgLCAnYWYnICwgJ2FyLWR6JyAsICdhci1rdycgLCAnYXItbHknICwgJ2FyLW1hJyAsICdhci1zYScgLCAnYXItdG4nICwgJ2FyJyAsICdheicgLCAnYmUnICxcclxuICAgICdiZycgLCAnYm0nICwgJ2JuJyAsICdibycgLCAnYnInICwgJ2JzJyAsICdjYScgLCAnY3MnICwgJ2N2JyAsICdjeScgLCAnZGEnICwgJ2RlLWF0JyAsICdkZS1jaCcgLCAnZGUnICwgJ2R2JyAsICdlbCcgLFxyXG4gICAgJ2VuLWF1JyAsICdlbi1jYScgLCAnZW4tZ2InICwgJ2VuLWllJyAsICdlbi1ueicsICdlbycgLCAnZXMtZG8nICwgJ2VzLXVzJyAsICdlcycgLCAnZXQnICwgJ2V1JyAsICdmYScgLCAnZmknICxcclxuICAgICdmbycgLCAnZnItY2EnICwgJ2ZyLWNoJyAsICdmcicgLCAnZnknICwgJ2dkJyAsICdnbCcgLCAnZ29tLWxhdG4nICwgJ2d1JyAsICdoZScsICdoaScgLCAnaHInICwgJ2h1JyAsICdoeS1hbScgLFxyXG4gICAgJ2lkJyAsICdpcycgLCAnaXQnICwgJ2phJyAsICdqdicgLCAna2EnICwgJ2trJyAsICdrbScgLCAna24nICwgJ2tvJyAsICdreScgLCAnbGInICwgJ2xvJyAsICdsdCcgLCAnbHYnICwgJ21lJyAsXHJcbiAgICAnbWknLCAnbWsnICwgJ21sJyAsICdtcicgLCAnbXMtbXknICwgJ21zJyAsICdtdCcgLCAnbXknICwgJ25iJyAsICduZScgLCAnbmwtYmUnICwgJ25sJyAsICdubicgLCAncGEtaW4nICwgJ3BsJyAsXHJcbiAgICAncHQtYnInICwgJ3B0JyAsICdybycgLCAncnUnICwgJ3NkJywgJ3NlJyAsICdzaScgLCAnc2snICwgJ3NsJyAsICdzcScgLCAnc3ItY3lybCcgLCAnc3InICwgJ3NzJyAsICdzdicgLCAnc3cnICxcclxuICAgICd0YScgLCAndGUnICwgJ3RldCcgLCAndGgnICwgJ3RsLXBoJyAsICd0bGgnICwgJ3RyJyAsICd0emwnLCAndHptLWxhdG4nICwgJ3R6bScgLCAndWsnICwgJ3VyJyAsICd1ei1sYXRuJyAsICd1eicgLFxyXG4gICAgJ3ZpJyAsICd4LXBzZXVkbycgLCAneW8nICwgJ3poLWNuJyAsICd6aC1oaycgLCAnemgtdHcnXTtcclxuICBjb25zdCBOR19PTl9PTklUX05BTUUgPSAnbmdPbkluaXQnO1xyXG5cclxuICAvKiogbmdPbkluaXQgbWlnaHQgbm90IGJlIGltcGxlbWVudGVkIGJ5IHRoaXMgY29tcG9uZW50ICovXHJcbiAgY29uc3QgbmdPbkluaXRDbG9uZTogRnVuY3Rpb258bnVsbCA9IHRhcmdldFtOR19PTl9PTklUX05BTUVdO1xyXG5cclxuICBPYmplY3QuZGVmaW5lUHJvcGVydHkodGFyZ2V0LCBOR19PTl9PTklUX05BTUUsIHtcclxuICAgIHZhbHVlOiBmdW5jdGlvbigpIHtcclxuICAgICAgaWYgKHRoaXNbcHJvcF0pIHtcclxuICAgICAgICB0aGlzW3Byb3BdID0gdGhpc1twcm9wXTtcclxuICAgICAgICBpZiAodmFsaWRMb2NhbGVzLmluZGV4T2YodGhpc1twcm9wXSkgPT09IC0xKSB7XHJcbiAgICAgICAgICBjb25zb2xlLmVycm9yKFxyXG4gICAgICAgICAgICB0YXJnZXQuY29uc3RydWN0b3IubmFtZSArXHJcbmA6ICR7dGhpc1twcm9wXX0gaXMgbm90IHZhbGlkIGxvY2FsZSB2YWx1ZVxcbnZhbGlkIHZhbHVlczpcclxuZW4gPSBFbmdsaXNoXHJcbmFmID0gQWZyaWthYW5zXHJcbmFyLWR6ID0gQXJhYmljIChBbGdlcmlhKVxyXG5hci1rdyA9IEFyYWJpYyAoS3V3YWl0KVxyXG5hci1seSA9IEFyYWJpYyAoTGlieWEpXHJcbmFyLW1hID0gQXJhYmljIChNb3JvY2NvKVxyXG5hci1zYSA9IEFyYWJpYyAoU2F1ZGkgQXJhYmlhKVxyXG5hci10biA9IEFyYWJpYyAoVHVuaXNpYSlcclxuYXIgPSBBcmFiaWNcclxuYXogPSBBemVyYmFpamFuaVxyXG5iZSA9IEJlbGFydXNpYW5cclxuYmcgPSBCdWxnYXJpYW5cclxuYm0gPSBCYW1iYXJhXHJcbmJuID0gQmVuZ2FsaVxyXG5ibyA9IFRpYmV0YW5cclxuYnIgPSBCcmV0b25cclxuYnMgPSBCb3NuaWFuXHJcbmNhID0gQ2F0YWxhblxyXG5jcyA9IEN6ZWNoXHJcbmN2ID0gQ2h1dmFzaFxyXG5jeSA9IFdlbHNoXHJcbmRhID0gRGFuaXNoXHJcbmRlLWF0ID0gR2VybWFuIChBdXN0cmlhKVxyXG5kZS1jaCA9IEdlcm1hbiAoU3dpdHplcmxhbmQpXHJcbmRlID0gR2VybWFuXHJcbmR2ID0gRGl2ZWhpXHJcbmVsID0gR3JlZWtcclxuZW4tYXUgPSBFbmdsaXNoIChBdXN0cmFsaWEpXHJcbmVuLWNhID0gRW5nbGlzaCAoQ2FuYWRhKVxyXG5lbi1nYiA9IEVuZ2xpc2ggKFVuaXRlZCBLaW5nZG9tKVxyXG5lbi1pZSA9IEVuZ2xpc2ggKElyZWxhbmQpXHJcbmVuLW56ID0gRW5nbGlzaCAoTmV3IFplYWxhbmQpXHJcbmVvID0gRXNwZXJhbnRvXHJcbmVzLWRvID0gU3BhbmlzaCAoRG9taW5pY2FuIFJlcHVibGljKVxyXG5lcy11cyA9IFNwYW5pc2ggKFVuaXRlZCBTdGF0ZXMpXHJcbmVzID0gU3BhbmlzaFxyXG5ldCA9IEVzdG9uaWFuXHJcbmV1ID0gQmFzcXVlXHJcbmZhID0gUGVyc2lhblxyXG5maSA9IEZpbm5pc2hcclxuZm8gPSBGYXJvZXNlXHJcbmZyLWNhID0gRnJlbmNoIChDYW5hZGEpXHJcbmZyLWNoID0gRnJlbmNoIChTd2l0emVybGFuZClcclxuZnIgPSBGcmVuY2hcclxuZnkgPSBXZXN0ZXJuIEZyaXNpYW5cclxuZ2QgPSBTY290dGlzaCBHYWVsaWNcclxuZ2wgPSBHYWxpY2lhblxyXG5nb20tbGF0biA9IGdvbSAoTGF0aW4pXHJcbmd1ID0gR3VqYXJhdGlcclxuaGUgPSBIZWJyZXdcclxuaGkgPSBIaW5kaVxyXG5ociA9IENyb2F0aWFuXHJcbmh1ID0gSHVuZ2FyaWFuXHJcbmh5LWFtID0gQXJtZW5pYW4gKEFybWVuaWEpXHJcbmlkID0gSW5kb25lc2lhblxyXG5pcyA9IEljZWxhbmRpY1xyXG5pdCA9IEl0YWxpYW5cclxuamEgPSBKYXBhbmVzZVxyXG5qdiA9IEphdmFuZXNlXHJcbmthID0gR2VvcmdpYW5cclxua2sgPSBLYXpha2hcclxua20gPSBLaG1lclxyXG5rbiA9IEthbm5hZGFcclxua28gPSBLb3JlYW5cclxua3kgPSBLaXJnaGl6XHJcbmxiID0gTHV4ZW1ib3VyZ2lzaFxyXG5sbyA9IExhb1xyXG5sdCA9IExpdGh1YW5pYW5cclxubHYgPSBMYXR2aWFuXHJcbm1lID0gbWVcclxubWkgPSBNYW9yaVxyXG5tayA9IE1hY2Vkb25pYW5cclxubWwgPSBNYWxheWFsYW1cclxubXIgPSBNYXJhdGhpXHJcbm1zLW15ID0gTWFsYXkgKE1hbGF5c2lhKVxyXG5tcyA9IE1hbGF5XHJcbm10ID0gTWFsdGVzZVxyXG5teSA9IEJ1cm1lc2VcclxubmIgPSBOb3J3ZWdpYW4gQm9rbcOlbFxyXG5uZSA9IE5lcGFsaVxyXG5ubC1iZSA9IER1dGNoIChCZWxnaXVtKVxyXG5ubCA9IER1dGNoXHJcbm5uID0gTm9yd2VnaWFuIE55bm9yc2tcclxucGEtaW4gPSBQdW5qYWJpIChJbmRpYSlcclxucGwgPSBQb2xpc2hcclxucHQtYnIgPSBQb3J0dWd1ZXNlIChCcmF6aWwpXHJcbnB0ID0gUG9ydHVndWVzZVxyXG5ybyA9IFJvbWFuaWFuXHJcbnJ1ID0gUnVzc2lhblxyXG5zZCA9IFNpbmRoaVxyXG5zZSA9IE5vcnRoZXJuIFNhbWlcclxuc2kgPSBTaW5oYWxhXHJcbnNrID0gU2xvdmFrXHJcbnNsID0gU2xvdmVuaWFuXHJcbnNxID0gQWxiYW5pYW5cclxuc3ItY3lybCA9IFNlcmJpYW4gKEN5cmlsbGljKVxyXG5zciA9IFNlcmJpYW5cclxuc3MgPSBTd2F0aVxyXG5zdiA9IFN3ZWRpc2hcclxuc3cgPSBTd2FoaWxpXHJcbnRhID0gVGFtaWxcclxudGUgPSBUZWx1Z3VcclxudGV0ID0gVGV0dW1cclxudGggPSBUaGFpXHJcbnRsLXBoID0gVGFnYWxvZyAoUGhpbGlwcGluZXMpXHJcbnRsaCA9IEtsaW5nb25cclxudHIgPSBUdXJraXNoXHJcbnR6bCA9IHR6bFxyXG50em0tbGF0biA9IHR6bSAoTGF0aW4pXHJcbnR6bSA9IHR6bVxyXG51ayA9IFVrcmFpbmlhblxyXG51ciA9IFVyZHVcclxudXotbGF0biA9IFV6YmVrIChMYXRpbilcclxudXogPSBVemJla1xyXG52aSA9IFZpZXRuYW1lc2VcclxueC1wc2V1ZG8gPSB4LXBzZXVkb1xyXG55byA9IFlvcnViYVxyXG56aC1jbiA9IENoaW5lc2UgKENoaW5hKVxyXG56aC1oayA9IENoaW5lc2UgKEhvbmcgS29uZyBTQVIgQ2hpbmEpXHJcbnpoLXR3ID0gQ2hpbmVzZSAoVGFpd2FuKWBcclxuICAgICAgICAgICk7XHJcbiAgICAgICAgICB0aGlzW3Byb3BdID0gJ2VuLXVzJztcclxuICAgICAgICB9XHJcbiAgICAgIH0gZWxzZSB7XHJcbiAgICAgICAgdGhpc1twcm9wXSA9ICdlbi11cyc7XHJcbiAgICAgIH1cclxuICAgICAgLy8gQ2FsbGluZyB0aGUgb3JpZ2luYWwgbmdPbkluaXQgd2l0aCBpdHMgb3JpZ2luYWwgY29udGV4dFxyXG4gICAgICBpZiAoIG5nT25Jbml0Q2xvbmUgKSB7XHJcbiAgICAgICAgbmdPbkluaXRDbG9uZS5jYWxsKHRoaXMpO1xyXG4gICAgICB9XHJcbiAgICB9XHJcbiAgfSk7XHJcbn1cclxuIl19
|
import logging
import pytest
import salt.modules.etcd_mod as etcd_mod
import salt.states.etcd_mod as etcd_state
from salt.utils.etcd_util import get_conn
from tests.support.pytest.etcd import * # pylint: disable=wildcard-import,unused-wildcard-import
docker = pytest.importorskip("docker")
log = logging.getLogger(__name__)
pytestmark = [
pytest.mark.windows_whitelisted,
pytest.mark.skip_if_binaries_missing("docker", "dockerd", check_all=False),
]
@pytest.fixture
def configure_loader_modules(minion_opts):
return {
etcd_state: {
"__salt__": {
"etcd.get": etcd_mod.get_,
"etcd.set": etcd_mod.set_,
"etcd.rm": etcd_mod.rm_,
},
},
etcd_mod: {
"__opts__": minion_opts,
"__utils__": {
"etcd_util.get_conn": get_conn,
},
},
}
@pytest.fixture(scope="module")
def minion_config_overrides(etcd_profile):
return etcd_profile
@pytest.fixture(scope="module")
def etcd_client(minion_opts, profile_name):
return get_conn(minion_opts, profile=profile_name)
@pytest.fixture(scope="module")
def prefix():
return "/salt/states/test"
@pytest.fixture(autouse=True)
def cleanup_prefixed_entries(etcd_client, prefix):
"""
Cleanup after each test to ensure a consistent starting state.
"""
try:
assert etcd_client.get(prefix, recurse=True) is None
yield
finally:
etcd_client.delete(prefix, recurse=True)
def test_basic_operations(subtests, profile_name, prefix, etcd_version):
"""
Test basic CRUD operations
"""
with subtests.test("Removing a non-existent key should not explode"):
expected = {
"name": "{}/2/3".format(prefix),
"comment": "Key does not exist",
"result": True,
"changes": {},
}
assert etcd_state.rm("{}/2/3".format(prefix), profile=profile_name) == expected
with subtests.test("We should be able to set a value"):
expected = {
"name": "{}/1".format(prefix),
"comment": "New key created",
"result": True,
"changes": {"{}/1".format(prefix): "one"},
}
assert (
etcd_state.set_("{}/1".format(prefix), "one", profile=profile_name)
== expected
)
with subtests.test(
"We should be able to create an empty directory and set values in it"
):
if etcd_version in (EtcdVersion.v2, EtcdVersion.v3_v2_mode):
expected = {
"name": "{}/2".format(prefix),
"comment": "New directory created",
"result": True,
"changes": {"{}/2".format(prefix): "Created"},
}
assert (
etcd_state.directory("{}/2".format(prefix), profile=profile_name)
== expected
)
expected = {
"name": "{}/2/3".format(prefix),
"comment": "New key created",
"result": True,
"changes": {"{}/2/3".format(prefix): "two-three"},
}
assert (
etcd_state.set_("{}/2/3".format(prefix), "two-three", profile=profile_name)
== expected
)
with subtests.test("We should be able to remove an existing key"):
expected = {
"name": "{}/2/3".format(prefix),
"comment": "Key removed",
"result": True,
"changes": {"{}/2/3".format(prefix): "Deleted"},
}
assert etcd_state.rm("{}/2/3".format(prefix), profile=profile_name) == expected
def test_with_missing_profile(subtests, prefix, etcd_version, etcd_port):
"""
Test the correct response when the profile is missing and we can't connect
"""
if etcd_version in (EtcdVersion.v2, EtcdVersion.v3_v2_mode) and etcd_port != 2379:
# Only need to run this once
with subtests.test("Test no profile and bad connection in set_"):
ret = etcd_state.set_("{}/1".format(prefix), "one")
assert not ret["result"]
assert ret["comment"] == etcd_state.NO_PROFILE_MSG
with subtests.test("Test no profile and bad connection in directory"):
ret = etcd_state.directory("{}/2".format(prefix))
assert not ret["result"]
assert ret["comment"] == etcd_state.NO_PROFILE_MSG
with subtests.test("Test no profile and bad connection in rm"):
ret = etcd_state.rm("{}/2/3".format(prefix))
assert not ret["result"]
assert ret["comment"] == etcd_state.NO_PROFILE_MSG
|
(function($) {
$(document).ready(function() {
$('.modal-backdrop').remove();
/*********************
* Category Insert *
*********************/
$(document).on('submit', 'form#category_form', function(event) {
event.preventDefault();
$('#error-category').text('');
$.ajax({
url: 'category-store',
type: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(response) {
if (response) {
$('form#category_form')[0].reset();
swal("Good job!", "Category Added Successful", "success");
allCategories();
}
},
error: function(response) {
$('#error-category').text(response.responseJSON.errors.name);
}
});
});
/*********************
* Category show *
*********************/
function allCategories() {
$.ajax({
url: 'category-show',
success: function(response) {
$('tbody#category_tbody').html(response);
}
});
}
allCategories();
/*********************
* Category Delete *
*********************/
$(document).on('click', 'a#delete_id', function(event) {
event.preventDefault();
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this Category!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
let id = $(this).attr('del_id');
$.ajax({
url: 'category-delete/' + id,
success: function(response) {
if (willDelete) {
swal("Opps! Your Category file has been deleted!", {
icon: "success",
});
allCategories();
} else {
swal("Your Category hasn't deleted");
}
}
});
});
});
/*********************
* Category Edit *
*********************/
$(document).on('click', 'a#edit_id', function(event) {
event.preventDefault();
let id = $(this).attr('edit_id');
$.ajax({
url: 'category-edit/' + id,
success: function(response) {
$("#edit_modal input[name='name']").val(response.name);
$("#edit_modal input[name='id']").val(response.id);
}
});
});
/*********************
* Category Update *
*********************/
$(document).on('submit', 'form#category_update_form', function(event) {
event.preventDefault();
$('#error-category').text('');
$.ajax({
url: 'category-update',
method: "POST",
contentType: false,
processData: false,
data: new FormData(this),
success: function(response) {
swal("Good job!", "You clicked the button!", "success");
allCategories();
}
});
});
});
})(jQuery)
|
import requests
r = requests.get('http://webconcepts.info/concepts/http-status-code.json')
json = r.json()
template = "response-template.html"
for i in json["values"]:
with open(template) as f:
content = f.read()
new_content = content
error_code = int(i["value"])
#print("Error Code: %d" % (error_code))
if error_code == 418 or error_code < 400 or error_code > 599:
continue
# Set the background and body color for the different error codes
body_color = "#fefefe"
if error_code < 200:
# 1xx codes
bg_color = "#78909C"
elif error_code < 300:
# 2xx codes
bg_color = "#1E88E5"
elif error_code < 500:
# 3xx and 4xx codes
bg_color = "#e74c3c"
elif error_code < 600:
# 5xx codes
bg_color = "#f1c40f"
new_content = new_content.replace("$ERROR_CODE", i["value"])
new_content = new_content.replace("$ERROR_NAME", i["description"])
new_content = new_content.replace("$ERROR_DESC", i["details"][0]["description"])
new_content = new_content.replace("$BG_COLOR", bg_color)
new_content = new_content.replace("$BODY_COLOR", body_color)
with open(i["value"] + ".html", "w") as output_file:
output_file.write(new_content)
print(f"ErrorDocument {error_code} /errors/{error_code}.html")
|
"""Apps for DBBackup"""
from django.apps import AppConfig
from django.utils.translation import gettext_lazy
from dbbackup import log
class DbbackupConfig(AppConfig):
"""
Config for DBBackup application.
"""
name = 'dbbackup'
label = 'dbbackup'
verbose_name = gettext_lazy('Backup and restore')
def ready(self):
log.load()
|
/*
* testlistfmtasync.js - test the list formatter object
*
* Copyright © 2018, JEDLSoft
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSe-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import ListFmt from "../lib/ListFmt.js";
module.exports.testlistfmtasync = {
testListFmtAsyncConstructorEmpty: function(test) {
new ListFmt({
sync: false,
onLoad: function(fmt) {
test.expect(1);
test.ok(fmt !== null);
test.done();
}
});
},
testListFmtAsyncTestPropertyTwo: function(test) {
new ListFmt({
sync: false,
onLoad: function(fmt) {
test.expect(2);
test.ok(fmt !== null);
test.equal(fmt.format(["true", "false"]), "true & false");
test.done();
}
});
},
testListFmtAsyncbnINNumberFormatFour: function(test) {
new ListFmt({
locale: "bn-IN",
sync: false,
onLoad: function(fmt) {
test.expect(2);
test.ok(fmt !== null);
test.equal(fmt.format(["এক", "দুই", "তিন", "চার"]), "এক, দুই, তিন এবং চার");
test.done();
}
});
},
testListFmtAsynckoKRNumberFormatThree: function(test) {
new ListFmt({
locale: "ko-KR",
sync: false,
onLoad: function(fmt) {
test.expect(2);
test.ok(fmt !== null);
test.equal(fmt.format(["하나", "둘", "셋"]), "하나, 둘 및 셋");
test.done();
}
});
}
};
|
/* config-overrides.js */
const path = require("path");
const ModuleScopePlugin = require("react-dev-utils/ModuleScopePlugin");
module.exports = {
// The function to use to create a webpack dev server configuration when running the development
// server with 'npm run start' or 'yarn start'.
// Example: set the dev server to use a specific certificate in https.
devServer: function(configFunction) {
// Return the replacement function for create-react-app to use to generate the Webpack
// Development Server config. "configFunction" is the function that would normally have
// been used to generate the Webpack Development server config - you can use it to create
// a starting configuration to then modify instead of having to create a config from scratch.
return function(proxy, allowedHost) {
// Create the default config by calling configFunction with the proxy/allowedHost parameters
const config = configFunction(proxy, allowedHost);
config.headers = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET",
"Access-Control-Allow-Headers":
"X-Requested-With, content-type, Authorization",
};
// Return your customised Webpack Development Server config.
return config;
};
},
};
|
#
# Copyright (c) 2019, Neptune Labs Sp. z o.o.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import io
import os
import numpy
import six
from PIL import Image
from neptune.exceptions import FileNotFound, InvalidChannelValue
def get_image_content(image):
if isinstance(image, six.string_types):
if not os.path.exists(image):
raise FileNotFound(image)
with open(image, 'rb') as image_file:
return image_file.read()
elif isinstance(image, numpy.ndarray):
return _get_numpy_as_image(image)
elif isinstance(image, Image.Image):
return _get_pil_image_data(image)
else:
try:
from matplotlib import figure
if isinstance(image, figure.Figure):
return _get_figure_as_image(image)
except ImportError:
pass
try:
from torch import Tensor as TorchTensor
if isinstance(image, TorchTensor):
return _get_numpy_as_image(image.detach().numpy())
except ImportError:
pass
try:
from tensorflow import Tensor as TensorflowTensor
if isinstance(image, TensorflowTensor):
return _get_numpy_as_image(image.numpy())
except ImportError:
pass
raise InvalidChannelValue(expected_type='image', actual_type=type(image).__name__)
def _get_figure_as_image(figure):
with io.BytesIO() as image_buffer:
figure.savefig(image_buffer, format='png', bbox_inches="tight")
return image_buffer.getvalue()
def _get_pil_image_data(image):
with io.BytesIO() as image_buffer:
image.save(image_buffer, format='PNG')
return image_buffer.getvalue()
def _get_numpy_as_image(array):
array *= 255
shape = array.shape
if len(shape) == 2:
return _get_pil_image_data(Image.fromarray(array.astype(numpy.uint8)))
if len(shape) == 3:
if shape[2] == 1:
array2d = numpy.array([[col[0] for col in row] for row in array])
return _get_pil_image_data(Image.fromarray(array2d.astype(numpy.uint8)))
if shape[2] in (3, 4):
return _get_pil_image_data(Image.fromarray(array.astype(numpy.uint8)))
raise ValueError("Incorrect size of numpy.ndarray. Should be 2-dimensional or"
" 3-dimensional with 3rd dimension of size 1, 3 or 4.")
|
!function(i,c){var r,a,l="createElement",g="getElementsByTagName",b="length",E="style",s="title",h="undefined",k="setAttribute",w="getAttribute",x=null,y="__svgInject",A="--inject-",C=new RegExp(A+"\\d+","g"),S="LOAD_FAIL",t="SVG_NOT_SUPPORTED",I="SVG_INVALID",d=["src","alt","onload","onerror"],L=c[l]("a"),j=typeof SVGRect!=h,o={useCache:!0,copyAttributes:!0,makeIdsUnique:!0},G={clipPath:["clip-path"],"color-profile":x,cursor:x,filter:x,linearGradient:["fill","stroke"],marker:["marker",
"marker-end","marker-mid","marker-start"],mask:x,pattern:["fill","stroke"],radialGradient:["fill","stroke"]},u=1,f=2,N=1;function O(e){return(r=r||new XMLSerializer).serializeToString(e)}function T(e,r){var t,n,i,o,a=A+N++,f=/url\("?#([a-zA-Z][\w:.=-]*)"?\)/g,u=e.querySelectorAll("[id]"),c=r?[]:x,l={},s=[],d=!1;if(u[b]){for(i=0;i<u[b];i++)(n=u[i].localName)in G&&(l[n]=1);for(n in l)(G[n]||[n]).forEach(function(e){s.indexOf(e)<0&&s.push(e)});s[b]&&s.push(E);var v,p,m,h=e[g]("*"),y=e;for(
i=-1;y!=x;){if(y.localName==E)(m=(p=y.textContent)&&p.replace(f,function(e,r){return c&&(c[r]=1),"url(#"+r+a+")"}))!==p&&(y.textContent=m);else if(y.hasAttributes()){for(o=0;o<s[b];o++)v=s[o],(m=(p=y[w](v))&&p.replace(f,function(e,r){return c&&(c[r]=1),"url(#"+r+a+")"}))!==p&&y[k](v,m);["xlink:href","href"].forEach(function(e){var r=y[w](e);/^\s*#/.test(r)&&(r=r.trim(),y[k](e,r+a),c&&(c[r.substring(1)]=1))})}y=h[++i]}for(i=0;i<u[b];i++)t=u[i],c&&!c[t.id]||(t.id+=a,d=!0)}return d}function P(e,r,t
,n){if(r){r[k]("data-inject-url",t);var i=e.parentNode;if(i){n.copyAttributes&&function(e,r){for(var t,n,i,o=e.attributes,a=0;a<o[b];a++)if(n=(t=o[a]).name,-1==d.indexOf(n))if(i=t.value,n==s){var f,u=r.firstElementChild;u&&u.localName.toLowerCase()==s?f=u:(f=c[l+"NS"]("http://www.w3.org/2000/svg",s),r.insertBefore(f,u)),f.textContent=i}else r[k](n,i)}(e,r);var o=n.beforeInject,a=o&&o(e,r)||r;i.replaceChild(a,e),e[y]=u,p(e);var f=n.afterInject;f&&f(e,a)}}else _(e,n)}function v(){for(var e={},
r=arguments,t=0;t<r[b];t++){var n=r[t];for(var i in n)n.hasOwnProperty(i)&&(e[i]=n[i])}return e}function V(e,r){if(r){var t;try{n=e,t=(a=a||new DOMParser).parseFromString(n,"text/xml")}catch(o){return x}return t[g]("parsererror")[b]?x:t.documentElement}var n,i=c.createElement("div");return i.innerHTML=e,i.firstElementChild}function p(e){e.removeAttribute("onload")}function n(e){console.error("SVGInject: "+e)}function m(e,r,t){e[y]=f,t.onFail?t.onFail(e,r):n(r)}function _(e,r){p(e),m(e,I,r)}
function D(e,r){p(e),m(e,t,r)}function F(e,r){m(e,S,r)}function M(e){e.onload=x,e.onerror=x}function q(e){n("no img element")}var e=function R(e,r){var t=v(o,r),m={};function n(a,f){f=v(t,f);var e=function(r){var e=function(){var e=f.onAllFinish;e&&e(),r&&r()};if(a&&typeof a[b]!=h){var t=0,n=a[b];if(0==n)e();else for(var i=function(){++t==n&&e()},o=0;o<n;o++)u(a[o],f,i)}else u(a,f,e)};return typeof Promise==h?e():new Promise(e)}function u(u,c,e){if(u){var r=u[y];if(r)Array.isArray(r)?r.push(e
):e();else{if(M(u),!j)return D(u,c),void e();var t=c.beforeLoad,n=t&&t(u)||u[w]("src");if(!n)return""===n&&F(u,c),void e();var i=[];u[y]=i;var l=function(){e(),i.forEach(function(e){e()})},s=(f=n,L.href=f,L.href),d=c.useCache,v=c.makeIdsUnique,p=function(r){d&&(m[s].forEach(function(e){e(r)}),m[s]=r)};if(d){var o,a=function(e){if(e===S)F(u,c);else if(e===I)_(u,c);else{var r,t=e[0],n=e[1],i=e[2];v&&(t===x?(t=T(r=V(n,!1),!1),e[0]=t,e[2]=t&&O(r)):t&&(n=i.replace(C,A+N++))),r=r||V(n,!1),P(u,r,s,c)}
l()};if(typeof(o=m[s])!=h)return void(o.isCallbackQueue?o.push(a):a(o));(o=[]).isCallbackQueue=!0,m[s]=o}!function(e,r,t){if(e){var n=new XMLHttpRequest;n.onreadystatechange=function(){if(4==n.readyState){var e=n.status;200==e?r(n.responseXML,n.responseText.trim()):400<=e?t():0==e&&t()}},n.open("GET",e,!0),n.send()}}(s,function(e,r){var t=e instanceof Document?e.documentElement:V(r,!0),n=c.afterLoad;if(n){var i=n(t,r)||t;if(i){var o="string"==typeof i;r=o?i:O(t),t=o?V(i,!0):i}}if(
t instanceof SVGElement){var a=x;if(v&&(a=T(t,!1)),d){var f=a&&O(t);p([a,r,f])}P(u,t,s,c)}else _(u,c),p(I);l()},function(){F(u,c),p(S),l()})}}else q();var f}return j&&function(e){var r=c[g]("head")[0];if(r){var t=c[l](E);t.type="text/css",t.appendChild(c.createTextNode(e)),r.appendChild(t)}}('img[onload^="'+e+'("]{visibility:hidden;}'),n.setOptions=function(e){t=v(t,e)},n.create=R,n.err=function(e,r){e?e[y]!=f&&(M(e),j?(p(e),F(e,t)):D(e,t),r&&(p(e),e.src=r)):q()},i[e]=n}("SVGInject")
;"object"==typeof module&&"object"==typeof module.exports&&(module.exports=e)}(window,document);
|
/**
* @name views.customizePlayer
* @namespace Create a new custom player or customize an existing one.
*/
define(["dao", "globals", "ui", "core/finances", "core/league", "core/player", "core/team", "lib/faces", "lib/knockout", "lib/knockout.mapping", "util/bbgmView", "util/helpers"], function (dao, g, ui, finances, league, player, team, faces, ko, komapping, bbgmView, helpers) {
"use strict";
var mapping;
// Same as faces.generate, but round of long decimals
function generateFace() {
var face;
face = faces.generate();
face.fatness = helpers.round(face.fatness, 2);
face.eyes[0].angle = helpers.round(face.eyes[0].angle, 1);
face.eyes[1].angle = helpers.round(face.eyes[1].angle, 1);
return face;
}
function get(req) {
if (!g.godMode) {
return {
errorMessage: 'You can\'t customize players unless you enable <a href="' + helpers.leagueUrl(["god_mode"]) + '">God Mode</a>.'
};
}
if (req.params.hasOwnProperty("pid")) {
return {
pid: parseInt(req.params.pid, 10)
};
}
return {
pid: null
};
}
function InitViewModel() {
var ratingKeys;
this.p = {
face: ko.observable(),
ratings: ko.observableArray(),
born: {
year: ko.observable()
},
contract: {
amount: ko.observable(),
exp: ko.observable()
}
};
this.positions = [];
// Used to kepe track of the TID for an edited player
this.originalTid = ko.observable(null);
// Easy access to ratings array, since it could have any number of entries and we only want the last one
this.ratings = {};
ratingKeys = ["pot", "hgt", "stre", "spd", "jmp", "endu", "ins", "dnk", "ft", "fg", "tp", "blk", "stl", "drb", "pss", "reb"];
ratingKeys.forEach(function (ratingKey) {
this.ratings[ratingKey] = ko.computed({
read: function () {
// Critical: this will always call p.ratings() so it knows to update after player is loaded
if (this.p.ratings().length > 0) {
return this.p.ratings()[this.p.ratings().length - 1][ratingKey]();
}
return 0;
},
write: function (value) {
var rating;
rating = helpers.bound(parseInt(value, 10), 0, 100);
if (isNaN(rating)) { rating = 0; }
this.p.ratings()[this.p.ratings().length - 1][ratingKey](rating);
},
owner: this
});
}, this);
// Set born.year based on age input
this.age = ko.computed({
read: function () {
return g.season - this.p.born.year();
},
write: function (value) {
this.p.born.year(g.season - parseInt(value, 10));
},
owner: this
});
// Contract stuff
this.contract = {
amount: ko.computed({
read: function () {
return this.p.contract.amount() / 1000;
},
write: function (value) {
var amount;
// Allow any value, even above or below normal limits, but round to $10k
// amount = helpers.round(100 * parseFloat(value)) * 10;
amount = 0;
if (isNaN(amount)) { amount = g.minContract; }
this.p.contract.amount(amount);
},
owner: this
}),
exp: ko.computed({
read: function () {
return this.p.contract.exp();
},
write: function (value) {
var season;
season = parseInt(value, 10);
if (isNaN(season)) { season = g.season; }
// No contracts expiring in the past
if (season < g.season) {
season = g.season;
}
// If current season contracts already expired, then current season can't be allowed for new contract
if (season === g.season && g.phase >= g.PHASE.RESIGN_PLAYERS) {
season += 1;
}
this.p.contract.exp(season);
},
owner: this
})
};
}
mapping = {
teams: {
create: function (options) {
return options.data;
}
}
};
function updateCustomizePlayer(inputs, updateEvents) {
if (updateEvents.indexOf("firstRun") >= 0) {
return team.filter({
attrs: ["tid", "region", "name"],
season: g.season
}).then(function (teams) {
var i, positions, seasonOffset, vars;
// Once a new draft class is generated, if the next season hasn't started, need to bump up year numbers
if (g.phase < g.PHASE.FREE_AGENCY) {
seasonOffset = 0;
} else {
seasonOffset = 1;
}
for (i = 0; i < teams.length; i++) {
teams[i].text = teams[i].region + " " + teams[i].name;
}
teams.unshift({
tid: g.PLAYER.RETIRED,
text: "Left School"
});
teams.unshift({
tid: g.PLAYER.UNDRAFTED_3,
text: (g.season + seasonOffset + 2) + " Recruit"
});
teams.unshift({
tid: g.PLAYER.UNDRAFTED_2,
text: (g.season + seasonOffset + 1) + " Recruit"
});
teams.unshift({
tid: g.PLAYER.UNDRAFTED,
text: (g.season + seasonOffset) + " Recruit"
});
teams.unshift({
tid: g.PLAYER.FREE_AGENT,
text: "Division II"
});
positions = ["PG", "SG", "SF", "PF", "C", "G", "GF", "F", "FC"];
vars = {
appearanceOptions: ["Cartoon Face", "Image URL"],
faceOptions: {
eyes: [0, 1, 2, 3],
nose: [0, 1, 2],
mouth: [0, 1, 2, 3, 4],
hair: [0, 1, 2, 3, 4]
},
positions: positions,
teams: teams
};
if (inputs.pid === null) {
// Generate new player as basis
return dao.teams.get({key: g.userTid}).then(function (t) {
var p, scoutingRank;
scoutingRank = finances.getRankLastThree(t, "expenses", "scouting");
p = player.generate(g.PLAYER.FREE_AGENT,
19,
null,
50,
50,
g.season,
false,
scoutingRank);
p.face.fatness = helpers.round(p.face.fatness, 2);
p.face.eyes[0].angle = helpers.round(p.face.eyes[0].angle, 1);
p.face.eyes[1].angle = helpers.round(p.face.eyes[1].angle, 1);
vars.appearanceOption = "Cartoon Face";
p.imgURL = "http://";
vars.p = p;
return vars;
});
}
// Load a player to edit
return dao.players.get({key: inputs.pid}).then(function (p) {
if (p.imgURL.length > 0) {
vars.appearanceOption = "Image URL";
} else {
vars.appearanceOption = "Cartoon Face";
p.imgURL = "http://";
}
vars.originalTid = p.tid;
vars.p = p;
return vars;
});
});
}
}
function uiFirst(vm) {
if (vm.originalTid() === null) {
ui.title("Create A Player");
} else {
ui.title("Edit Player");
}
document.getElementById("randomize-face").addEventListener("click", function () {
vm.p.face(komapping.fromJS(generateFace()));
});
// Since there are two eyes and the updated observable is the first one, update the second in parallel
ko.computed(function () {
vm.p.face().eyes()[1].id(vm.p.face().eyes()[0].id());
}).extend({throttle: 1});
ko.computed(function () {
vm.p.face().eyes()[1].angle(vm.p.face().eyes()[0].angle());
}).extend({throttle: 1});
// Update picture display
ko.computed(function () {
// This ensures it's not drawn when not visible (like if defaulting to Image URL for a
// player), and it also ensures that this computed is called when appearanceOption
// changes. Without this "if", it hows a corrupted display for some reason if Image URL
// is default and the face is switched to.
if (vm.appearanceOption() === "Cartoon Face") {
faces.display("picture", ko.toJS(vm.p.face));
}
}).extend({throttle: 1});
document.getElementById("create-a-player").addEventListener("click", function () {
var p, pid, r;
p = komapping.toJS(vm.p);
// Fix integers that Knockout may have mangled
p.tid = parseInt(p.tid, 10);
p.hgt = parseInt(p.hgt, 10);
p.weight = parseInt(p.weight, 10);
p.face.fatness = parseFloat(p.face.fatness);
p.face.eyes[0].angle = parseFloat(p.face.eyes[0].angle);
p.face.eyes[1].angle = parseFloat(p.face.eyes[1].angle);
// Fix draft season
if (p.tid === g.PLAYER.UNDRAFTED || p.tid === g.PLAYER.UNDRAFTED_2 || p.tid === g.PLAYER.UNDRAFTED_3) {
if (p.tid === g.PLAYER.UNDRAFTED) {
p.draft.year = g.season;
} else if (p.tid === g.PLAYER.UNDRAFTED_2) {
p.draft.year = g.season + 1;
} else if (p.tid === g.PLAYER.UNDRAFTED_3) {
p.draft.year = g.season + 2;
}
// Once a new draft class is generated, if the next season hasn't started, need to bump up year numbers
if (g.phase >= g.PHASE.FREE_AGENCY) {
p.draft.year += 1;
}
}
// Set ovr, skills, and bound pot by ovr
r = p.ratings.length - 1;
p.ratings[r].ovr = player.ovr(p.ratings[r]);
p.ratings[r].skills = player.skills(p.ratings[r]);
if (p.ratings[r].ovr > p.ratings[r].pot) {
p.ratings[r].pot = p.ratings[r].ovr;
}
// If player was retired, add ratings (but don't develop, because that would change ratings)
if (vm.originalTid() === g.PLAYER.RETIRED) {
if (g.season - p.ratings[r].season > 0) {
p = player.addRatingsRow(p, 15);
}
}
// Only save image URL if it's selected
if (vm.appearanceOption() !== "Image URL") {
p.imgURL = "";
}
// If we are *creating* a player who is not a draft prospect, make sure he won't show up in the draft this year
if (p.tid !== g.PLAYER.UNDRAFTED && p.tid !== g.PLAYER.UNDRAFTED_2 && p.tid !== g.PLAYER.UNDRAFTED_3 && g.phase < g.PHASE.FREE_AGENCY) {
// This makes sure it's only for created players, not edited players
if (!p.hasOwnProperty("pid")) {
p.draft.year = g.season - 1;
}
}
// Similarly, if we are editing a draft prospect and moving him to a team, make his draft year in the past
if ((p.tid !== g.PLAYER.UNDRAFTED && p.tid !== g.PLAYER.UNDRAFTED_2 && p.tid !== g.PLAYER.UNDRAFTED_3) && (vm.originalTid() === g.PLAYER.UNDRAFTED || vm.originalTid() === g.PLAYER.UNDRAFTED_2 || vm.originalTid() === g.PLAYER.UNDRAFTED_3) && g.phase < g.PHASE.FREE_AGENCY) {
p.draft.year = g.season - 1;
}
// Recalculate player values, since ratings may have changed
player.updateValues(null, p, []).then(function (p) {
var tx;
tx = dao.tx(["players", "playerStats"], "readwrite");
dao.players.put({ot: tx, value: p}).then(function (pidLocal) {
// Get pid (primary key) after add, but can't redirect to player page until transaction completes or else it's a race condition
// When adding a player, this is the only way to know the pid
pid = pidLocal;
// Add regular season or playoffs stat row, if necessary
if (p.tid >= 0 && p.tid !== vm.originalTid() && g.phase <= g.PHASE.PLAYOFFS) {
p.pid = pid;
// If it is the playoffs, this is only necessary if p.tid actually made the playoffs, but causes only cosmetic harm otherwise.
p = player.addStatsRow(tx, p, g.phase === g.PHASE.PLAYOFFS);
// Add back to database
dao.players.put({ot: tx, value: p});
}
});
tx.complete().then(function () {
return league.setGameAttributes({lastDbChange: Date.now()});
}).then(function () {
ui.realtimeUpdate([], helpers.leagueUrl(["player", pid]));
});
});
});
}
return bbgmView.init({
id: "customizePlayer",
get: get,
InitViewModel: InitViewModel,
mapping: mapping,
runBefore: [updateCustomizePlayer],
uiFirst: uiFirst
});
});
|