code
stringlengths
2
1.05M
'use strict'; require('../common/service.js'); require('../prize_types/prize_types.service.js'); require('./roulette_game.service.js'); let angular = require('angular'); module.exports = angular.module('sanya.roulette_game', [ 'ui.router', 'sanya.common.services', 'sanya.prize_types.service', 'sanya.roulette_game.service' ]).config(moduleConfig) .controller('RouletteGameController', RouletteGameController); /* @ngInject */ function moduleConfig($stateProvider) { $stateProvider .state('roulette_game', { url: '/roulette-game', templateUrl: '/roulette_game/roulette_game.html', controller: 'RouletteGameController as scope' }); } /* @ngInject */ function RouletteGameController($stateParams, PrizeTypesService, RouletteGameService, AlertService) { let vm = this; vm.setupGame = function setupGame(game) { RouletteGameService.save(game).$promise .then(function () { AlertService.success('设置成功'); }).catch(function (err) { AlertService.warning(err.data || err.statusText); }); }; (function init() { PrizeTypesService.query().$promise .then(function (prizeTypes) { vm.prizeTypes = prizeTypes; return RouletteGameService.query({ offswitch: true }).$promise; }).then(function (rouletteGames) { vm.game = rouletteGames[0]; }).catch(function (err) { AlertService.warning(err.data || err.statusText); }); }()); }
import NavItem from "./NavItem.js"; export { NavItem };
'use strict'; var angular = require('angular'); /* @ngInject */ function currentVersion($log, version, buildTimestamp) { function _link(scope, element, attrs) { $log.debug('directiveDefinition.name', directiveDefinition.name); $log.debug('attrs[directiveDefinition.name]', attrs[directiveDefinition.name]); element.text(attrs[directiveDefinition.name] === 'full' ? version + ' (' + buildTimestamp + ')' : version); } var directiveDefinition = { link: _link }; return directiveDefinition; } module.exports = angular.module('myApp.version.directive', []) .directive('currentVersion', currentVersion);
(function(){ if (navigator.userAgent.match(/IEMobile\/10\.0/)) { var msViewportStyle = document.createElement("style"); msViewportStyle.appendChild( document.createTextNode( "@-ms-viewport{width:auto!important}" ) ); document.getElementsByTagName("head")[0].appendChild(msViewportStyle); } }());
version https://git-lfs.github.com/spec/v1 oid sha256:191d21e01913c665717e5da5dea69284231fe0773357a37eaefc80b871f1c85e size 1170
/* * CanvasJS v1.0.0 Beta 3- canvasjs.com * Copyright 2013 fenopix */ (function(){function K(a,d){var b;b=function(){};b.prototype=d.prototype;b=new b;a.prototype=b;a.prototype.constructor=a;a.parent=d.prototype}function Y(a,d,b){"millisecond"===b?a.setMilliseconds(a.getMilliseconds()+1*d):"second"===b?a.setSeconds(a.getSeconds()+1*d):"minute"===b?a.setMinutes(a.getMinutes()+1*d):"hour"===b?a.setHours(a.getHours()+1*d):"day"===b?a.setDate(a.getDate()+1*d):"week"===b?a.setDate(a.getDate()+7*d):"month"===b?a.setMonth(a.getMonth()+1*d):"year"===b&&a.setFullYear(a.getFullYear()+ 1*d);return a}function M(a,d){return y[d+"Duration"]*a}function B(a,d){var b=!1;0>a&&(b=!0,a*=-1);a=""+a;for(d=!d?1:d;a.length<d;)a="0"+a;return b?"-"+a:a}function N(a){a=a.replace(/^\s\s*/,"");for(var d=/\s/,b=a.length;d.test(a.charAt(--b)););return a.slice(0,b+1)}function Z(a,d){return a-d}function ea(a,d){return a.x-d.x}function A(a){var d=((a&16711680)>>16).toString(16),b=((a&65280)>>8).toString(16);a=((a&255)>>0).toString(16);d=2>d.length?"0"+d:d;b=2>b.length?"0"+b:b;a=2>a.length?"0"+a:a;return"#"+ d+b+a}function T(a){var d=[];d[0]=(a&16711680)>>16;d[1]=(a&65280)>>8;d[2]=(a&255)>>0;return d}function G(a,d,b){this._defaultsKey=a;currentTheme={};b&&(U[b]&&U[b][a])&&(currentTheme=U[b][a]);this._options=d?d:{};this.setOptions(this._options,currentTheme)}function t(a,d,b){t.parent.constructor.call(this,"Chart",d,d.theme?d.theme:"theme1");t.externalReference=b;var c=this;this._containerId=a;this._objectsInitialized=!1;this.overlaidCanvasCtx=this.ctx=null;this._indexLabels=[];this._panTimerId=0;this._lastTouchEventType= "";this.panEnabled=!1;if(this._container=document.getElementById(this._containerId))d=a=0,a=this._options.width?this.width:0<this._container.clientWidth?this._container.clientWidth:this.width,d=this._options.height?this.height:0<this._container.clientHeight?this._container.clientHeight:this.height,this.width=a,this.height=d,this._canvasJSContainer=document.createElement("div"),this._canvasJSContainer.style.position="relative",this._container.appendChild(this._canvasJSContainer),this.canvas=document.createElement("canvas"), this.canvas.width=a,this.canvas.height=d,this.canvas.style.background=this.backgroundColor,this.canvas.style.position="absolute",this._canvasJSContainer.appendChild(this.canvas),this.overlaidCanvas=document.createElement("canvas"),this.overlaidCanvas.width=a,this.overlaidCanvas.height=d,this.overlaidCanvas.style.position="absolute",this._canvasJSContainer.appendChild(this.overlaidCanvas),this._eventManager=new P(this),this._toolBar=document.createElement("div"),this._toolBar.style.position="absolute", this._toolBar.style.top="0px",this._toolBar.style.right="0px",this._canvasJSContainer.appendChild(this._toolBar),this.zoomEnabled&&(this._zoomButton=document.createElement("button"),this._zoomButton.appendChild(document.createTextNode("Pan")),this._toolBar.appendChild(this._zoomButton),this._zoomButton.addEventListener("click",function(){c.zoomEnabled?(c.zoomEnabled=!1,c.panEnabled=!0,c._zoomButton.innerText="Zoom"):(c.zoomEnabled=!0,c.panEnabled=!1,c._zoomButton.innerText="Pan ");c.render()},!1)), this.zoomEnabled&&(this._resetButton=document.createElement("button"),this._resetButton.appendChild(document.createTextNode("Reset")),this._toolBar.appendChild(this._resetButton),c.zoomEnabled=c._options.zoomEnabled?!0:!1,c.panEnabled=!1,this._resetButton.addEventListener("click",function(){c._toolTip.hide();c.zoomEnabled||c.panEnabled?(c.zoomEnabled=!0,c.panEnabled=!1,c._zoomButton.innerText="Pan"):(c.zoomEnabled=!1,c.panEnabled=!1);c.sessionVariables.axisX.internalMinimum=c._options.axisX&&c._options.axisX.minimum? c._options.axisX.minimum:null;c.sessionVariables.axisX.internalMaximum=c._options.axisX&&c._options.axisX.maximum?c._options.axisX.maximum:null;c.resetOverlayedCanvas();c.render()},!1)),window.addEventListener("resize",function(){var a=0,b=0,a=c._options.width?c.width:0<c._container.clientWidth?c._container.clientWidth:c.width,b=c._options.height?c.height:0<c._container.clientHeight?c._container.clientHeight:c.height;if(c.canvas.width!==a||c.canvas.height!==b)c.renderCount--,c.canvas.width=a,c.canvas.height= b,c.overlaidCanvas.width=a,c.overlaidCanvas.height=b,c.render()}),this._toolBar.style.display="none",this.bounds={x1:0,y1:0,x2:this.canvas.width,y2:this.canvas.height},c=this,this.canvas.getContext&&(this.ctx=this.canvas.getContext("2d"),this.ctx.textBaseline="top",this.overlaidCanvasCtx=this.overlaidCanvas.getContext("2d"),this.overlaidCanvasCtx.textBaseline="top",this.ctx.roundRect=function(a,b,c,d,h,j,m,n){m&&(this.fillStyle=m);n&&(this.strokeStyle=n);"undefined"==typeof stroke&&(stroke=!0);"undefined"=== typeof h&&(h=5);this.lineWidth=j;this.beginPath();this.moveTo(a+h,b);this.lineTo(a+c-h,b);this.quadraticCurveTo(a+c,b,a+c,b+h);this.lineTo(a+c,b+d-h);this.quadraticCurveTo(a+c,b+d,a+c-h,b+d);this.lineTo(a+h,b+d);this.quadraticCurveTo(a,b+d,a,b+d-h);this.lineTo(a,b+h);this.quadraticCurveTo(a,b,a+h,b);this.closePath();m&&this.fill();n&&0<j&&this.stroke()},this.overlaidCanvas.addEventListener("click",function(a){c._mouseEventHandler(a)},!1),this.overlaidCanvas.addEventListener("mousemove",function(a){c._mouseEventHandler(a)}, !1),this.overlaidCanvas.addEventListener("mouseup",function(a){c._mouseEventHandler(a)},!1),this.overlaidCanvas.addEventListener("mousedown",function(a){c._mouseEventHandler(a)},!1),this.overlaidCanvas.addEventListener("mouseout",function(a){c._mouseEventHandler(a)},!1),this.overlaidCanvas.addEventListener(window.navigator.msPointerEnabled?"MSPointerDown":"touchstart",function(a){c._touchEventHandler(a)},!1),this.overlaidCanvas.addEventListener(window.navigator.msPointerEnabled?"MSPointerMove":"touchmove", function(a){c._touchEventHandler(a)},!1),this.overlaidCanvas.addEventListener(window.navigator.msPointerEnabled?"MSPointerUp":"touchend",function(a){c._touchEventHandler(a)},!1),this.overlaidCanvas.addEventListener(window.navigator.msPointerEnabled?"MSPointerCancel":"touchcancel",function(a){c._touchEventHandler(a)},!1)),this._toolTip=new I(this,this._options.toolTip,this.theme),this.layoutManager=new O(this.canvas),this.axisY2=this.axisY=this.axisX=this.data=null,this.renderCount=0,this.sessionVariables= {axisX:{internalMinimum:null,internalMaximum:null},axisY:{internalMinimum:null,internalMaximum:null},axisY2:{internalMinimum:null,internalMaximum:null}}}function O(a){this._rightOccupied=this._leftOccupied=this._bottomOccupied=this._topOccupied=0;this.canvas=a}function D(a,d){D.parent.constructor.call(this,"TextBlock",d);this.ctx=a;this._isDirty=!0;this._wrappedText=null}function Q(a,d){Q.parent.constructor.call(this,"Title",d,a.theme);this.chart=a;this.canvas=a.canvas;this.ctx=this.chart.ctx;"undefined"=== typeof this._options.fontSize&&(this.fontSize=this.chart.getAutoFontSize(this.fontSize));this.height=this.width=null;this.bounds={x1:null,y1:null,x2:null,y2:null}}function R(a,d,b){R.parent.constructor.call(this,"Legend",d,b);this.chart=a;this.canvas=a.canvas;this.ctx=this.chart.ctx;this.height=this.width=0;this.orientation=null;this.horizontalSpacing=10;this.dataSeries=[];this.bounds={x1:null,y1:null,x2:null,y2:null}}function V(a,d){V.parent.constructor.call(this,d);this.chart=a;this.canvas=a.canvas; this.ctx=this.chart.ctx}function J(a,d,b,c,e){J.parent.constructor.call(this,"DataSeries",d,b);this.chart=a;this.canvas=a.canvas;this._ctx=a.canvas.ctx;this.index=c;this.noDataPointsInPlotArea=0;this.id=e;this.dataPointIds=[];this.axisY=this.axisX=null;this.axisPlacement=this.getDefaultAxisPlacement()}function x(a,d,b,c){x.parent.constructor.call(this,"Axis",d,a.theme);this.chart=a;this.canvas=a.canvas;this.ctx=a.ctx;this.intervalStartPosition=this.maxHeight=this.maxWidth=0;this.labels=[];this.dataInfo= {min:Infinity,max:-Infinity,viewPortMin:Infinity,viewPortMax:-Infinity,minDiff:Infinity};"axisX"===b?(this.sessionVariables=this.chart.sessionVariables[b],this._options.interval||(this.intervalType=null)):this.sessionVariables="left"===c||"top"===c?this.chart.sessionVariables.axisY:this.chart.sessionVariables.axisY2;"undefined"===typeof this._options.titleFontSize&&(this.titleFontSize=fontSize=this.chart.getAutoFontSize(this.titleFontSize));"undefined"===typeof this._options.labelFontSize&&(this.labelFontSize= this.chart.getAutoFontSize(this.labelFontSize));this.type=b;if(!d||"undefined"===typeof d.gridThickness)this.gridThickness="axisX"===b?0:1;this._labels=null;this._position=c;this.lineCoordinates={x1:null,y1:null,x2:null,y2:null,width:null};this.labelAngle=(this.labelAngle%360+360)%360;90<this.labelAngle&&270>=this.labelAngle?this.labelAngle-=180:180<this.labelAngle&&270>=this.labelAngle?this.labelAngle-=180:270<this.labelAngle&&360>=this.labelAngle&&(this.labelAngle-=360);this._absoluteMaximum=this._absoluteMinimum= this._titleTextBlock=null;this.hasOptionChanged("minimum")&&(this.sessionVariables.internalMinimum=this.minimum);this.hasOptionChanged("maximum")&&(this.sessionVariables.internalMaximum=this.maximum);this.trackChanges("minimum");this.trackChanges("maximum")}function I(a,d,b){I.parent.constructor.call(this,"ToolTip",d,b);this.chart=a;this.canvas=a.canvas;this.ctx=this.chart.ctx;this.currentDataPointIndex=this.currentSeriesIndex=-1;this._timerId=0;this._initialize()}function P(a){this.chart=a;this.lastObjectId= 0;this.objectMap=[];this.rectangularRegionEventSubscriptions=[];this.previousDataPointEventObject=null;this.ghostCanvas=document.createElement("canvas");this.ghostCanvas.width=this.chart.canvas.width;this.ghostCanvas.height=this.chart.canvas.height;this.ghostCtx=this.ghostCanvas.getContext("2d")}var $={Chart:{width:500,height:400,zoomEnabled:!1,backgroundColor:"white",backgroundColor:"white",theme:"theme1",animationEnabled:!0,colorSet:"colorSet1"},Title:{padding:0,text:null,verticalAlign:"top",horizontalAlign:"center", fontSize:20,fontFamily:"Calibri",fontWeight:"normal",fontColor:"black",fontStyle:"normal",borderThickness:0,borderColor:"black",cornerRadius:0,backgroundColor:null,margin:5},DataSeries:{name:null,dataPoints:null,label:"",bevelEnabled:!1,indexLabel:"",indexLabelPlacement:"outside",indexLabelOrientation:"horizontal",indexLabelFontColor:"black",indexLabelFontSize:12,indexLabelFontStyle:"normal",indexLabelFontFamily:"Arial",indexLabelFontWeight:"normal",indexLabelBackgroundColor:null,indexLabelLineColor:"#808080", indexLabelLineThickness:1,lineThickness:2,color:null,startAngle:0,type:"column",xValueType:"number",axisYType:"primary",showInLegend:null,legendMarkerType:null,legendMarkerColor:null,legendText:null,markerType:"circle",markerColor:null,markerSize:null,markerBorderColor:null,markerBorderThickness:null,mouseover:null,mouseout:null,mousemove:null,click:null,toolTipContent:null},Axis:{minimum:null,maximum:null,interval:null,intervalType:null,title:null,titleFontColor:"black",titleFontSize:20,titleFontFamily:"arial", titleFontWeight:"normal",titleFontStyle:"normal",labelAngle:0,labelFontFamily:"arial",labelFontColor:"black",labelFontSize:12,labelFontWeight:"normal",labelFontStyle:"normal",prefix:"",suffix:"",includeZero:!0,tickLength:5,tickColor:"black",tickThickness:1,lineColor:"black",lineThickness:1,gridColor:"A0A0A0",gridThickness:0,interlacedColor:null,valueFormatString:null,margin:2},Legend:{name:null,borderThickness:0,borderColor:"black",cornerRadius:0,verticalAlign:"center",horizontalAlign:"right",fontSize:12, fontFamily:"Calibri",fontWeight:"normal",fontColor:"black",fontStyle:"normal"},ToolTip:{enabled:!0,borderColor:null,shared:!1,animationEnabled:!0,content:null},TextBlock:{x:0,y:0,width:null,height:null,maxWidth:null,maxHeight:null,padding:0,angle:0,text:"",horizontalAlign:"center",fontSize:12,fontFamily:"Calibri",fontWeight:"normal",fontColor:"black",fontStyle:"normal",borderThickness:0,borderColor:"black",cornerRadius:0,backgroundColor:null,textBaseline:"top"}},S={colorSet1:"#369EAD #C24642 #7F6084 #86B402 #A2D1CF #C8B631 #6DBCEB #52514E #4F81BC #A064A1 #F79647".split(" "), colorSet2:"#4F81BC #C0504E #9BBB58 #23BFAA #8064A1 #4AACC5 #F79647".split(" "),colorSet3:"#8CA1BC #36845C #017E82 #8CB9D0 #708C98 #94838D #F08891 #0366A7 #008276 #EE7757 #E5BA3A #F2990B #03557B #782970".split(" ")},U={theme1:{Chart:{colorSet:"colorSet1"},Title:{fontFamily:"Candara, Optima, Trebuchet MS, Helvetica Neue, Helvetica, Trebuchet MS, serif",fontSize:32,fontColor:"rgb(68,78,58)",fontColor:"#3A3A3A",fontWeight:"bold",verticalAlign:"top",margin:10},Axis:{titleFontSize:22,titleFontColor:"rgb(98,98,98)", titleFontFamily:"Verdana, Geneva, Calibri, sans-serif",labelFontFamily:"Calibri, Optima, Candara, Verdana, Geneva, sans-serif",labelFontSize:18,labelFontColor:"grey",tickColor:"grey",tickThickness:2,gridThickness:2,gridColor:"grey",lineThickness:2,lineColor:"grey"},Legend:{verticalAlign:"bottom",horizontalAlign:"right",fontFamily:"monospace, sans-serif,arial black"},DataSeries:{bevelEnabled:!0,indexLabelFontColor:"grey",indexLabelFontFamily:"Candara, Optima, Calibri, Verdana, Geneva, sans-serif", indexLabelFontSize:18,indexLabelLineColor:"lightgrey",indexLabelLineThickness:2}},theme2:{Chart:{colorSet:"colorSet2"},Title:{fontFamily:"impact, charcoal, arial black, sans-serif",fontSize:32,fontColor:"#333333",verticalAlign:"top",margin:10},Axis:{titleFontSize:22,titleFontColor:"rgb(98,98,98)",titleFontFamily:"monospace, sans-serif,arial black",titleFontWeight:"bold",labelFontFamily:"monospace, Courier New, Courier",labelFontSize:16,labelFontColor:"grey",labelFontWeight:"bold",tickColor:"grey", tickThickness:2,gridThickness:2,gridColor:"grey",lineThickness:0},Legend:{verticalAlign:"bottom",horizontalAlign:"right",fontFamily:"monospace, sans-serif,arial black"},DataSeries:{indexLabelFontColor:"grey",indexLabelFontFamily:"Courier New, Courier, monospace",indexLabelFontWeight:"bold",indexLabelFontSize:18,indexLabelLineColor:"lightgrey",indexLabelLineThickness:2}}},y={numberDuration:1,yearDuration:314496E5,monthDuration:2592E6,weekDuration:6048E5,dayDuration:864E5,hourDuration:36E5,minuteDuration:6E4, secondDuration:1E3,millisecondDuration:1,dayOfWeekFromInt:"Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ")},W,fa=/D{1,4}|M{1,4}|Y{1,4}|h{1,2}|H{1,2}|m{1,2}|s{1,2}|f{1,3}|t{1,2}|T{1,2}|K|z{1,3}|"[^"]*"|'[^']*'/g,aa="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),ba="January February March April May June July August September October November December".split(" "),ga=/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g, ha=/[^-+\dA-Z]/g;W=function(a,d){var b="",c=!1;a=a&&a.getTime?a:a?new Date(a):new Date;if(isNaN(a))throw SyntaxError("invalid date");"UTC:"==d.slice(0,4)&&(d=d.slice(4),c=!0);var b=c?"getUTC":"get",e=a[b+"Date"](),f=a[b+"Day"](),g=a[b+"Month"](),k=a[b+"FullYear"](),h=a[b+"Hours"](),j=a[b+"Minutes"](),m=a[b+"Seconds"](),n=a[b+"Milliseconds"](),p=c?0:a.getTimezoneOffset();return b=d.replace(fa,function(b){switch(b){case "D":return e;case "DD":return B(e,2);case "DDD":return aa[f].slice(0,3);case "DDDD":return aa[f]; case "M":return g+1;case "MM":return B(g+1,2);case "MMM":return ba[g].slice(0,3);case "MMMM":return ba[g];case "Y":return parseInt(String(k).slice(-2));case "YY":return B(String(k).slice(-2),2);case "YYY":return B(String(k).slice(-3),3);case "YYYY":return B(k,4);case "h":return h%12||12;case "hh":return B(h%12||12,2);case "H":return h;case "HH":return B(h,2);case "m":return j;case "mm":return B(j,2);case "s":return m;case "ss":return B(m,2);case "f":return String(n).slice(0,1);case "ff":return B(String(n).slice(0, 2),2);case "fff":return B(String(n).slice(0,3),3);case "t":return 12>h?"a":"p";case "tt":return 12>h?"am":"pm";case "T":return 12>h?"A":"P";case "TT":return 12>h?"AM":"PM";case "K":return c?"UTC":(String(a).match(ga)||[""]).pop().replace(ha,"");case "z":return(0<p?"-":"+")+Math.floor(Math.abs(p)/60);case "zz":return(0<p?"-":"+")+B(Math.floor(Math.abs(p)/60),2);case "zzz":return(0<p?"-":"+")+B(Math.floor(Math.abs(p)/60),2)+B(Math.abs(p)%60,2);default:return b.slice(1,b.length-1)}})};var X=function(a, d){a=Number(a);var b=0>a?!0:!1;b&&(a*=-1);var c="";d=String(d);for(var e=1,f="",g="",k=-1,h=[],j=[],m=0,n=0,p=0,e=1,l=!1,s=0,g=d.match(/"[^"]*"|'[^']*'|[eE][+-]*[0]+|[,]+[.]|\u2030|./g),q=0;g&&q<g.length;q++)if(c=g[q],"."===c&&0>k)k=q;else{if("%"===c)e*=100;else if("\u2030"===c){e*=1E3;continue}else if(","===c[0]&&"."===c[c.length-1]){e/=Math.pow(1E3,c.length-1);k=q+c.length-1;continue}else if(("E"===c[0]||"e"===c[0])&&"0"===c[c.length-1])l=!0;0>k?(h.push(c),"#"===c||"0"===c?m++:","===c&&p++):(j.push(c), ("#"===c||"0"===c)&&n++)}l&&(c=Math.floor(a),s=(0===c?"":String(c)).length-m,e/=Math.pow(10,s));0>k&&(k=q);c=(a*e).toFixed(n);c=c.split(".");e=(c[0]+"").split("");k=(c[1]+"").split("");e&&"0"===e[0]&&e.shift();for(var r=l=g=q=n=0;0<h.length;)if(c=h.pop(),"#"===c||"0"===c)if(n++,n===m){var u=e,e=[];if("0"===c)for(c=m-q-(u?u.length:0);0<c;)u.unshift("0"),c--;for(;0<u.length;)f=u.pop()+f,r++,0===r%l&&(g===p&&0<u.length)&&(f=","+f);b&&(f="-"+f)}else 0<e.length?(f=e.pop()+f,q++,r++):"0"===c&&(f="0"+f, q++,r++),0===r%l&&(g===p&&0<e.length)&&(f=","+f);else("E"===c[0]||"e"===c[0])&&"0"===c[c.length-1]&&/[eE][+-]*[0]+/.test(c)?(c=0>s?c.replace("+","").replace("-",""):c.replace("-",""),f+=c.replace(/[0]+/,function(a){return B(s,a.length)})):","===c?(g++,l=r,r=0,0<e.length&&(f=c+f)):f=1<c.length&&('"'===c[0]&&'"'===c[c.length-1]||"'"===c[0]&&"'"===c[c.length-1])?c.slice(1,c.length-1)+f:c+f;for(b=0;0<j.length;)c=j.shift(),"#"===c||"0"===c?0<k.length&&0!==Number(k.join(""))?f+=(0===b++?".":"")+k.shift(): "0"===c&&(f+=(0===b++?".":"")+"0"):1<c.length&&('"'===c[0]&&'"'===c[c.length-1]||"'"===c[0]&&"'"===c[c.length-1])?f+=(0===b++?".":"")+c.slice(1,c.length-1):("E"===c[0]||"e"===c[0])&&"0"===c[c.length-1]&&/[eE][+-]*[0]+/.test(c)?(c=0>s?c.replace("+","").replace("-",""):c.replace("-",""),f+=c.replace(/[0]+/,function(a){return B(s,a.length)})):f+=(0===b++?".":"")+c;return f},ca=function(a){var d=0,b=0;a||(a=window.event);a.offsetX||0===a.offsetX?(d=a.offsetX,b=a.offsetY):a.layerX||0==a.layerX?(d=a.layerX, b=a.layerY):(d=a.pageX-a.target.offsetLeft,b=a.pageY-a.target.offsetTop);return{x:d,y:b}};G.prototype.setOptions=function(a,d){if($[this._defaultsKey]){var b=$[this._defaultsKey];for(prop in b)this[prop]=a&&prop in a?a[prop]:d&&prop in d?d[prop]:b[prop]}};G.prototype.trackChanges=function(a){this._options._oldOptions||(this._options._oldOptions={});this._options._oldOptions[a]=this._options[a]};G.prototype.isBeingTracked=function(a){this._options._oldOptions||(this._options._oldOptions={});return this._options._oldOptions[a]? !0:!1};G.prototype.hasOptionChanged=function(a){this._options._oldOptions||(this._options._oldOptions={});return this._options._oldOptions[a]!==this._options[a]};K(t,G);t.prototype._initialize=function(){this._selectedColorSet="undefined"!==typeof S[this.colorSet]?S[this.colorSet]:S.colorSet1;this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);this.ctx.beginPath();this.axisY2=this.axisY=this.axisX=null;this._indexLabels=[];this._events=[];this._eventManager&&this._eventManager.reset();this.plotInfo= {axisPlacement:null,axisXValueType:null,plotTypes:[]};this.layoutManager.reset();this.data=[];var a=0;for(series in this._options.data)if(a++,!this._options.data[series].type||0<=t._supportedChartTypes.indexOf(this._options.data[series].type)){var d=new J(this,this._options.data[series],this.theme,a-1,++this._eventManager.lastObjectId);null===d.name&&(d.name="DataSeries "+a);null===d.color?1<this._options.data.length?(d._colorSet=[this._selectedColorSet[d.index%this._selectedColorSet.length]],d.color= this._selectedColorSet[d.index%this._selectedColorSet.length]):d._colorSet="line"===d.type||"area"===d.type||"stackedArea"===d.type||"stackedArea100"===d.type?[this._selectedColorSet[0]]:this._selectedColorSet:d._colorSet=[d.color];if(null===d.markerSize&&("line"===d.type&&d.dataPoints.length<this.canvas.width/16||"scatter"===d.type))d.markerSize=8;("bubble"===d.type||"scatter"===d.type)&&d.dataPoints.sort(ea);this.data.push(d);var b=d.axisPlacement,c;"normal"===b?"xySwapped"===this.plotInfo.axisPlacement? c='You cannot combine "'+d.type+'" with bar chart':"none"===this.plotInfo.axisPlacement?c='You cannot combine "'+d.type+'" with pie chart':null===this.plotInfo.axisPlacement&&(this.plotInfo.axisPlacement="normal"):"xySwapped"===b?"normal"===this.plotInfo.axisPlacement?c='You cannot combine "'+d.type+'" with line, area, column or pie chart':"none"===this.plotInfo.axisPlacement?c='You cannot combine "'+d.type+'" with pie chart':null===this.plotInfo.axisPlacement&&(this.plotInfo.axisPlacement="xySwapped"): "none"==b&&("normal"===this.plotInfo.axisPlacement?c='You cannot combine "'+d.type+'" with line, area, column or bar chart':"xySwapped"===this.plotInfo.axisPlacement?c='You cannot combine "'+d.type+'" with bar chart':null===this.plotInfo.axisPlacement&&(this.plotInfo.axisPlacement="none"));if(c&&window.console){window.console.log(c);return}}this._objectsInitialized=!0};t._supportedChartTypes="line column area bar bubble scatter stackedColumn stackedColumn100 stackedBar stackedBar100 stackedArea stackedArea100 pie doughnut".split(" "); t.prototype.render=function(){this._initialize();for(var a=0;a<this.data.length;a++)if("normal"===this.plotInfo.axisPlacement||"xySwapped"===this.plotInfo.axisPlacement)!this.data[a].axisYType||"primary"===this.data[a].axisYType?(this.axisY||("normal"===this.plotInfo.axisPlacement?this.axisY=new x(this,this._options.axisY,"axisY","left"):"xySwapped"===this.plotInfo.axisPlacement&&(this.axisY=new x(this,this._options.axisY,"axisY","bottom"))),this.data[a].axisY=this.axisY):"secondary"===this.data[a].axisYType&& (this.axisY2||("normal"===this.plotInfo.axisPlacement?this.axisY2=new x(this,this._options.axisY2,"axisY","right"):"xySwapped"===this.plotInfo.axisPlacement&&(this.axisY2=new x(this,this._options.axisY2,"axisY","top"))),this.data[a].axisY=this.axisY2),this.axisX||("normal"===this.plotInfo.axisPlacement?this.axisX=new x(this,this._options.axisX,"axisX","bottom"):"xySwapped"===this.plotInfo.axisPlacement&&(this.axisX=new x(this,this._options.axisX,"axisX","left"))),this.data[a].axisX=this.axisX;this._processData(); this._options.title&&(this._title=new Q(this,this._options.title),this._title.render());this.legend=new R(this,this._options.legend,this.theme);for(a=0;a<this.data.length;a++)this.data[a].showInLegend&&this.legend.dataSeries.push(this.data[a]);this.legend.render();if("normal"===this.plotInfo.axisPlacement||"xySwapped"===this.plotInfo.axisPlacement)x.setLayoutAndRender(this.axisX,this.axisY,this.axisY2,this.plotInfo.axisPlacement,this.layoutManager.getFreeSpace());else if("none"!==this.plotInfo.axisPlacement)return; for(a=0;a<this.plotInfo.plotTypes.length;a++)for(var d=this.plotInfo.plotTypes[a],b=0;b<d.plotUnits.length;b++){var c=d.plotUnits[b];"line"===c.type?this.renderLine(c):"column"===c.type?this.renderColumn(c):"bar"===c.type?this.renderBar(c):"area"===c.type?this.renderArea(c):"stackedColumn"===c.type?this.renderStackedColumn(c):"stackedColumn100"===c.type?this.renderStackedColumn100(c):"stackedBar"===c.type?this.renderStackedBar(c):"stackedBar100"===c.type?this.renderStackedBar100(c):"stackedArea"=== c.type?this.renderStackedArea(c):"stackedArea100"===c.type?this.renderStackedArea100(c):"bubble"===c.type?this.renderBubble(c):"scatter"===c.type?this.renderScatter(c):"pie"===c.type?this.renderPie(c):"doughnut"===c.type&&this.renderPie(c)}0<this._indexLabels.length&&this.renderIndexLabels();this.setToolbarButtonStates();this.renderCount++};t.prototype.setToolbarButtonStates=function(){this.zoomEnabled||this.panEnabled||this._toolTip.enabled?this.attachEvent({context:this,chart:this,mousedown:this._plotAreaMouseDown, mouseup:this._plotAreaMouseUp,mousemove:this._plotAreaMouseMove,cursor:this.panEnabled?"move":"default",capture:!0,bounds:this.getPlotArea()}):this._toolBar.style.display="none"};t.prototype.categoriseDataSeries=function(){for(var a="",d=0;d<this.data.length;d++)if(a=this.data[d],a.dataPoints&&0!==a.dataPoints.length&&0<=t._supportedChartTypes.indexOf(a.type)){for(var b=null,c=!1,e=null,f=!1,g=0;g<this.plotInfo.plotTypes.length;g++)if(this.plotInfo.plotTypes[g].type===a.type){c=!0;b=this.plotInfo.plotTypes[g]; break}c||(b={type:a.type,totalDataSeries:0,plotUnits:[]},this.plotInfo.plotTypes.push(b));for(g=0;g<b.plotUnits.length;g++)if(b.plotUnits[g].axisYType===a.axisYType){f=!0;e=b.plotUnits[g];break}f||(e={type:a.type,previousDataSeriesCount:0,index:b.plotUnits.length,plotType:b,axisYType:a.axisYType,axisY:"primary"===a.axisYType?this.axisY:this.axisY2,axisX:this.axisX,dataSeriesIndexes:[]},b.plotUnits.push(e));b.totalDataSeries++;e.dataSeriesIndexes.push(d)}for(d=0;d<this.plotInfo.plotTypes.length;d++){b= this.plotInfo.plotTypes[d];for(g=a=0;g<b.plotUnits.length;g++)b.plotUnits[g].previousDataSeriesCount=a,a+=b.plotUnits[g].dataSeriesIndexes.length}};t.prototype.assignIdToDataPoints=function(){for(var a=0;a<this.data.length;a++){dataSeries=this.data[a];for(var d=dataSeries.dataPoints.length,b=0;b<d;b++)dataSeries.dataPointIds[b]=++this._eventManager.lastObjectId}};t.prototype._processData=function(){this.assignIdToDataPoints();this.categoriseDataSeries();for(var a=0;a<this.plotInfo.plotTypes.length;a++)for(var d= this.plotInfo.plotTypes[a],b=0;b<d.plotUnits.length;b++){var c=d.plotUnits[b];"line"===c.type||"column"===c.type||"area"===c.type||"bar"===c.type||"bubble"===c.type||"scatter"===c.type?this._processMultiseriesPlotUnit(c):"stackedColumn"===c.type||"stackedBar"===c.type||"stackedArea"===c.type?this._processStackedPlotUnit(c):("stackedColumn100"===c.type||"stackedBar100"===c.type||"stackedArea100"===c.type)&&this._processStacked100PlotUnit(c)}};t.prototype._processMultiseriesPlotUnit=function(a){if(a.dataSeriesIndexes&& !(1>a.dataSeriesIndexes.length))for(var d=a.axisY.dataInfo,b=a.axisX.dataInfo,c,e,f=!1,g=0;g<a.dataSeriesIndexes.length;g++){var k=this.data[a.dataSeriesIndexes[g]],h=0,j=!1,m=!1;if("normal"===k.axisPlacement||"xySwapped"===k.axisPlacement)var n=this.sessionVariables.axisX.internalMinimum?this.sessionVariables.axisX.internalMinimum:this._options.axisX&&this._options.axisX.minimum?this._options.axisX.minimum:-Infinity,p=this.sessionVariables.axisX.internalMaximum?this.sessionVariables.axisX.internalMaximum: this._options.axisX&&this._options.axisX.maximum?this._options.axisX.maximum:Infinity;if(k.dataPoints[h].x&&k.dataPoints[h].x.getTime||"dateTime"===k.xValueType)f=!0;for(h=0;h<k.dataPoints.length;h++){"undefined"===typeof k.dataPoints[h].x&&(k.dataPoints[h].x=h);k.dataPoints[h].x.getTime?(f=!0,c=k.dataPoints[h].x.getTime()):c=k.dataPoints[h].x;e=k.dataPoints[h].y;c<b.min&&(b.min=c);c>b.max&&(b.max=c);e<d.min&&(d.min=e);e>d.max&&(d.max=e);if(0<h){var l=c-k.dataPoints[h-1].x;0>l&&(l*=-1);b.minDiff> l&&0!==l&&(b.minDiff=l)}if(!(c<n)||j){if(!j&&(j=!0,0<h)){h-=2;continue}if(c>p&&!m)m=!0;else if(c>p&&m)continue;k.dataPoints[h].label&&(a.axisX.labels[c]=k.dataPoints[h].label);c<b.viewPortMin&&(b.viewPortMin=c);c>b.viewPortMax&&(b.viewPortMax=c);e<d.viewPortMin&&(d.viewPortMin=e);e>d.viewPortMax&&(d.viewPortMax=e)}}this.plotInfo.axisXValueType=k.xValueType=f?"dateTime":"number"}};t.prototype._processStackedPlotUnit=function(a){if(a.dataSeriesIndexes&&!(1>a.dataSeriesIndexes.length)){for(var d=a.axisY.dataInfo, b=a.axisX.dataInfo,c,e,f=!1,g=[],k=[],h=0;h<a.dataSeriesIndexes.length;h++){var j=this.data[a.dataSeriesIndexes[h]],m=0,n=!1,p=!1;if("normal"===j.axisPlacement||"xySwapped"===j.axisPlacement)var l=this.sessionVariables.axisX.internalMinimum?this.sessionVariables.axisX.internalMinimum:this._options.axisX&&this._options.axisX.minimum?this._options.axisX.minimum:-Infinity,s=this.sessionVariables.axisX.internalMaximum?this.sessionVariables.axisX.internalMaximum:this._options.axisX&&this._options.axisX.maximum? this._options.axisX.maximum:Infinity;if(j.dataPoints[m].x&&j.dataPoints[m].x.getTime||"dateTime"===j.xValueType)f=!0;for(m=0;m<j.dataPoints.length;m++){"undefined"===typeof j.dataPoints[m].x&&(j.dataPoints[m].x=m);j.dataPoints[m].x.getTime?(f=!0,c=j.dataPoints[m].x.getTime()):c=j.dataPoints[m].x;e=j.dataPoints[m].y;c<b.min&&(b.min=c);c>b.max&&(b.max=c);if(0<m){var q=c-j.dataPoints[m-1].x;0>q&&(q*=-1);b.minDiff>q&&0!==q&&(b.minDiff=q)}if(!(c<l)||n){if(!n&&(n=!0,0<m)){m-=2;continue}if(c>s&&!p)p=!0; else if(c>s&&p)continue;j.dataPoints[m].label&&(a.axisX.labels[c]=j.dataPoints[m].label);c<b.viewPortMin&&(b.viewPortMin=c);c>b.viewPortMax&&(b.viewPortMax=c);0<=e?g[c]=g[c]?g[c]+e:e:k[c]=k[c]?k[c]+e:e}}this.plotInfo.axisXValueType=j.xValueType=f?"dateTime":"number"}for(m in g)a=g[m],a<d.min&&(d.min=a),a>d.max&&(d.max=a),m<b.viewPortMin||m>b.viewPortMax||(a<d.viewPortMin&&(d.viewPortMin=a),a>d.viewPortMax&&(d.viewPortMax=a));for(m in k)a=k[m],a<d.min&&(d.min=a),a>d.max&&(d.max=a),m<b.viewPortMin|| m>b.viewPortMax||(a<d.viewPortMin&&(d.viewPortMin=a),a>d.viewPortMax&&(d.viewPortMax=a))}};t.prototype._processStacked100PlotUnit=function(a){if(a.dataSeriesIndexes&&!(1>a.dataSeriesIndexes.length)){for(var d=a.axisY.dataInfo,b=a.axisX.dataInfo,c,e,f=!1,g=!1,k=!1,h=[],j=0;j<a.dataSeriesIndexes.length;j++){var m=this.data[a.dataSeriesIndexes[j]],n=0,p=!1,l=!1;if("normal"===m.axisPlacement||"xySwapped"===m.axisPlacement)var s=this.sessionVariables.axisX.internalMinimum?this.sessionVariables.axisX.internalMinimum: this._options.axisX&&this._options.axisX.minimum?this._options.axisX.minimum:-Infinity,q=this.sessionVariables.axisX.internalMaximum?this.sessionVariables.axisX.internalMaximum:this._options.axisX&&this._options.axisX.maximum?this._options.axisX.maximum:Infinity;if(m.dataPoints[n].x&&m.dataPoints[n].x.getTime||"dateTime"===m.xValueType)f=!0;for(n=0;n<m.dataPoints.length;n++){"undefined"===typeof m.dataPoints[n].x&&(m.dataPoints[n].x=n);m.dataPoints[n].x.getTime?(f=!0,c=m.dataPoints[n].x.getTime()): c=m.dataPoints[n].x;e=m.dataPoints[n].y;c<b.min&&(b.min=c);c>b.max&&(b.max=c);if(0<n){var r=c-m.dataPoints[n-1].x;0>r&&(r*=-1);b.minDiff>r&&0!==r&&(b.minDiff=r)}if(!(c<s)||p){if(!p&&(p=!0,0<n)){n-=2;continue}if(c>q&&!l)l=!0;else if(c>q&&l)continue;m.dataPoints[n].label&&(a.axisX.labels[c]=m.dataPoints[n].label);c<b.viewPortMin&&(b.viewPortMin=c);c>b.viewPortMax&&(b.viewPortMax=c);0<=e?g=!0:k=!0;h[c]=h[c]?h[c]+Math.abs(e):Math.abs(e)}}this.plotInfo.axisXValueType=m.xValueType=f?"dateTime":"number"}g&& !k?(d.max=99,d.min=1):g&&k?(d.max=99,d.min=-99):!g&&k&&(d.max=-1,d.min=-99);d.viewPortMin=d.min;d.viewPortMax=d.max;a.dataPointYSums=h}};t.prototype.getAutoFontSize=function(a){return Math.min(this.canvas.width,this.canvas.height)*(a/400)};t.prototype.resetOverlayedCanvas=function(){var a=this.overlaidCanvas.width;this.overlaidCanvas.width=0;this.overlaidCanvas.width=a};t.prototype.attachEvent=function(a){this._events.push(a)};t.prototype._touchEventHandler=function(a){if(a.changedTouches){var d= [];first=(d=a.changedTouches)?d[0]:a;switch(a.type){case "touchstart":case "MSPointerDown":d=["mousemove","mousedown"];break;case "touchmove":case "MSPointerMove":d=["mousemove"];break;case "touchend":case "MSPointerUp":d="touchstart"===this._lastTouchEventType||"MSPointerDown"===this._lastTouchEventType?["mouseup","click"]:["mouseup"];break;default:return}this._lastTouchEventType=a.type;for(var b=0;b<d.length;b++){var c=d[b],e=document.createEvent("MouseEvent");e.initMouseEvent(c,!0,!0,window,1, first.screenX,first.screenY,first.clientX,first.clientY,!1,!1,!1,!1,0,null);first.target.dispatchEvent(e);a.preventManipulation&&a.preventManipulation();a.preventDefault&&a.preventDefault()}}};t.prototype._mouseEventHandler=function(a){a.preventManipulation&&a.preventManipulation();a.preventDefault&&a.preventDefault();var d=ca(a),b=a.type,c,e;a.which?e=3==a.which:a.button&&(e=2==a.button);if(!e){if(t.capturedEventParam)c=t.capturedEventParam,"mouseup"===b&&(t.capturedEventParam=null,c.chart.overlaidCanvas.releaseCapture? c.chart.overlaidCanvas.releaseCapture():document.body.removeEventListener("mouseup",c.chart._mouseEventHandler,!1)),c.hasOwnProperty(b)&&c[b].call(c.context,d.x,d.y);else if(this._events){for(e=0;e<this._events.length;e++)if(this._events[e].hasOwnProperty(b)){c=this._events[e];var f=c.bounds;if(d.x>=f.x1&&d.x<=f.x2&&d.y>=f.y1&&d.y<=f.y2){c[b].call(c.context,d.x,d.y);"mousedown"===b&&!0===c.capture?(t.capturedEventParam=c,this.overlaidCanvas.setCapture?this.overlaidCanvas.setCapture():document.body.addEventListener("mouseup", this._mouseEventHandler,!1)):"mouseup"===b&&(c.chart.overlaidCanvas.releaseCapture?c.chart.overlaidCanvas.releaseCapture():document.body.removeEventListener("mouseup",this._mouseEventHandler,!1));break}else c=null}a.target.style.cursor=c&&c.cursor?c.cursor:"default"}this._toolTip.enabled&&(b=this.getPlotArea(),(d.x<b.x1||d.x>b.x2||d.y<b.y1||d.y>b.y2)&&this._toolTip.hide());(!this.isDrag||!this.zoomEnabled)&&this._eventManager.mouseEventHandler(a)}};t.prototype._plotAreaMouseDown=function(a,d){if("normal"=== this.plotInfo.axisPlacement||"xySwapped"===this.plotInfo.axisPlacement)this.isDrag=!0,this.dragStartPoint={x:a,y:d,xMinimum:this.axisX.minimum,xMaximum:this.axisX.maximum}};t.prototype._plotAreaMouseUp=function(a,d){var b,c;if(("normal"===this.plotInfo.axisPlacement||"xySwapped"===this.plotInfo.axisPlacement)&&this.isDrag){this.isDrag=!1;var e=0,e=this.axisX.lineCoordinates,e="xySwapped"===this.plotInfo.axisPlacement?d-this.dragStartPoint.y:this.dragStartPoint.x-a;Math.abs(this.axisX.maximum-this.axisX.minimum); if(2<Math.abs(e)){if(this.panEnabled)e=!1,c=0,this.axisX.sessionVariables.internalMinimum<this.axisX._absoluteMinimum?(c=this.axisX._absoluteMinimum-this.axisX.sessionVariables.internalMinimum,this.axisX.sessionVariables.internalMinimum+=c,this.axisX.sessionVariables.internalMaximum+=c,e=!0):this.axisX.sessionVariables.internalMaximum>this.axisX._absoluteMaximum&&(c=this.axisX.sessionVariables.internalMaximum-this.axisX._absoluteMaximum,this.axisX.sessionVariables.internalMaximum-=c,this.axisX.sessionVariables.internalMinimum-= c,e=!0),e&&this.render();else if(this.zoomEnabled){this.resetOverlayedCanvas();if(!this.dragStartPoint)return;"xySwapped"===this.plotInfo.axisPlacement?(b=Math.min(this.dragStartPoint.y,d),c=Math.max(this.dragStartPoint.y,d),1<Math.abs(b-c)&&(e=this.axisX.lineCoordinates,c=this.axisX.maximum-(this.axisX.maximum-this.axisX.minimum)/e.height*(c-e.y1),e=this.axisX.maximum-(this.axisX.maximum-this.axisX.minimum)/e.height*(b-e.y1),c=Math.max(c,this.axisX.dataInfo.min),e=Math.min(e,this.axisX.dataInfo.max), Math.abs((e-c)/this.axisX.dataInfo.minDiff)>=0.008*this.canvas.height&&(this.axisX.sessionVariables.internalMinimum=c,this.axisX.sessionVariables.internalMaximum=e,this.render()))):"normal"===this.plotInfo.axisPlacement&&(c=Math.min(this.dragStartPoint.x,a),b=Math.max(this.dragStartPoint.x,a),1<Math.abs(c-b)&&(e=this.axisX.lineCoordinates,c=(this.axisX.maximum-this.axisX.minimum)/e.width*(c-e.x1)+this.axisX.minimum,e=(this.axisX.maximum-this.axisX.minimum)/e.width*(b-e.x1)+this.axisX.minimum,c=Math.max(c, this.axisX.dataInfo.min),e=Math.min(e,this.axisX.dataInfo.max),Math.abs((e-c)/this.axisX.dataInfo.minDiff)>=0.01*this.canvas.width&&(this.axisX.sessionVariables.internalMinimum=c,this.axisX.sessionVariables.internalMaximum=e,this.render())))}this._toolBar.style.display="inline"}}this.dragStartPoint=null};t.prototype._plotAreaMouseMove=function(a,d){if(this.isDrag){var b=0,c=0,c=this.axisX.lineCoordinates;"xySwapped"===this.plotInfo.axisPlacement?(b=d-this.dragStartPoint.y,c=Math.abs(this.axisX.maximum- this.axisX.minimum)/c.height*b):(b=this.dragStartPoint.x-a,c=Math.abs(this.axisX.maximum-this.axisX.minimum)/c.width*b);2<Math.abs(b)&&8>Math.abs(b)&&(this.panEnabled||this.zoomEnabled)?this._toolTip.hide():this._toolTip.enabled&&(!this.panEnabled&&!this.zoomEnabled)&&this._toolTip.mouseMoveHandler(a,d);if(2<Math.abs(b)&&(this.panEnabled||this.zoomEnabled))if(this.panEnabled){this.axisX.sessionVariables.internalMinimum=this.dragStartPoint.xMinimum+c;this.axisX.sessionVariables.internalMaximum=this.dragStartPoint.xMaximum+ c;b=0;this.axisX.sessionVariables.internalMinimum<this.axisX._absoluteMinimum-M(this.axisX.interval,this.axisX.intervalType)?(b=this.axisX._absoluteMinimum-M(this.axisX.interval,this.axisX.intervalType)-this.axisX.sessionVariables.internalMinimum,this.axisX.sessionVariables.internalMinimum+=b,this.axisX.sessionVariables.internalMaximum+=b):this.axisX.sessionVariables.internalMaximum>this.axisX._absoluteMaximum+M(this.axisX.interval,this.axisX.intervalType)&&(b=this.axisX.sessionVariables.internalMaximum- (this.axisX._absoluteMaximum+M(this.axisX.interval,this.axisX.intervalType)),this.axisX.sessionVariables.internalMaximum-=b,this.axisX.sessionVariables.internalMinimum-=b);var e=this;clearTimeout(this._panTimerId);this._panTimerId=setTimeout(function(){e.render()},0)}else this.zoomEnabled&&(b=this.getPlotArea(),this.resetOverlayedCanvas(),c=this.overlaidCanvasCtx.globalAlpha,this.overlaidCanvasCtx.globalAlpha=0.7,this.overlaidCanvasCtx.fillStyle="#A0ABB8","xySwapped"===this.plotInfo.axisPlacement? this.overlaidCanvasCtx.fillRect(b.x1,this.dragStartPoint.y,b.x2-b.x1,d-this.dragStartPoint.y):"normal"===this.plotInfo.axisPlacement&&this.overlaidCanvasCtx.fillRect(this.dragStartPoint.x,b.y1,a-this.dragStartPoint.x,b.y2-b.y1),this.overlaidCanvasCtx.globalAlpha=c)}else this._toolTip.enabled&&this._toolTip.mouseMoveHandler(a,d)};t.prototype.getPlotArea=function(){var a,d,b,c;c=this.axisY?this.axisY:this.axisY2;if(this.axisX&&c)a=this.axisX.lineCoordinates.x1<this.axisX.lineCoordinates.x2?this.axisX.lineCoordinates.x1: c.lineCoordinates.x1,b=this.axisX.lineCoordinates.y1<c.lineCoordinates.y1?this.axisX.lineCoordinates.y1:c.lineCoordinates.y1,d=this.axisX.lineCoordinates.x2>c.lineCoordinates.x2?this.axisX.lineCoordinates.x2:c.lineCoordinates.x2,c=this.axisX.lineCoordinates.y2>this.axisX.lineCoordinates.y1?this.axisX.lineCoordinates.y2:c.lineCoordinates.y2;else return this.layoutManager.getFreeSpace();return{x1:a,y1:b,x2:d,y2:c,width:d-a,height:c-b}};t.prototype.getPixelCoordinatesOnPlotArea=function(a,d){return{x:this.axisX.getPixelCoordinatesOnAxis(a).x, y:this.axisY.getPixelCoordinatesOnAxis(d).y}};t.prototype.renderIndexLabels=function(){this.ctx.textBaseline="middle";for(var a=this.getPlotArea(),d=0;d<this._indexLabels.length;d++){var b=this._indexLabels[d],c,e,f;this.ctx.fillStyle="indexLabelFontColor"in b.dataPoint?b.dataPoint.indexLabelFontColor:b.dataSeries.indexLabelFontColor;f=this.ctx;var g=b.dataPoint,k=b.dataSeries,h="",h=h+(g.indexLabelFontStyle?g.indexLabelFontStyle+" ":k&&k.indexLabelFontStyle?k.indexLabelFontStyle+" ":""),h=h+(g.indexLabelFontWeight? g.indexLabelFontWeight+" ":k&&k.indexLabelFontWeight?k.indexLabelFontWeight+" ":""),h=h+(g.indexLabelFontSize?g.indexLabelFontSize+"px ":k&&k.indexLabelFontSize?k.indexLabelFontSize+"px ":""),h=h+(g.indexLabelFontFamily?g.indexLabelFontFamily+" ":k&&k.indexLabelFontFamily?k.indexLabelFontFamily+" ":"");f.font=h;var g=this.replaceKeywordsWithValue("indexLabel"in b.dataPoint?b.dataPoint.indexLabel:b.dataSeries.indexLabel,b.dataPoint,b.dataSeries),k=this.ctx.measureText(g).width,h="indexLabelFontSize"in b.dataPoint?b.dataPoint.indexLabelFontSize:b.dataSeries.indexLabelFontSize,j="indexLabelPlacement"in b.dataPoint?b.dataPoint.indexLabelPlacement:b.dataSeries.indexLabelPlacement,m="indexLabelOrientation"in b.dataPoint?b.dataPoint.indexLabelOrientation:b.dataSeries.indexLabelOrientation,n=f=0,p=0,l=0,s=0;"column"===b.chartType||"stackedColumn"===b.chartType||"stackedColumn100"===b.chartType||"bar"===b.chartType||"stackedBar"===b.chartType||"stackedBar100"===b.chartType?(Math.abs(b.bounds.x1,b.bounds.x2), Math.abs(b.bounds.y1,b.bounds.y2),"normal"===this.plotInfo.axisPlacement?("outside"===j?(n=a.y1,p=a.y2):"inside"===j&&(n=b.bounds.y1,p=b.bounds.y2),"horizontal"===m?(c=b.point.x-k/2,e=0<=b.dataPoint.y?Math.min(Math.max(b.point.y-h/2-5,n+h/2+5),p-h/2-5):Math.max(Math.min(b.point.y+h/2+5,p-h/2),n+h/2+5)):"vertical"===m&&(c=b.point.x,e=0<=b.dataPoint.y?Math.min(Math.max(b.point.y-5,n+k+5),p):Math.max(Math.min(b.point.y+k+5,p-5),n),f=-90)):"xySwapped"===this.plotInfo.axisPlacement&&("outside"===j?(l= a.x1,s=a.x2):"inside"===j&&(l=b.bounds.x1,s=b.bounds.x2),"horizontal"===m?(e=b.point.y,c=0<=b.dataPoint.y?Math.max(Math.min(b.point.x+5,s-k),l):Math.min(Math.max(b.point.x-k-5,l),s)):"vertical"===m&&(e=b.point.y+k/2,c=0<=b.dataPoint.y?Math.max(Math.min(b.point.x+h/2+5,s-h/2),l):Math.min(Math.max(b.point.x-h/2-5,l+h/2),s+h/2),f=-90))):"horizontal"===m?(c=b.point.x-k/2,e=0<=b.dataPoint.y?Math.max(b.point.y-h/2-5,a.y1+h/2):Math.min(b.point.y+h/2+5,a.y2-h/2)):"vertical"===m&&(c=b.point.x,e=0<=b.dataPoint.y? Math.max(b.point.y-5,a.y1+k):Math.min(b.point.y+k+5,a.y2),f=-90);this.ctx.save();this.ctx.translate(c,e);this.ctx.rotate(Math.PI/180*f);this.ctx.fillText(g,0,0);this.ctx.restore()}};t.prototype.renderLine=function(a){if(!(0>=a.dataSeriesIndexes.length)){var d=this._eventManager.ghostCtx;this.ctx.save();var b=this.getPlotArea();this.ctx.beginPath();this.ctx.rect(b.x1,b.y1,b.width,b.height);this.ctx.clip();for(var b=[],c=0;c<a.dataSeriesIndexes.length;c++){var e=a.dataSeriesIndexes[c],f=this.data[e]; this.ctx.lineWidth=f.lineThickness;var g=f.dataPoints,k=f.id;this._eventManager.objectMap[k]={objectType:"dataSeries",dataSeriesIndex:e};k=A(k);d.strokeStyle=k;d.lineWidth=0<f.lineThickness?Math.max(f.lineThickness,4):0;colorSet=f._colorSet;color=colorSet[0];this.ctx.strokeStyle=color;var k=!0,h=0,j,m;if(0<g.length){for(h=0;h<g.length;h++)if(j=g[h].getTime?g[h].x.getTime():g[h].x,!(j<a.axisX.dataInfo.viewPortMin||j>a.axisX.dataInfo.viewPortMax)&&"number"===typeof g[h].y){j=a.axisX.convertionParameters.reference+ a.axisX.convertionParameters.pixelPerUnit*(j-a.axisX.convertionParameters.minimum)+0.5<<0;m=a.axisY.convertionParameters.reference+a.axisY.convertionParameters.pixelPerUnit*(g[h].y-a.axisY.convertionParameters.minimum)+0.5<<0;var n=f.dataPointIds[h];this._eventManager.objectMap[n]={objectType:"dataPoint",dataSeriesIndex:e,dataPointIndex:h,x1:j,y1:m};k?(this.ctx.beginPath(),this.ctx.moveTo(j,m),d.beginPath(),d.moveTo(j,m),k=!1):(this.ctx.lineTo(j,m),d.lineTo(j,m),0==h%500&&(this.ctx.stroke(),this.ctx.beginPath(), this.ctx.moveTo(j,m),d.stroke(),d.beginPath(),d.moveTo(j,m)));if(0<g[h].markerSize||0<f.markerSize){var p=f.getMarkerProperties(h,j,m,this.ctx);b.push(p);n=A(n);b.push({x:j,y:m,ctx:d,type:p.type,size:p.size,color:n,borderColor:n,borderThickness:p.borderThickness})}(g[h].indexLabel||f.indexLabel)&&this._indexLabels.push({chartType:"line",dataPoint:g[h],dataSeries:f,point:{x:j,y:m},color:color})}this.ctx.stroke();d.stroke()}}H.drawMarkers(b);this.ctx.restore();this.ctx.beginPath();d.beginPath()}};var C= function(a,d,b,c,e,f,g,k,h,j){var m=15<c-d&&15<e-b?8:0.35*Math.min(c-d,e-b);color2="rgba(255, 255, 255, .4)";color3="rgba(255, 255, 255, 0.1)";color1=f;a.beginPath();a.moveTo(d,b);a.save();a.fillStyle=color1;a.fillRect(d,b,c-d,e-b);a.restore();!0===g&&(a.save(),a.beginPath(),a.moveTo(d,b),a.lineTo(d+m,b+m),a.lineTo(c-m,b+m),a.lineTo(c,b),a.closePath(),f=a.createLinearGradient((c+d)/2,b+m,(c+d)/2,b),f.addColorStop(0,color1),f.addColorStop(1,color2),a.fillStyle=f,a.fill(),a.restore());!0===k&&(a.save(), a.beginPath(),a.moveTo(d,e),a.lineTo(d+m,e-m),a.lineTo(c-m,e-m),a.lineTo(c,e),a.closePath(),f=a.createLinearGradient((c+d)/2,e-m,(c+d)/2,e),f.addColorStop(0,color1),f.addColorStop(1,color2),a.fillStyle=f,a.fill(),a.restore());!0===h&&(a.save(),a.beginPath(),a.moveTo(d,b),a.lineTo(d+m,b+m),a.lineTo(d+m,e-m),a.lineTo(d,e),a.closePath(),f=a.createLinearGradient(d+m,(e+b)/2,d,(e+b)/2),f.addColorStop(0,color1),f.addColorStop(1,color3),a.fillStyle=f,a.fill(),a.restore());!0===j&&(a.save(),a.beginPath(), a.moveTo(c,b),a.lineTo(c-m,b+m),a.lineTo(c-m,e-m),a.lineTo(c,e),f=a.createLinearGradient(c-m,(e+b)/2,c,(e+b)/2),f.addColorStop(0,color1),f.addColorStop(1,color3),a.fillStyle=f,f.addColorStop(0,color1),f.addColorStop(1,color3),a.fillStyle=f,a.fill(),a.closePath(),a.restore())};t.prototype.renderColumn=function(a){if(!(0>=a.dataSeriesIndexes.length)){var d=null,b=this.getPlotArea(),c=0,e,f,g=a.axisY.convertionParameters.reference+a.axisY.convertionParameters.pixelPerUnit*(0-a.axisY.convertionParameters.minimum)<< 0,k=0.15*this.canvas.width,c=a.axisX.dataInfo.minDiff,h=0.9*(b.width/Math.abs(a.axisX.maximum-a.axisX.minimum)*Math.abs(c)/a.plotType.totalDataSeries)<<0;this.ctx.save();this._eventManager.ghostCtx.save();this.ctx.beginPath();this.ctx.rect(b.x1,b.y1,b.width,b.height);this.ctx.clip();this._eventManager.ghostCtx.rect(b.x1,b.y1,b.width,b.height);this._eventManager.ghostCtx.clip();for(var j=0;j<a.dataSeriesIndexes.length;j++){var m=a.dataSeriesIndexes[j],n=this.data[m],p=n.dataPoints;1==p.length&&(h= k);1>h?h=1:h>k&&(h=k);if(0<p.length)for(var l=5<h&&n.bevelEnabled?!0:!1,c=0;c<p.length;c++)if(p[c].getTime?f=p[c].x.getTime():f=p[c].x,!(f<a.axisX.dataInfo.viewPortMin||f>a.axisX.dataInfo.viewPortMax)&&"number"===typeof p[c].y){b=a.axisX.convertionParameters.reference+a.axisX.convertionParameters.pixelPerUnit*(f-a.axisX.convertionParameters.minimum)+0.5<<0;e=a.axisY.convertionParameters.reference+a.axisY.convertionParameters.pixelPerUnit*(p[c].y-a.axisY.convertionParameters.minimum)+0.5<<0;var s= b-a.plotType.totalDataSeries*h/2+(a.previousDataSeriesCount+j)*h<<0,q=s+h<<0,r;0<=p[c].y?r=g:(r=e,e=g);e>r&&(r=e=r);d=p[c].color?p[c].color:n._colorSet[c%n._colorSet.length];C(this.ctx,s,e,q,r,d,l&&0<=p[c].y,0>p[c].y&&l,!1,!1);d=n.dataPointIds[c];this._eventManager.objectMap[d]={objectType:"dataPoint",dataSeriesIndex:m,dataPointIndex:c,x1:s,y1:e,x2:q,y2:r};d=A(d);C(this._eventManager.ghostCtx,s,e,q,r,d,!1,!1,!1,!1);if(p[c].indexLabel||n.indexLabel)this._indexLabels.push({chartType:"column",dataPoint:p[c], dataSeries:n,point:{x:b,y:0<=p[c].y?e:r},bounds:{x1:s,y1:Math.min(e,r),x2:q,y2:Math.max(e,r)},color:d})}}this.ctx.restore();this._eventManager.ghostCtx.restore()}};t.prototype.renderStackedColumn=function(a){if(!(0>=a.dataSeriesIndexes.length)){var d=null,b=this.getPlotArea(),c=[],e=[],f=0,g,k=a.axisY.convertionParameters.reference+a.axisY.convertionParameters.pixelPerUnit*(0-a.axisY.convertionParameters.minimum)<<0,h=0.15*this.canvas.width,f=a.axisX.dataInfo.minDiff,j=0.9*(b.width/Math.abs(a.axisX.maximum- a.axisX.minimum)*Math.abs(f)/a.plotType.plotUnits.length)<<0;this.ctx.save();this._eventManager.ghostCtx.save();this.ctx.beginPath();this.ctx.rect(b.x1,b.y1,b.width,b.height);this.ctx.clip();this._eventManager.ghostCtx.rect(b.x1,b.y1,b.width,b.height);this._eventManager.ghostCtx.clip();for(var m=0;m<a.dataSeriesIndexes.length;m++){var n=a.dataSeriesIndexes[m],p=this.data[n],l=p.dataPoints;1==l.length&&(j=h);1>j?j=1:j>h&&(j=h);if(0<l.length){var s=5<j&&p.bevelEnabled?!0:!1;this.ctx.strokeStyle="#4572A7 "; for(f=0;f<l.length;f++)if(d=l[f].x.getTime?l[f].x.getTime():l[f].x,!(d<a.axisX.dataInfo.viewPortMin||d>a.axisX.dataInfo.viewPortMax)&&"number"===typeof l[f].y){b=a.axisX.convertionParameters.reference+a.axisX.convertionParameters.pixelPerUnit*(d-a.axisX.convertionParameters.minimum)+0.5<<0;g=a.axisY.convertionParameters.reference+a.axisY.convertionParameters.pixelPerUnit*(l[f].y-a.axisY.convertionParameters.minimum)+0.5<<0;var q=b-a.plotType.plotUnits.length*j/2+a.index*j<<0,r=q+j<<0,u;if(0<=l[f].y){var v= c[d]?c[d]:0;g-=v;u=k-v;c[d]=v+(u-g)}else v=e[d]?e[d]:0,u=g+v,g=k+v,e[d]=v+(u-g);d=l[f].color?l[f].color:p._colorSet[f%p._colorSet.length];C(this.ctx,q,g,r,u,d,s&&0<=l[f].y,0>l[f].y&&s,!1,!1);d=p.dataPointIds[f];this._eventManager.objectMap[d]={objectType:"dataPoint",dataSeriesIndex:n,dataPointIndex:f,x1:q,y1:g,x2:r,y2:u};d=A(d);C(this._eventManager.ghostCtx,q,g,r,u,d,!1,!1,!1,!1);if(l[f].indexLabel||p.indexLabel)this._indexLabels.push({chartType:"stackedColumn",dataPoint:l[f],dataSeries:p,point:{x:b, y:0<=l[f].y?g:u},bounds:{x1:q,y1:Math.min(g,u),x2:r,y2:Math.max(g,u)},color:d})}}}this.ctx.restore();this._eventManager.ghostCtx.restore()}};t.prototype.renderStackedColumn100=function(a){if(!(0>=a.dataSeriesIndexes.length)){var d=null,b=this.getPlotArea(),c=[],e=[],f=0,g,k=a.axisY.convertionParameters.reference+a.axisY.convertionParameters.pixelPerUnit*(0-a.axisY.convertionParameters.minimum)<<0,h=0.15*this.canvas.width,f=a.axisX.dataInfo.minDiff,j=0.9*(b.width/Math.abs(a.axisX.maximum-a.axisX.minimum)* Math.abs(f)/a.plotType.plotUnits.length)<<0;this.ctx.save();this._eventManager.ghostCtx.save();this.ctx.beginPath();this.ctx.rect(b.x1,b.y1,b.width,b.height);this.ctx.clip();this._eventManager.ghostCtx.rect(b.x1,b.y1,b.width,b.height);this._eventManager.ghostCtx.clip();for(var m=0;m<a.dataSeriesIndexes.length;m++){var n=a.dataSeriesIndexes[m],p=this.data[n],l=p.dataPoints;1==l.length&&(j=h);1>j?j=1:j>h&&(j=h);if(0<l.length)for(var s=5<j&&p.bevelEnabled?!0:!1,f=0;f<l.length;f++)if(d=l[f].x.getTime? l[f].x.getTime():l[f].x,!(d<a.axisX.dataInfo.viewPortMin||d>a.axisX.dataInfo.viewPortMax)&&"number"===typeof l[f].y){b=a.axisX.convertionParameters.reference+a.axisX.convertionParameters.pixelPerUnit*(d-a.axisX.convertionParameters.minimum)+0.5<<0;g=a.axisY.convertionParameters.reference+a.axisY.convertionParameters.pixelPerUnit*((0!==a.dataPointYSums[d]?100*(l[f].y/a.dataPointYSums[d]):0)-a.axisY.convertionParameters.minimum)+0.5<<0;var q=b-a.plotType.plotUnits.length*j/2+a.index*j<<0,r=q+j<<0,u; if(0<=l[f].y){var v=c[d]?c[d]:0;g-=v;u=k-v;c[d]=v+(u-g)}else v=e[d]?e[d]:0,u=g+v,g=k+v,e[d]=v+(u-g);d=l[f].color?l[f].color:p._colorSet[f%p._colorSet.length];C(this.ctx,q,g,r,u,d,s&&0<=l[f].y,0>l[f].y&&s,!1,!1);d=p.dataPointIds[f];this._eventManager.objectMap[d]={objectType:"dataPoint",dataSeriesIndex:n,dataPointIndex:f,x1:q,y1:g,x2:r,y2:u};d=A(d);C(this._eventManager.ghostCtx,q,g,r,u,d,!1,!1,!1,!1);if(l[f].indexLabel||p.indexLabel)this._indexLabels.push({chartType:"stackedColumn100",dataPoint:l[f], dataSeries:p,point:{x:b,y:0<=l[f].y?g:u},bounds:{x1:q,y1:Math.min(g,u),x2:r,y2:Math.max(g,u)},color:d})}}this.ctx.restore();this._eventManager.ghostCtx.restore()}};t.prototype.renderBar=function(a){if(!(0>=a.dataSeriesIndexes.length)){var d=null,b=this.getPlotArea(),c=0,e,f,g=a.axisY.convertionParameters.reference+a.axisY.convertionParameters.pixelPerUnit*(0-a.axisY.convertionParameters.minimum)<<0,k=0.15*this.canvas.height,c=a.axisX.dataInfo.minDiff,h=0.9*(b.height/Math.abs(a.axisX.maximum-a.axisX.minimum)* Math.abs(c)/a.plotType.totalDataSeries)<<0;this.ctx.save();this._eventManager.ghostCtx.save();this.ctx.beginPath();this.ctx.rect(b.x1,b.y1,b.width,b.height);this.ctx.clip();this._eventManager.ghostCtx.rect(b.x1,b.y1,b.width,b.height);this._eventManager.ghostCtx.clip();for(var j=0;j<a.dataSeriesIndexes.length;j++){var m=a.dataSeriesIndexes[j],n=this.data[m],p=n.dataPoints;1==p.length&&(h=k);1>h?h=1:h>k&&(h=k);if(0<p.length){var l=5<h&&n.bevelEnabled?!0:!1;this.ctx.strokeStyle="#4572A7 ";for(c=0;c< p.length;c++)if(p[c].getTime?f=p[c].x.getTime():f=p[c].x,!(f<a.axisX.dataInfo.viewPortMin||f>a.axisX.dataInfo.viewPortMax)&&"number"===typeof p[c].y){b=a.axisX.convertionParameters.reference+a.axisX.convertionParameters.pixelPerUnit*(f-a.axisX.convertionParameters.minimum)+0.5<<0;e=a.axisY.convertionParameters.reference+a.axisY.convertionParameters.pixelPerUnit*(p[c].y-a.axisY.convertionParameters.minimum)+0.5<<0;var s=b-a.plotType.totalDataSeries*h/2+(a.previousDataSeriesCount+j)*h<<0,q=s+h<<0,r; 0<=p[c].y?r=g:(r=e,e=g);d=p[c].color?p[c].color:n._colorSet[c%n._colorSet.length];C(this.ctx,r,s,e,q,d,l,!1,!1,!1);d=n.dataPointIds[c];this._eventManager.objectMap[d]={objectType:"dataPoint",dataSeriesIndex:m,dataPointIndex:c,x1:r,y1:s,x2:e,y2:q};d=A(d);C(this._eventManager.ghostCtx,r,s,e,q,d,!1,!1,!1,!1);this._indexLabels.push({chartType:"bar",dataPoint:p[c],dataSeries:n,point:{x:0<=p[c].y?e:r,y:b},bounds:{x1:Math.min(r,e),y1:s,x2:Math.max(r,e),y2:q},color:d})}}}this.ctx.restore();this._eventManager.ghostCtx.restore()}}; t.prototype.renderStackedBar=function(a){if(!(0>=a.dataSeriesIndexes.length)){var d=null,b=this.getPlotArea(),c=[],e=[],f=0,g,k=a.axisY.convertionParameters.reference+a.axisY.convertionParameters.pixelPerUnit*(0-a.axisY.convertionParameters.minimum)<<0,h=0.15*this.canvas.width,f=a.axisX.dataInfo.minDiff,j=0.9*(b.height/Math.abs(a.axisX.maximum-a.axisX.minimum)*Math.abs(f)/a.plotType.plotUnits.length)<<0;this.ctx.save();this._eventManager.ghostCtx.save();this.ctx.beginPath();this.ctx.rect(b.x1,b.y1, b.width,b.height);this.ctx.clip();this._eventManager.ghostCtx.rect(b.x1,b.y1,b.width,b.height);this._eventManager.ghostCtx.clip();for(var m=0;m<a.dataSeriesIndexes.length;m++){var n=a.dataSeriesIndexes[m],p=this.data[n],l=p.dataPoints;1==l.length&&(j=h);1>j?j=1:j>h&&(j=h);if(0<l.length){var s=5<j&&p.bevelEnabled?!0:!1;this.ctx.strokeStyle="#4572A7 ";for(f=0;f<l.length;f++)if(d=l[f].x.getTime?l[f].x.getTime():l[f].x,!(d<a.axisX.dataInfo.viewPortMin||d>a.axisX.dataInfo.viewPortMax)&&"number"===typeof l[f].y){b= a.axisX.convertionParameters.reference+a.axisX.convertionParameters.pixelPerUnit*(d-a.axisX.convertionParameters.minimum)+0.5<<0;g=a.axisY.convertionParameters.reference+a.axisY.convertionParameters.pixelPerUnit*(l[f].y-a.axisY.convertionParameters.minimum)+0.5<<0;var q=b-a.plotType.plotUnits.length*j/2+a.index*j<<0,r=q+j<<0,u;if(0<=l[f].y){var v=c[d]?c[d]:0;u=k+v;g+=v;c[d]=v+(g-u)}else v=e[d]?e[d]:0,u=g-v,g=k-v,e[d]=v+(g-u);d=l[f].color?l[f].color:p._colorSet[f%p._colorSet.length];C(this.ctx,u,q, g,r,d,s,!1,!1,!1);d=p.dataPointIds[f];this._eventManager.objectMap[d]={objectType:"dataPoint",dataSeriesIndex:n,dataPointIndex:f,x1:u,y1:q,x2:g,y2:r};d=A(d);C(this._eventManager.ghostCtx,u,q,g,r,d,!1,!1,!1,!1);this._indexLabels.push({chartType:"stackedBar",dataPoint:l[f],dataSeries:p,point:{x:0<=l[f].y?g:u,y:b},bounds:{x1:Math.min(u,g),y1:q,x2:Math.max(u,g),y2:r},color:d})}}}this.ctx.restore();this._eventManager.ghostCtx.restore()}};t.prototype.renderStackedBar100=function(a){if(!(0>=a.dataSeriesIndexes.length)){var d= null,b=this.getPlotArea(),c=[],e=[],f=0,g,k=a.axisY.convertionParameters.reference+a.axisY.convertionParameters.pixelPerUnit*(0-a.axisY.convertionParameters.minimum)<<0,h=0.15*this.canvas.width,f=a.axisX.dataInfo.minDiff,j=0.9*(b.height/Math.abs(a.axisX.maximum-a.axisX.minimum)*Math.abs(f)/a.plotType.plotUnits.length)<<0;this.ctx.save();this._eventManager.ghostCtx.save();this.ctx.beginPath();this.ctx.rect(b.x1,b.y1,b.width,b.height);this.ctx.clip();this._eventManager.ghostCtx.rect(b.x1,b.y1,b.width, b.height);this._eventManager.ghostCtx.clip();for(var m=0;m<a.dataSeriesIndexes.length;m++){var n=a.dataSeriesIndexes[m],p=this.data[n],l=p.dataPoints;1==l.length&&(j=h);1>j?j=1:j>h&&(j=h);if(0<l.length){var s=5<j&&p.bevelEnabled?!0:!1;this.ctx.strokeStyle="#4572A7 ";for(f=0;f<l.length;f++)if(d=l[f].x.getTime?l[f].x.getTime():l[f].x,!(d<a.axisX.dataInfo.viewPortMin||d>a.axisX.dataInfo.viewPortMax)&&"number"===typeof l[f].y){b=a.axisX.convertionParameters.reference+a.axisX.convertionParameters.pixelPerUnit* (d-a.axisX.convertionParameters.minimum)+0.5<<0;g=a.axisY.convertionParameters.reference+a.axisY.convertionParameters.pixelPerUnit*((0!==a.dataPointYSums[d]?100*(l[f].y/a.dataPointYSums[d]):0)-a.axisY.convertionParameters.minimum)+0.5<<0;var q=b-a.plotType.plotUnits.length*j/2+a.index*j<<0,r=q+j<<0,u;if(0<=l[f].y){var v=c[d]?c[d]:0;u=k+v;g+=v;c[d]=v+(g-u)}else v=e[d]?e[d]:0,u=g-v,g=k-v,e[d]=v+(g-u);d=l[f].color?l[f].color:p._colorSet[f%p._colorSet.length];C(this.ctx,u,q,g,r,d,s,!1,!1,!1);d=p.dataPointIds[f]; this._eventManager.objectMap[d]={objectType:"dataPoint",dataSeriesIndex:n,dataPointIndex:f,x1:u,y1:q,x2:g,y2:r};d=A(d);C(this._eventManager.ghostCtx,u,q,g,r,d,!1,!1,!1,!1);this._indexLabels.push({chartType:"stackedBar100",dataPoint:l[f],dataSeries:p,point:{x:0<=l[f].y?g:u,y:b},bounds:{x1:Math.min(u,g),y1:q,x2:Math.max(u,g),y2:r},color:d})}}}this.ctx.restore();this._eventManager.ghostCtx.restore()}};t.prototype.renderArea=function(a){if(!(0>=a.dataSeriesIndexes.length)){var d=this._eventManager.ghostCtx, b=a.axisX.lineCoordinates,c=a.axisY.lineCoordinates,e=[],f=this.getPlotArea();this.ctx.save();d.save();this.ctx.beginPath();this.ctx.rect(f.x1,f.y1,f.width,f.height);this.ctx.clip();d.beginPath();d.rect(f.x1,f.y1,f.width,f.height);d.clip();for(f=0;f<a.dataSeriesIndexes.length;f++){var g=a.dataSeriesIndexes[f],k=this.data[g],h=k.dataPoints,e=k.id;this._eventManager.objectMap[e]={objectType:"dataSeries",dataSeriesIndex:g};e=A(e);d.fillStyle=e;var e=[],j=!0,m=0,n,p,l=a.axisY.convertionParameters.reference+ a.axisY.convertionParameters.pixelPerUnit*(0-a.axisY.convertionParameters.minimum)+0.5<<0,s,q=null;if(0<h.length){color=k._colorSet[m%k._colorSet.length];for(this.ctx.fillStyle=color;m<h.length;m++)if(p=h[m].x.getTime?h[m].x.getTime():h[m].x,!(p<a.axisX.dataInfo.viewPortMin||p>a.axisX.dataInfo.viewPortMax))if(n=a.axisX.convertionParameters.reference+a.axisX.convertionParameters.pixelPerUnit*(p-a.axisX.convertionParameters.minimum)+0.5<<0,p=a.axisY.convertionParameters.reference+a.axisY.convertionParameters.pixelPerUnit* (h[m].y-a.axisY.convertionParameters.minimum)+0.5<<0,"number"===typeof h[m].y){j?(this.ctx.beginPath(),this.ctx.moveTo(n,p),q={x:n,y:p},d.beginPath(),d.moveTo(n,p),j=!1):(this.ctx.lineTo(n,p),d.lineTo(n,p),0==m%250&&(0>=a.axisY.minimum&&0<=a.axisY.maximum?s=l:0>a.axisY.maximum?s=c.y1:0<a.axisY.minimum&&(s=b.y2),this.ctx.lineTo(n,s),this.ctx.lineTo(q.x,s),this.ctx.closePath(),this.ctx.fill(),this.ctx.beginPath(),this.ctx.moveTo(n,p),d.lineTo(n,s),d.lineTo(q.x,s),d.closePath(),d.fill(),d.beginPath(), d.moveTo(n,p),q={x:n,y:p}));var r=k.dataPointIds[m];this._eventManager.objectMap[r]={objectType:"dataPoint",dataSeriesIndex:g,dataPointIndex:m,x1:n,y1:p};if(0!==h[m].markerSize&&(0<h[m].markerSize||0<k.markerSize)){var u=k.getMarkerProperties(m,n,p,this.ctx);e.push(u);markerColor=A(r);e.push({x:n,y:p,ctx:d,type:u.type,size:u.size,color:markerColor,borderColor:markerColor,borderThickness:u.borderThickness})}(h[m].indexLabel||k.indexLabel)&&this._indexLabels.push({chartType:"area",dataPoint:h[m],dataSeries:k, point:{x:n,y:p},color:color})}0>=a.axisY.minimum&&0<=a.axisY.maximum?s=l:0>a.axisY.maximum?s=c.y1:0<a.axisY.minimum&&(s=b.y2);this.ctx.lineTo(n,s);this.ctx.lineTo(q.x,s);this.ctx.closePath();this.ctx.fill();d.lineTo(n,s);d.lineTo(q.x,s);d.closePath();d.fill();H.drawMarkers(e)}}this.ctx.restore();this._eventManager.ghostCtx.restore()}};t.prototype.renderStackedArea=function(a){if(!(0>=a.dataSeriesIndexes.length)){var d=null,b=[],c=this.getPlotArea(),e=[],f=[],g=0,k,h,j,m=a.axisY.convertionParameters.reference+ a.axisY.convertionParameters.pixelPerUnit*(0-a.axisY.convertionParameters.minimum)<<0,n=this._eventManager.ghostCtx;n.beginPath();this.ctx.save();n.save();this.ctx.beginPath();this.ctx.rect(c.x1,c.y1,c.width,c.height);this.ctx.clip();n.beginPath();n.rect(c.x1,c.y1,c.width,c.height);n.clip();xValuePresent=[];for(c=0;c<a.dataSeriesIndexes.length;c++){var p=a.dataSeriesIndexes[c],l=this.data[p],s=l.dataPoints;l.dataPointIndexes=[];for(g=0;g<s.length;g++)p=s[g].x.getTime?s[g].x.getTime():s[g].x,l.dataPointIndexes[p]= g,xValuePresent[p]||(f.push(p),xValuePresent[p]=!0);f.sort(Z)}for(c=0;c<a.dataSeriesIndexes.length;c++){var p=a.dataSeriesIndexes[c],l=this.data[p],s=l.dataPoints,q=!0,r=[],g=l.id;this._eventManager.objectMap[g]={objectType:"dataSeries",dataSeriesIndex:p};g=A(g);n.fillStyle=g;if(0<f.length){d=l._colorSet[0];this.ctx.fillStyle=d;for(g=0;g<f.length;g++){j=f[g];var u=null,u=0<=l.dataPointIndexes[j]?s[l.dataPointIndexes[j]]:{x:j,y:0};if(!(j<a.axisX.dataInfo.viewPortMin||j>a.axisX.dataInfo.viewPortMax)&& "number"===typeof u.y){k=a.axisX.convertionParameters.reference+a.axisX.convertionParameters.pixelPerUnit*(j-a.axisX.convertionParameters.minimum)+0.5<<0;h=a.axisY.convertionParameters.reference+a.axisY.convertionParameters.pixelPerUnit*(u.y-a.axisY.convertionParameters.minimum)+0.5<<0;var v=e[j]?e[j]:0;h-=v;r.push({x:k,y:m-v});e[j]=m-h;if(q)this.ctx.beginPath(),this.ctx.moveTo(k,h),n.beginPath(),n.moveTo(k,h),q=!1;else if(this.ctx.lineTo(k,h),n.lineTo(k,h),0==g%250){for(;0<r.length;){var t=r.pop(); this.ctx.lineTo(t.x,t.y);n.lineTo(t.x,t.y)}this.ctx.closePath();this.ctx.fill();this.ctx.beginPath();this.ctx.moveTo(k,h);n.closePath();n.fill();n.beginPath();n.moveTo(k,h);r.push({x:k,y:m-v})}if(0<=l.dataPointIndexes[j]){var y=l.dataPointIds[l.dataPointIndexes[j]];this._eventManager.objectMap[y]={objectType:"dataPoint",dataSeriesIndex:p,dataPointIndex:l.dataPointIndexes[j],x1:k,y1:h}}if(0<=l.dataPointIndexes[j]&&0!==u.markerSize&&(0<u.markerSize||0<l.markerSize))j=l.getMarkerProperties(g,k,h,this.ctx), b.push(j),markerColor=A(y),b.push({x:k,y:h,ctx:n,type:j.type,size:j.size,color:markerColor,borderColor:markerColor,borderThickness:j.borderThickness});(u.indexLabel||l.indexLabel)&&this._indexLabels.push({chartType:"stackedArea",dataPoint:u,dataSeries:l,point:{x:k,y:h},color:d})}}for(;0<r.length;)t=r.pop(),this.ctx.lineTo(t.x,t.y),n.lineTo(t.x,t.y);this.ctx.closePath();this.ctx.fill();this.ctx.beginPath();this.ctx.moveTo(k,h);n.closePath();n.fill();n.beginPath();n.moveTo(k,h)}delete l.dataPointIndexes}H.drawMarkers(b); this.ctx.restore();n.restore()}};t.prototype.renderStackedArea100=function(a){if(!(0>=a.dataSeriesIndexes.length)){var d=null,b=this.getPlotArea(),c=[],e=[],f=[],g=0,k,h,j,m=a.axisY.convertionParameters.reference+a.axisY.convertionParameters.pixelPerUnit*(0-a.axisY.convertionParameters.minimum)<<0,n=0.15*this.canvas.width,p=a.axisX.dataInfo.minDiff,p=0.9*b.width/Math.abs(a.axisX.maximum-a.axisX.minimum)*Math.abs(p)<<0,l=this._eventManager.ghostCtx;this.ctx.save();l.save();this.ctx.beginPath();this.ctx.rect(b.x1, b.y1,b.width,b.height);this.ctx.clip();l.beginPath();l.rect(b.x1,b.y1,b.width,b.height);this._eventManager.ghostCtx.clip();xValuePresent=[];for(b=0;b<a.dataSeriesIndexes.length;b++){var s=a.dataSeriesIndexes[b],q=this.data[s],r=q.dataPoints;q.dataPointIndexes=[];for(g=0;g<r.length;g++)s=r[g].x.getTime?r[g].x.getTime():r[g].x,q.dataPointIndexes[s]=g,xValuePresent[s]||(f.push(s),xValuePresent[s]=!0);f.sort(Z)}for(b=0;b<a.dataSeriesIndexes.length;b++){var s=a.dataSeriesIndexes[b],q=this.data[s],r=q.dataPoints, u=!0,d=q.id;this._eventManager.objectMap[d]={objectType:"dataSeries",dataSeriesIndex:s};d=A(d);l.fillStyle=d;1==r.length&&(p=n);1>p?p=1:p>n&&(p=n);var v=[];if(0<f.length){d=q._colorSet[g%q._colorSet.length];this.ctx.fillStyle=d;for(g=0;g<f.length;g++){j=f[g];var t=null,t=0<=q.dataPointIndexes[j]?r[q.dataPointIndexes[j]]:{x:j,y:0};if(!(j<a.axisX.dataInfo.viewPortMin||j>a.axisX.dataInfo.viewPortMax)&&"number"===typeof t.y){h=0!==a.dataPointYSums[j]?100*(t.y/a.dataPointYSums[j]):0;k=a.axisX.convertionParameters.reference+ a.axisX.convertionParameters.pixelPerUnit*(j-a.axisX.convertionParameters.minimum)+0.5<<0;h=a.axisY.convertionParameters.reference+a.axisY.convertionParameters.pixelPerUnit*(h-a.axisY.convertionParameters.minimum)+0.5<<0;var y=e[j]?e[j]:0;h-=y;v.push({x:k,y:m-y});e[j]=m-h;if(u)this.ctx.beginPath(),this.ctx.moveTo(k,h),l.beginPath(),l.moveTo(k,h),u=!1;else if(this.ctx.lineTo(k,h),l.lineTo(k,h),0==g%250){for(;0<v.length;){var x=v.pop();this.ctx.lineTo(x.x,x.y);l.lineTo(x.x,x.y)}this.ctx.closePath(); this.ctx.fill();this.ctx.beginPath();this.ctx.moveTo(k,h);l.closePath();l.fill();l.beginPath();l.moveTo(k,h);v.push({x:k,y:m-y})}if(0<=q.dataPointIndexes[j]){var F=q.dataPointIds[q.dataPointIndexes[j]];this._eventManager.objectMap[F]={objectType:"dataPoint",dataSeriesIndex:s,dataPointIndex:q.dataPointIndexes[j],x1:k,y1:h}}if(0<=q.dataPointIndexes[j]&&0!==t.markerSize&&(0<t.markerSize||0<q.markerSize))j=q.getMarkerProperties(g,k,h,this.ctx),c.push(j),markerColor=A(F),c.push({x:k,y:h,ctx:l,type:j.type, size:j.size,color:markerColor,borderColor:markerColor,borderThickness:j.borderThickness});(t.indexLabel||q.indexLabel)&&this._indexLabels.push({chartType:"stackedArea100",dataPoint:t,dataSeries:q,point:{x:k,y:h},color:d})}}for(;0<v.length;)x=v.pop(),this.ctx.lineTo(x.x,x.y),l.lineTo(x.x,x.y);this.ctx.closePath();this.ctx.fill();this.ctx.beginPath();this.ctx.moveTo(k,h);l.closePath();l.fill();l.beginPath();l.moveTo(k,h)}delete q.dataPointIndexes}H.drawMarkers(c);this.ctx.restore();l.restore()}};t.prototype.renderBubble= function(a){var d=a.dataSeriesIndexes.length;if(!(0>=d)){var b=this.getPlotArea(),c=0,e,f,g=0.15*this.canvas.width,c=a.axisX.dataInfo.minDiff,d=0.9*(b.width/Math.abs(a.axisX.maximum-a.axisX.minimum)*Math.abs(c)/d)<<0;this.ctx.save();this._eventManager.ghostCtx.save();this.ctx.beginPath();this.ctx.rect(b.x1,b.y1,b.width,b.height);this.ctx.clip();this._eventManager.ghostCtx.rect(b.x1,b.y1,b.width,b.height);this._eventManager.ghostCtx.clip();for(var k=-Infinity,h=Infinity,j=0;j<a.dataSeriesIndexes.length;j++)for(var m= a.dataSeriesIndexes[j],n=this.data[m],p=n.dataPoints,l=0,c=0;c<p.length;c++)if(e=p[c].getTime?e=p[c].x.getTime():e=p[c].x,!(e<a.axisX.dataInfo.viewPortMin||e>a.axisX.dataInfo.viewPortMax)&&"undefined"!==typeof p[c].z)l=p[c].z,l>k&&(k=l),l<h&&(h=l);for(var s=25*Math.PI,b=Math.max(Math.pow(0.25*Math.min(b.height,b.width)/2,2)*Math.PI,s),j=0;j<a.dataSeriesIndexes.length;j++)if(m=a.dataSeriesIndexes[j],n=this.data[m],p=n.dataPoints,1==p.length&&(d=g),1>d?d=1:d>g&&(d=g),0<p.length){this.ctx.strokeStyle= "#4572A7 ";for(c=0;c<p.length;c++)if(e=p[c].getTime?e=p[c].x.getTime():e=p[c].x,!(e<a.axisX.dataInfo.viewPortMin||e>a.axisX.dataInfo.viewPortMax)&&"number"===typeof p[c].y){e=a.axisX.convertionParameters.reference+a.axisX.convertionParameters.pixelPerUnit*(e-a.axisX.convertionParameters.minimum)+0.5<<0;f=a.axisY.convertionParameters.reference+a.axisY.convertionParameters.pixelPerUnit*(p[c].y-a.axisY.convertionParameters.minimum)+0.5<<0;var l=p[c].z,q=2*Math.max(Math.sqrt((s+(b-s)/(k-h)*(l-h))/Math.PI)<< 0,1),l=n.getMarkerProperties(c,this.ctx);l.size=q;H.drawMarker(e,f,this.ctx,l.type,l.size,l.color,l.borderColor,l.borderThickness);var r=n.dataPointIds[c];this._eventManager.objectMap[r]={objectType:"dataPoint",dataSeriesIndex:m,dataPointIndex:c,x1:e,y1:f,size:q};q=A(r);H.drawMarker(e,f,this._eventManager.ghostCtx,l.type,l.size,q,q,l.borderThickness)}}this.ctx.restore();this._eventManager.ghostCtx.restore()}};t.prototype.renderScatter=function(a){var d=a.dataSeriesIndexes.length;if(!(0>=d)){var b= this.getPlotArea(),c=0,e,f,g=0.15*this.canvas.width,c=a.axisX.dataInfo.minDiff,d=0.9*(b.width/Math.abs(a.axisX.maximum-a.axisX.minimum)*Math.abs(c)/d)<<0;this.ctx.save();this._eventManager.ghostCtx.save();this.ctx.beginPath();this.ctx.rect(b.x1,b.y1,b.width,b.height);this.ctx.clip();this._eventManager.ghostCtx.rect(b.x1,b.y1,b.width,b.height);this._eventManager.ghostCtx.clip();for(var k=0;k<a.dataSeriesIndexes.length;k++){var h=a.dataSeriesIndexes[k],j=this.data[h],m=j.dataPoints;1==m.length&&(d= g);1>d?d=1:d>g&&(d=g);if(0<m.length){this.ctx.strokeStyle="#4572A7 ";Math.pow(0.3*Math.min(b.height,b.width)/2,2);for(var n=0,p=0,c=0;c<m.length;c++)if(e=m[c].getTime?e=m[c].x.getTime():e=m[c].x,!(e<a.axisX.dataInfo.viewPortMin||e>a.axisX.dataInfo.viewPortMax)&&"number"===typeof m[c].y){e=a.axisX.convertionParameters.reference+a.axisX.convertionParameters.pixelPerUnit*(e-a.axisX.convertionParameters.minimum)+0.5<<0;f=a.axisY.convertionParameters.reference+a.axisY.convertionParameters.pixelPerUnit* (m[c].y-a.axisY.convertionParameters.minimum)+0.5<<0;var l=j.getMarkerProperties(c,e,f,this.ctx);H.drawMarker(l.x,l.y,l.ctx,l.type,l.size,l.color,l.color,l.thickness);Math.sqrt((n-e)*(n-e)+(p-f)*(p-f))<Math.min(l.size,5)||(n=j.dataPointIds[c],this._eventManager.objectMap[n]={objectType:"dataPoint",dataSeriesIndex:h,dataPointIndex:c,x1:e,y1:f},n=A(n),H.drawMarker(l.x,l.y,this._eventManager.ghostCtx,l.type,l.size,n,n,l.borderThickness),n=e,p=f)}}}this.ctx.restore();this._eventManager.ghostCtx.restore()}}; var L=function(a,d,b,c,e,f,g){a.save();"pie"===e?(a.beginPath(),a.moveTo(d.x,d.y),a.arc(d.x,d.y,b,f,g,!1),a.fillStyle=c,a.strokeStyle="white",a.lineWidth=2,a.closePath(),a.stroke(),a.fill()):"doughnut"===e&&(a.beginPath(),a.arc(d.x,d.y,b,f,g,!1),a.arc(d.x,d.y,0.6*b,g,f,!0),a.closePath(),a.fillStyle=c,a.strokeStyle="white",a.lineWidth=2,a.stroke(),a.fill());a.restore()};t.prototype.renderPie=function(a){function d(){w.ctx.save();w._eventManager.ghostCtx.save();w.ctx.translate(t.x,t.y);w._eventManager.ghostCtx.translate(t.x, t.y);w.ctx.fillStyle=w.backgroundColor?w.backgroundColor:"white";w.ctx.fillRect(-v.width/2,-v.height/2,v.width,v.height);var a=!0===w.animationEnabled?60:1;if(null!=z&&z.frame<a){z.isAnimating--;for(var c=0,c=h[0],k=z.maxAngle+2*Math.PI/a,j=0;j<u;j++){var m=f.dataPoints[j].exploded,l=f.dataPoints[j].color?f.dataPoints[j].color:f.color?f.color:y[j%y.length],q=c,r=c=q+2*Math.PI/n*Math.abs(f.dataPoints[j].y),s=!1;r>k&&(r=k,s=!0);type=f.type;"outside"===f.indexLabelPlacement?(indexLineMinLength=Math.min(v.width, v.height)/14,p=indexLineMinLength<x?x-indexLineMinLength:x-25):"inside"===f.indexLabelPlacement&&(p=(1-g)*0.5*Math.min(v.width,v.height));var B={x:0,y:0};L(w.ctx,B,p,l,type,q,r);q=!0===f.dataPoints[j].exploded?!0:!1;typeof f.dataPoints[j]===Boolean&&(userSetExploed=!0);r=f.dataPointIds[j];w._eventManager.objectMap[r]={objectType:"dataPoint",dataSeriesIndex:0,dataPointIndex:j,center:{x:t.x,y:t.y},radius:p,color:l,startAngle:h[j],endAngle:h[j+1],currentlyExploded:q,userSetExploded:m,pastExploded:!1}; m=T(r);w._eventManager.ghostCtx.save();l="rgb("+m[0]+","+m[1]+","+m[2]+")";L(w._eventManager.ghostCtx,B,p,l,type,h[j],h[j+1]);w._eventManager.ghostCtx.restore();if(s)break}z.maxAngle=k;z.frame++;z.frame<a?w.requestAnimFrame.call(window,d):(e(0,a),w.ctx.restore(),w._eventManager.ghostCtx.restore(),setTimeout(function(){z.frame=0;z.isAnimating=20;b()},200))}w.renderCount++;w.ctx.restore();w._eventManager.ghostCtx.restore()}function b(){w.ctx.save();w._eventManager.ghostCtx.save();w.ctx.translate(t.x, t.y);w._eventManager.ghostCtx.translate(t.x,t.y);if(null!==z&&20>z.frame){z.isAnimating--;w.ctx.fillStyle=w.backgroundColor?w.backgroundColor:"white";w.ctx.fillRect(-v.width/2,-v.height/2,v.width,v.height);for(var a=0;a<u;a++){var c=f.dataPoints[a].color?f.dataPoints[a].color:f.color?f.color:y[a%y.length],d={x:0,y:0},k=p*g*Math.cos(j[a]),m=p*g*Math.sin(j[a]),l=f.type,n=f.dataPointIds[a],q=w._eventManager.objectMap[n].currentlyExploded,r=w._eventManager.objectMap[n].pastExploded;!0===q&&!1===r?(d.x+= k/20*(z.frame+1),d.y+=m/20*(z.frame+1),20===z.frame+1&&(w._eventManager.objectMap[n].pastExploded=!0)):!0===q&&!0===r&&(d.x+=k,d.y+=m);w._eventManager.objectMap[n].center.x=d.x+t.x;w._eventManager.objectMap[n].center.y=d.y+t.y;r!==q&&(k={},k.dataSeries=f,k.dataPoint=f.dataPoints[a],k.index=a,w._toolTip.highlightObjects([k]));L(w.ctx,d,p,c,l,h[a],h[a+1]);19===z.frame&&(n=f.dataPointIds[a],c=T(n),w._eventManager.ghostCtx.save(),c="rgb("+c[0]+","+c[1]+","+c[2]+")",L(w._eventManager.ghostCtx,d,p,c,l, h[a],h[a+1]),w._eventManager.ghostCtx.restore())}z.frame++;20>z.frame&&w.requestAnimFrame.call(window,b)}e(z.frame,20);w.ctx.restore();w._eventManager.ghostCtx.restore()}function c(){w.ctx.save();w._eventManager.ghostCtx.save();w.ctx.translate(t.x,t.y);w._eventManager.ghostCtx.translate(t.x,t.y);if(null!==z&&0<z.frame){z.isAnimating--;w.ctx.fillStyle=w.backgroundColor?w.backgroundColor:"white";w.ctx.fillRect(-v.width/2,-v.height/2,v.width,v.height);for(var a=0;a<u;a++){var b=f.dataPointIds[a],d=w._eventManager.objectMap[b].currentlyExploded, k=w._eventManager.objectMap[b].pastExploded,m=f.dataPoints[a].color?f.dataPoints[a].color:f.color?f.color:y[a%y.length],l={x:0,y:0},n=f.type,d=w._eventManager.objectMap[b].currentlyExploded,q=p*g*Math.cos(j[a]),r=p*g*Math.sin(j[a]);!1===d&&!0===k?(l.x+=q/20*z.frame,l.y+=r/20*z.frame,1===z.frame&&(w._eventManager.objectMap[b].pastExploded=!1)):!0===d&&!0===k&&(l.x+=q,l.y+=r);w._eventManager.objectMap[b].center.x=l.x+t.x;w._eventManager.objectMap[b].center.y=l.y+t.y;k!==d&&(b={},b.dataSeries=f,b.dataPoint= f.dataPoints[a],b.index=a,w._toolTip.highlightObjects([b]));L(w.ctx,l,p,m,n,h[a],h[a+1]);1===z.frame&&(b=f.dataPointIds[a],m=T(b),w._eventManager.ghostCtx.save(),m="rgb("+m[0]+","+m[1]+","+m[2]+")",L(w._eventManager.ghostCtx,l,p,m,n,h[a],h[a+1]),w._eventManager.ghostCtx.restore())}z.frame--;0<z.frame&&w.requestAnimFrame.call(window,c)}e(z.frame,20);w.ctx.restore();w._eventManager.ghostCtx.restore()}function e(a,b){for(var c=0;c<f.dataPoints.length;c++){var d=f.dataPointIds[c],e=w.ctx,h=l[c],n=s[c], t=q[c],u=r[c],v=w._eventManager.objectMap[d].currentlyExploded,x=m[c],y=p,z=j[c],B=f.dataPoints[c].indexLabelFontColor?f.dataPoints[c].indexLabelFontColor:f.indexLabelFontColor,A=f.indexLabelPlacement,E=f.dataPoints[c].indexLabelLineColor?f.dataPoints[c].indexLabelLineColor:f.indexLabelLineColor,C=f.dataPoints[c].indexLabelLineThickness?f.dataPoints[c].indexLabelLineThickness:f.indexLabelLineThickness,D=a,F=b,d=w._eventManager.objectMap[d].pastExploded,G=k[c],H=f.dataPoints[c].indexLabelFontStyle? f.dataPoints[c].indexLabelFontStyle:f.indexLabelFontStyle,I=f.dataPoints[c].indexLabelFontWeight?f.dataPoints[c].indexLabelFontWeight:f.indexLabelFontWeight,J=f.dataPoints[c].indexLabelFontSize?f.dataPoints[c].indexLabelFontSize:f.indexLabelFontSize,K=f.dataPoints[c].indexLabelFontFamily?f.dataPoints[c].indexLabelFontFamily:f.indexLabelFontFamily,L=f.dataPoints[c].indexLabelBackgroundColor?f.dataPoints[c].indexLabelBackgroundColor:f.indexLabelBackgroundColor?f.indexLabelBackgroundColor:null,M=c;e.save(); e.lineWidth=C;e.font=H+" "+I+" "+J+"px "+K;C="left";0>h&&"outside"===A?C="right":0<=h&&"outside"===A?C="left":"inside"===A&&(C="center");e.textAlign=C;e.textBaseline="middle";e.beginPath();L&&(e.fillStyle=L,"outside"===A?0<=h?e.fillRect(h-2.5,t-2.5,n-h+5,u-t+5):e.fillRect(h+2.5,t-2.5,n-h-5,u-t+5):"inside"===A&&(0<=h?e.fillRect(h-G/2-2.5,t-2.5,n-h+5,u-t+5):e.fillRect(h+G/2+2.5,t-2.5,n-h-5,u-t+5)));e.fillStyle=B;e.fillText(x,h,(t+u)/2);"outside"===A&&k[M]&&(n=y*Math.cos(z),x=y*Math.sin(z),!0===v&&!0!== d?(n+=y*g*Math.cos(z)/F*D,x+=y*g*Math.sin(z)/F*D):!0===v&&!0===d?(n+=y*g*Math.cos(z),x+=y*g*Math.sin(z)):!0!==v&&!0===d&&(n+=y*g*Math.cos(z)/F*D,x+=y*g*Math.sin(z)/F*D),e.moveTo(n,x),0<h?(e.lineTo(h-10,(t+u)/2),e.lineTo(h-2,(t+u)/2)):0>h&&(e.lineTo(h+10,(t+u)/2),e.lineTo(h+2,(t+u)/2)),e.strokeStyle=E,e.stroke());e.restore()}}if(!(0>=a.dataSeriesIndexes.length)){var f=this.data[a.dataSeriesIndexes[0]],g=0.07;ctx=this.ctx;var k=[],h=[],j=[],m=[],n=0,p=0,l=[],s=[],q=[],r=[],u=f.dataPoints.length,v=this.getPlotArea(); v.width=v.x2-v.x1;v.height=v.y2-v.y1;var t={x:(v.x2+v.x1)/2,y:(v.y2+v.y1)/2};a=f.startAngle?f.startAngle:0;a=(a%360+360)%360*Math.PI/180;h.push(a);var y=this._selectedColorSet,x=0.5*Math.min(v.width,v.height);for(a=0;a<u;a++){var F=f.dataPoints[a].indexLabel?f.dataPoints[a].indexLabel:f.indexLabel?f.indexLabel:f.dataPoints[a].label?f.dataPoints[a].label:f.label?f.label:"",F=this.replaceKeywordsWithValue(F,f.dataPoints[a],f,a);m.push(F);var F=f.dataPoints[a].indexLabelFontStyle?f.dataPoints[a].indexLabelFontStyle: f.indexLabelFontStyle,B=f.dataPoints[a].indexLabelFontWeight?f.dataPoints[a].indexLabelFontWeight:f.indexLabelFontWeight,E=f.dataPoints[a].indexLabelFontSize?f.dataPoints[a].indexLabelFontSize:f.indexLabelFontSize,A=f.dataPoints[a].indexLabelFontFamily?f.dataPoints[a].indexLabelFontFamily:f.indexLabelFontFamily;ctx.save();ctx.font=F+" "+B+" "+E+"px "+A;F=ctx.measureText(m[a]).width;ctx.restore();k.push(F);n+=Math.abs(f.dataPoints[a].y)}for(a=F=0;a<u;a++)B=Math.abs(f.dataPoints[a].y),B=2*Math.PI*(B/ n),h.push(h[a]+B),B=B/2+h[a],j.push(B%(2*Math.PI)),F+=k[a];0===F&&(f.indexLabelPlacement="inside");F=0;if("inside"===f.indexLabelPlacement){x*=0.8*(1-g);for(a=0;a<u;a++)E=x*Math.cos(j[a]),A=x*Math.sin(j[a]),l.push(E),0<E?s.push(l[a]+k[a]):s.push(l[a]-k[a]),q.push(A-f.indexLabelFontSize/2),r.push(A+f.indexLabelFontSize/2)}else if("outside"===f.indexLabelPlacement)for(B=0;3>B;B++){for(a=0;a<u;a++)E=x*Math.cos(j[a]),A=x*Math.sin(j[a]),l.push(E),0<E?s.push(l[a]+k[a]):s.push(l[a]-k[a]),q.push(A-f.indexLabelFontSize/ 2),r.push(A+f.indexLabelFontSize/2);for(a=0;a<u;a++)j[a]<Math.PI/2&&(1<=a&&q[a]<r[a-1])&&(E=r[a-1]-q[a],q[a]+=E+2,r[a]+=E+2,20>u&&(q[a]+=3,r[a]+=3)),j[a]<3*Math.PI/2&&j[a]>=Math.PI&&r[a]>q[a-1]&&(E=r[a]-q[a-1],q[a]-=E+2,r[a]-=E+2,20>u&&(q[a]-=3,r[a]-=3));for(a=u;0<=a;a--)j[a]<Math.PI&&j[a]>=Math.PI/2&&q[a]<r[a+1]&&(E=r[a+1]-q[a],q[a]+=E+2,r[a]+=E+2,20>u&&(q[a]+=3,r[a]+=3)),j[a]>=3*Math.PI/2&&r[a]>q[a+1]&&(E=r[a]-q[a+1],q[a]-=E,r[a]-=E,20>u&&(q[a]+=-3,r[a]+=-3));if(2>F){a=Math.min.apply(Math,q.concat(r)); var E=Math.max.apply(Math,q.concat(r)),A=Math.max.apply(Math,s.concat(l)),D=Math.min.apply(Math,s.concat(l)),C=[];Math.abs(a)>v.height/2&&C.push(Math.abs(a)-v.height/2);Math.abs(E)>v.height/2&&C.push(Math.abs(E)-v.height/2);Math.abs(A)>v.width/2&&C.push(Math.abs(A)-v.width/2);Math.abs(D)>v.width/2&&C.push(Math.abs(D)-v.width/2);l=[];s=[];q=[];r=[];C.length&&(x-=Math.max.apply(Math,C)+f.indexLabelFontSize/2+2,40>x&&(x=40));F++}}var w=this,z={frame:0,maxAngle:h[0],count:0};0!==w.renderCount&&(this.animationEnabled= !1);z.isAnimating=60;d();this.pieDoughnutClickHandler=function(a){if(0===z.isAnimating){a=a.dataPointIndex;var d=f.dataPointIds[a];!0===w._eventManager.objectMap[d].currentlyExploded?(!0===w._eventManager.objectMap[d].userSetExploded&&(f.dataPoints[a].exploded=!1),w._eventManager.objectMap[d].currentlyExploded=!1,z.frame=20,z.isAnimating=20,c()):!1===w._eventManager.objectMap[d].currentlyExploded&&(!0===w._eventManager.objectMap[d].userSetExploded&&(f.dataPoints[a].exploded=!0),w._eventManager.objectMap[d].currentlyExploded= !0,z.isAnimating=20,z.frame=0,b())}}}};t.prototype.requestAnimFrame=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a){window.setTimeout(a,1E3/60)};O.prototype.registerSpace=function(a,d){"top"===a?this._topOccupied+=d.height:"bottom"===a?this._bottomOccupied+=d.height:"left"===a?this._leftOccupied+=d.width:"right"===a&&(this._rightOccupied+=d.width)};O.prototype.unRegisterSpace= function(a,d){"top"===a?this._topOccupied-=d.height:"bottom"===a?this._bottomOccupied-=d.height:"left"===a?this._leftOccupied-=d.width:"right"===a&&(this._rightOccupied-=d.width)};O.prototype.getFreeSpace=function(){return{x1:this._leftOccupied,y1:this._topOccupied,x2:this.canvas.width-this._rightOccupied,y2:this.canvas.height-this._bottomOccupied,width:this.canvas.width-this._rightOccupied-this._leftOccupied,height:this.canvas.height-this._bottomOccupied-this._topOccupied}};O.prototype.reset=function(){this._rightOccupied= this._leftOccupied=this._bottomOccupied=this._topOccupied=0};K(D,G);D.prototype.render=function(a){a&&this.ctx.save();var d=this.ctx.font;this.ctx.textBaseline=this.textBaseline;this._isDirty&&this.measureText(this.ctx);this.ctx.translate(this.x,this.y);this.ctx.font=this._getFontString();this.ctx.rotate(Math.PI/180*this.angle);var b=0,c=this.padding,e=null;if(0<this.borderThickness&&this.borderColor||this.backgroundColor)this.ctx.roundRect(0,0,this.width,this.height,this.cornerRadius,this.borderThickness, this.backgroundColor,this.borderColor),"middle"===this.textBaseline&&(c+=this.fontSize/2);this.ctx.fillStyle=this.fontColor;for(var f=0;f<this._wrappedText.lines.length;f++)e=this._wrappedText.lines[f],"right"===this.horizontalAlign?b=this.width-e.width-this.padding:"left"===this.horizontalAlign?b=this.padding:"center"===this.horizontalAlign&&(b=(this.width-2*this.padding)/2-e.width/2+this.padding),this.ctx.fillText(e.text,b,c),c+=e.height;this.ctx.font=d;a&&this.ctx.restore()};D.prototype.setText= function(a){this.text=a;this._isDirty=!0;this._wrappedText=null};D.prototype.measureText=function(){if(null===this.maxWidth)throw"Please set maxWidth and height for TextBlock";this._wrapText(this.ctx);this._isDirty=!1;return{width:this.width,height:this.height}};D.prototype._wrapText=function(){text=new String(N(this.text));var a=[],d=this.ctx.font,b=0,c=0;for(this.ctx.font=this._getFontString();0<text.length;){for(var e=text,f=0,g=0,k=this.maxWidth-2*this.padding,h=this.maxHeight-2*this.padding;;)if(f= this.ctx.measureText(e).width,g=0,f>k)g=e.length/f*k,f=Math.max(Math.min(Math.ceil(g),e.length-1),0),g=e.lastIndexOf(" ",f,e.length-1),e=0<=g?N(text.slice(0,g)):N(text.slice(0,f-1));else{a.push({text:e,width:f,height:this.fontSize});c=Math.max(c,f);b+=this.fontSize;text=N(text.slice(e.length,text.length));break}if(h&&b>h-this.fontSize&&0<text.length){e=a.pop();Math.min(e.text.length,3);a.push(e);break}}this._wrappedText={lines:a,width:c,height:b};this.width=c+2*this.padding;this.height=b+2*this.padding; this.ctx.font=d};D.prototype._getFontString=function(){return this.fontStyle+" "+this.fontWeight+" "+this.fontSize+"px "+this.fontFamily};K(Q,G);Q.prototype.render=function(){if(this.text){var a=this.chart.layoutManager.getFreeSpace(),d=0,b=0,c=0,e=0,f=0,g,k;"top"===this.verticalAlign||"bottom"===this.verticalAlign?(e=a.width-2*this.margin,f=0.5*a.height-2*this.margin,c=0):"center"===this.verticalAlign&&("left"===this.horizontalAlign||"right"===this.horizontalAlign?(e=a.height-2*this.margin,f=0.5* a.width-2*this.margin):"center"===this.horizontalAlign&&(e=a.width-2*this.margin,f=0.5*a.height-2*this.margin));var f=new D(this.ctx,{fontSize:this.fontSize,fontFamily:this.fontFamily,fontColor:this.fontColor,fontStyle:this.fontStyle,fontWeight:this.fontWeight,horizontalAlign:this.horizontalAlign,verticalAlign:this.verticalAlign,borderColor:this.borderColor,borderThickness:this.borderThickness,backgroundColor:this.backgroundColor,maxWidth:e,maxHeight:f,cornerRadius:this.cornerRadius,text:this.text, padding:this.padding,textBaseline:this.borderColor&&0<this.borderThickness?"middle":"top"}),h=f.measureText();"top"===this.verticalAlign||"bottom"===this.verticalAlign?("top"===this.verticalAlign?(b=this.margin,k="top"):"bottom"===this.verticalAlign&&(b=a.y2-this.margin-h.height,k="bottom"),"left"===this.horizontalAlign?d=a.x1+this.margin:"center"===this.horizontalAlign?d=a.x1+(e/2-h.width/2)+this.margin:"right"===this.horizontalAlign&&(d=a.x2-this.margin-h.width),g=this.horizontalAlign,this.width= h.width,this.height=h.height):"center"===this.verticalAlign&&("left"===this.horizontalAlign?(d=a.x1+this.margin,b=a.y2-this.margin-(e/2-h.width/2),c=-90,k="left",this.width=h.height,this.height=h.width):"right"===this.horizontalAlign?(d=a.x2-this.margin,b=a.y1+this.margin+(e/2-h.width/2),c=90,k="right",this.width=h.height,this.height=h.width):"center"===this.horizontalAlign&&(b=a.y1+(a.height/2-h.height/2),d=a.x1+(a.width/2-h.width/2),k="center",this.width=h.width,this.height=h.height),g="center"); f.x=d;f.y=b;f.angle=c;f.horizontalAlign=g;f.render(!0);this.chart.layoutManager.registerSpace(k,{width:this.width+2*this.margin,height:this.height+2*this.margin});this.bounds={x1:d,y1:b,x2:d+this.width,y2:b+this.height};this.ctx.textBaseline="top"}};K(R,G);R.prototype.render=function(){var a=this.chart.layoutManager.getFreeSpace(),d=null,b=0,c=0,e=0,f=0,g=[],k=[];"top"===this.verticalAlign||"bottom"===this.verticalAlign?(this.orientation="horizontal",d=this.verticalAlign,e=0.9*a.width,f=0.5*a.height): "center"===this.verticalAlign&&(this.orientation="vertical",d=this.horizontalAlign,e=0.5*a.width,f=0.9*a.height);for(var h=0;h<this.dataSeries.length;h++){var j=this.dataSeries[h],m=j.legendMarkerType?j.legendMarkerType:("line"===j.type||"scatter"===j.type||"bubble"===j.type)&&j.markerType?j.markerType:J.getDefaultLegendMarker(j.type),n=j.legendText?j.legendText:j.name,p=j.legendMarkerColor?j.legendMarkerColor:j.markerColor?j.markerColor:j._colorSet[0],l=!j.markerSize&&"line"===j.type?0:0.7*this.fontSize; if("pie"!==j.type&&"doughnut"!==j.type)m={markerType:m,markerColor:p,text:n,textBlock:null,chartType:j.type,markerSize:l,lineColor:j._colorSet[0]},g.push(m);else for(var s=0;s<j.dataPoints.length;s++)l=j.dataPoints[s],m=l.legendMarkerType?l.legendMarkerType:j.legendMarkerType?j.legendMarkerType:J.getDefaultLegendMarker(j.type),n=l.legendText?l.legendText:j.legendText?j.legendText:l.name?l.name:"DataPoint: "+(s+1),p=l.markerColor?l.markerColor:j.markerColor?j.markerColor:l.color?l.color:j.color?j.color: j._colorSet[s],l=(0===l.markerSize||0===j.markerSize&&!l.markerSize)&&"line"===j.type?0:0.7*this.fontSize,m={markerType:m,markerColor:p,text:n,textBlock:null,chartType:j.type,markerSize:l},g.push(m)}if(0<g.length){j=null;for(h=s=0;h<g.length;h++){m=g[h];if("horizontal"===this.orientation){if(m.textBlock=new D(this.ctx,{x:0,y:0,maxWidth:e,maxHeight:this.fontSize,angle:0,text:m.text,horizontalAlign:"left",fontSize:this.fontSize,fontFamily:this.fontFamily,fontWeight:this.fontWeight,fontColor:this.fontColor, fontStyle:this.fontStyle,textBaseline:"top"}),m.textBlock.measureText(),!j||j.width+m.textBlock.width+(0===j.width?0:this.horizontalSpacing)>e)j={entries:[],width:0},k.push(j),this.height=k.length*(this.fontSize+5)}else this.height+this.fontSize<f?(j={entries:[],width:0},k.push(j),this.height=k.length*this.fontSize):(j=k[s],s=(s+1)%k.length),m.textBlock=new D(this.ctx,{x:0,y:0,maxWidth:e,maxHeight:this.fontSize,angle:0,text:m.text,horizontalAlign:"left",fontSize:this.fontSize,fontFamily:this.fontFamily, fontWeight:this.fontWeight,fontColor:this.fontColor,fontStyle:this.fontStyle,textBaseline:"top"}),m.textBlock.measureText();m.textBlock.x=j.width+(0===j.width?0:this.horizontalSpacing);m.textBlock.y=0;j.width+=m.textBlock.width+(this.fontSize+5)+(0===j.width?0:this.horizontalSpacing);j.entries.push(m);this.width=Math.max(j.width,this.width)}this.height=k.length*this.fontSize}"top"===this.verticalAlign?(c="left"===this.horizontalAlign?a.x1:"right"===this.horizontalAlign?a.x2-this.width:a.x1+a.width/ 2-this.width/2,b=a.y1):"center"===this.verticalAlign?(c="left"===this.horizontalAlign?a.x1:"right"===this.horizontalAlign?a.x2-this.width:a.x1+a.width/2-this.width/2,b=a.y1+a.height/2-this.height/2):"bottom"===this.verticalAlign&&(c="left"===this.horizontalAlign?a.x1:"right"===this.horizontalAlign?a.x2-this.width:a.x1+a.width/2-this.width/2,b=a.y2-this.height-5);for(h=0;h<k.length;h++){var j=k[h],q;for(q in j.entries)m=j.entries[q],a=m.textBlock.x+c,e=b+h*this.fontSize,"line"===m.chartType&&(this.ctx.strokeStyle= m.lineColor,this.ctx.lineWidth=Math.ceil(this.fontSize/8),this.ctx.beginPath(),this.ctx.moveTo(a-2,e+this.fontSize/2),this.ctx.lineTo(a+2+this.fontSize,e+this.fontSize/2),this.ctx.stroke()),H.drawMarker(a+this.fontSize/2,e+this.fontSize/2,this.ctx,m.markerType,l,m.markerColor,null,0),m.textBlock.x=a+this.fontSize+5,m.textBlock.y=e,m.textBlock.render(!0)}this.chart.layoutManager.registerSpace(d,{width:this.width,height:this.height+5+5});this.bounds={x1:c,y1:b,x2:c+this.width,y2:b+this.height}};K(V, G);V.prototype.render=function(){var a=this.chart.layoutManager.getFreeSpace();this.ctx.fillStyle="red";this.ctx.fillRect(a.x1,a.y1,a.x2,a.y2)};K(J,G);J.prototype.getDefaultAxisPlacement=function(){type=this.type.toLowerCase();if("column"===type||"line"===type||"area"===type||"stackedcolumn"===type||"stackedline"===type||"bubble"===type||"scatter"===type||"stackedarea"===type||"stackedcolumn100"===type||"stackedline100"===type||"stackedarea100"===type)return"normal";if("bar"===type||"stackedbar"=== type||"stackedbar100"===type)return"xySwapped";if("pie"===type||"doughnut"===type)return"none";window.console.log("Unknown Chart Type: "+type);return null};J.getDefaultLegendMarker=function(a){a=a.toLowerCase();if("column"===a||"stackedcolumn"===a||"stackedline"===a||"bar"===a||"stackedbar"===a||"stackedbar100"===a||"bubble"===a||"scatter"===a||"stackedcolumn100"===a||"stackedline100"===a)return"square";if("line"===a||"pie"===a||"doughnut"===a)return"circle";if("area"===a||"stackedarea"===a||"stackedarea100"=== a)return"triangle";window.console.log("Unknown Chart Type: "+a);return null};J.prototype.findDataPointByX=function(a,d){for(var b=0,c=this.dataPoints.length,e,f={dataPoint:null,distance:Infinity,index:NaN},g=0,k=null;b<c;){g++;e=(b+c)/2<<0;var k=this.dataPoints[e],h=Math.abs(k.x-a);h<f.distance&&(f.dataPoint=k,f.distance=h,f.index=e);if(k.x<a)b=e+1;else if(k.x>a)c=e;else{f.dataPoint=k;f.distance=h;f.index=e;break}}return!d&&f.dataPoint.x===a?f:d&&null!==f.dataPoint?f:null};J.prototype.getMarkerProperties= function(a,d,b,c){var e=this.dataPoints,f=e[a].markerColor?e[a].markerColor:this.markerColor?this.markerColor:e[a].color?e[a].color:this.color?this.color:this._colorSet[a%this._colorSet.length];return{x:d,y:b,ctx:c,type:e[a].markerType?e[a].markerType:this.markerType,size:e[a].markerSize?e[a].markerSize:this.markerSize,color:f,borderColor:e[a].markerBorderColor?e[a].markerBorderColor:this.markerBorderColor?this.markerBorderColor:f,borderThickness:e[a].markerBorderThickness?e[a].markerBorderThickness: this.markerBorderThickness?this.markerBorderThickness:1}};K(x,G);x.prototype.createLabels=function(){var a,d=0,b,c;if("axisX"===this.type&&"dateTime"===this.chart.plotInfo.axisXValueType){b=Y(new Date(this.maximum),this.interval,this.intervalType);c=W;for(d=this.intervalStartPosition;d<b;Y(d,this.interval,this.intervalType))a="axisX"===this.type&&this.labels[d]?this.labels[d]:c(d,this.valueFormatString),a=new D(this.ctx,{x:0,y:0,maxWidth:this.maxHeight,maxHeight:this.labelFontSize,angle:this.labelAngle, text:this.prefix+a+this.suffix,horizontalAlign:"left",fontSize:this.labelFontSize,fontFamily:this.labelFontFamily,fontWeight:this.labelFontWeight,fontColor:this.labelFontColor,fontStyle:this.labelFontStyle,textBaseline:"middle"}),this._labels.push({position:d.getTime(),textBlock:a,effectiveHeight:null})}else{b=this.maximum;c=X;if(Math.floor(this.interval)<this.interval&&!this._options.interval){a=Math.ceil(this.interval);for(var e=Math.ceil(this.intervalStartPosition),f=!1,d=e;d<=this.maximum;d+= a)if(this.labels[d])f=!0;else{f=!1;break}f&&(this.interval=a,this.intervalStartPosition=e)}for(d=this.intervalStartPosition;d<=b;d+=this.interval)a="axisX"===this.type&&this.labels[d]?this.labels[d]:c(d,this.valueFormatString),a=new D(this.ctx,{x:0,y:0,maxWidth:this.maxHeight,maxHeight:this.labelFontSize,angle:this.labelAngle,text:this.prefix+a+this.suffix,horizontalAlign:"left",fontSize:this.labelFontSize,fontFamily:this.labelFontFamily,fontWeight:this.labelFontWeight,fontColor:this.labelFontColor, fontStyle:this.labelFontStyle,textBaseline:"middle",borderThickness:0}),this._labels.push({position:d,textBlock:a,effectiveHeight:null})}};x.prototype.createLabelsAndCalculateWidth=function(){var a=0;this._labels=[];if("left"===this._position||"right"===this._position){this.createLabels();for(i=0;i<this._labels.length;i++){textBlock=this._labels[i].textBlock;var d=textBlock.measureText();labelEffectiveWidth=0===this.labelAngle?d.width:d.width*Math.cos(Math.PI/180*Math.abs(this.labelAngle))+d.height/ 2*Math.sin(Math.PI/180*Math.abs(this.labelAngle));a<labelEffectiveWidth&&(a=labelEffectiveWidth);this._labels[i].effectiveWidth=labelEffectiveWidth}}return(this.title?this.titleFontSize+5:0)+a+this.tickLength+10};x.prototype.createLabelsAndCalculateHeight=function(){var a=0;this._labels=[];var d,b=0;this.createLabels();if("bottom"===this._position||"top"===this._position)for(b=0;b<this._labels.length;b++){d=this._labels[b].textBlock;d=d.measureText();var c=0,c=0===this.labelAngle?d.height:d.width* Math.sin(Math.PI/180*Math.abs(this.labelAngle))+d.height/2*Math.cos(Math.PI/180*Math.abs(this.labelAngle));a<c&&(a=c);this._labels[b].effectiveHeight=c}return(this.title?this.titleFontSize+5:0)+a+this.tickLength};x.setLayoutAndRender=function(a,d,b,c,e){var f,g,k,h=a.chart.ctx;a.calculateAxisParameters();d&&d.calculateAxisParameters();b&&b.calculateAxisParameters();if(d&&b&&"undefined"===typeof d._options.maximum&&"undefined"===typeof d._options.minimum&&"undefined"===typeof d._options.interval&& "undefined"===typeof b._options.maximum&&"undefined"===typeof b._options.minimum&&"undefined"===typeof b._options.interval){var j=(d.maximum-d.minimum)/d.interval,m=(b.maximum-b.minimum)/b.interval;j>m?b.maximum=b.interval*j+b.minimum:m>j&&(d.maximum=d.interval*m+d.minimum)}var j=d?d.lineThickness?d.lineThickness:0:0,m=b?b.lineThickness?b.lineThickness:0:0,n=d?d.gridThickness?d.gridThickness:0:0,p=b?b.gridThickness?b.gridThickness:0:0,l=d?d.margin:0;if("normal"===c){var s=d?d.createLabelsAndCalculateWidth(): 0,q=b?b.createLabelsAndCalculateWidth():0,r=a.createLabelsAndCalculateHeight();c=e.x1+s+l+j/2;f=e.y2-r-a.margin;g=e.x2-q>a.chart.canvas.width-10?a.chart.canvas.width-10:e.x2-q;k=e.y2-a.margin;a.lineCoordinates={x1:c,y1:f,x2:g,y2:f,width:Math.abs(g-c)};a.boundingRect={x1:c,y1:f,x2:g,y2:k,width:g-c,height:k-f};d&&(c=e.x1+d.margin,f=10>e.y1?10:e.y1,g=e.x1+s+d.margin,k=e.y2-r-a.margin-a.lineThickness/2,d.lineCoordinates={x1:g,y1:f,x2:g,y2:k,height:Math.abs(k-f)},d.boundingRect={x1:c,y1:f,x2:g,y2:k,width:g- c,height:k-f});b&&(c=a.lineCoordinates.x2,f=10>e.y1?10:e.y1,g=c+q+b.margin,k=e.y2-r-a.margin-a.lineThickness/2,b.lineCoordinates={x1:c,y1:f,x2:c,y2:k,height:Math.abs(k-f)},b.boundingRect={x1:c,y1:f,x2:g,y2:k,width:g-c,height:k-f});h.save();h.rect(a.boundingRect.x1-40,a.boundingRect.y1,a.boundingRect.width+80,a.boundingRect.height);h.clip();a.renderLabelsTicksAndTitle();h.restore();d&&d.renderLabelsTicksAndTitle();b&&b.renderLabelsTicksAndTitle();e=a.chart.getPlotArea();h.save();h.rect(e.x1-Math.max(j+ a.gridThickness)/2,e.y1-Math.max(p,n)/2,Math.abs(e.x2-e.x1+Math.max(j+a.gridThickness)/2+Math.max(m,a.gridThickness)/2),Math.abs(e.y2-e.y1+Math.max(p,n,a.lineThickness)));h.clip();a.calculateValueToPixelConvertionParameters();d&&d.calculateValueToPixelConvertionParameters();b&&b.calculateValueToPixelConvertionParameters();a.renderInterlacedColors();d&&d.renderInterlacedColors();b&&b.renderInterlacedColors();h.restore();a.renderGrid();d&&d.renderGrid();b&&b.renderGrid()}else s=d?d.createLabelsAndCalculateHeight(): 0,q=b?b.createLabelsAndCalculateHeight():0,r=a.createLabelsAndCalculateWidth(),d&&(c=e.x1+r+a.margin+a.lineThickness/2,f=e.y2-s-d.margin,g=e.x2>d.chart.canvas.width-10?d.chart.canvas.width-10:e.x2,k=e.y2-d.margin,d.lineCoordinates={x1:c,y1:f,x2:g,y2:f,width:Math.abs(g-c)},d.boundingRect={x1:c,y1:f,x2:g,y2:k,width:g-c,height:s}),b&&(c=e.x1+r+a.margin+a.lineThickness/2,f=e.y1+b.margin,g=e.x2>b.chart.canvas.width-10?b.chart.canvas.width-10:e.x2,k=e.y1+b.margin+q,b.lineCoordinates={x1:c,y1:k,x2:g,y2:k, width:Math.abs(g-c)},b.boundingRect={x1:c,y1:f,x2:g,y2:k,width:g-c,height:q}),c=e.x1+a.margin,f=10>e.y1+q+m/2?10:e.y1+q+m/2,g=e.x1+r+a.margin,k=e.y2-s-l-j/2,a.lineCoordinates={x1:g,y1:f,x2:g,y2:k,height:Math.abs(k-f)},a.boundingRect={x1:c,y1:f,x2:g,y2:k,width:g-c,height:k-f},h.save(),d&&d.renderLabelsTicksAndTitle(),b&&b.renderLabelsTicksAndTitle(),a.renderLabelsTicksAndTitle(),e=a.chart.getPlotArea(),h.save(),h.rect(e.x1-Math.max(a.lineThickness,n,p),e.y1,Math.abs(e.x2-e.x1+Math.max(a.lineThickness, n,p)+Math.max(n,p)),Math.abs(e.y2-e.y1+(j?j/2:0))),h.clip(),a.calculateValueToPixelConvertionParameters(),d&&d.calculateValueToPixelConvertionParameters(),b&&b.calculateValueToPixelConvertionParameters(),a.renderInterlacedColors(),d&&d.renderInterlacedColors(),b&&b.renderInterlacedColors(),a.renderGrid(),d&&d.renderGrid(),b&&b.renderGrid(),h.restore();a.renderAxisLine();d&&d.renderAxisLine();b&&b.renderAxisLine()};x.prototype.renderLabelsTicksAndTitle=function(){var a=!1,d=0,b=0.9,c=0;0!==this.labelAngle&& 360!==this.labelAngle&&(b=1.2);if("bottom"===this._position||"top"===this._position){for(e=0;e<this._labels.length;e++)f=this._labels[e],f.position<this.minimum||(f=f.textBlock.width*Math.cos(Math.PI/180*this.labelAngle)+f.textBlock.height*Math.sin(Math.PI/180*this.labelAngle),d+=f);d>this.lineCoordinates.width*b&&(a=!0)}if("left"===this._position||"right"===this._position){for(e=0;e<this._labels.length;e++)f=this._labels[e],f.position<this.minimum||(f=f.textBlock.height*Math.cos(Math.PI/180*this.labelAngle)+ f.textBlock.width*Math.sin(Math.PI/180*this.labelAngle),d+=f);d>this.lineCoordinates.height*b&&(a=!0)}if("bottom"===this._position){var e=0;this.ctx.lineWidth=this.tickThickness;this.ctx.strokeStyle=this.tickColor;for(var f,e=0;e<this._labels.length;e++)f=this._labels[e],f.position<this.minimum||f.position>this.maximum||(d=this.getPixelCoordinatesOnAxis(f.position),this.tickThickness&&(this.ctx.beginPath(),this.ctx.moveTo(d.x<<0,d.y<<0),this.ctx.lineTo(d.x<<0,d.y+this.tickLength<<0),this.ctx.stroke()), a&&0!==c++%2||(0===f.textBlock.angle?(d.x-=f.textBlock.width/2,d.y+=this.tickLength+f.textBlock.height/2):(d.x-=0>this.labelAngle?f.textBlock.width*Math.cos(Math.PI/180*this.labelAngle):0,d.y+=this.tickLength+Math.abs(0>this.labelAngle?f.textBlock.width*Math.sin(Math.PI/180*this.labelAngle):0)),f.textBlock.x=d.x,f.textBlock.y=d.y,f.textBlock.render(!0)));this.title&&(this._titleTextBlock=new D(this.ctx,{x:this.lineCoordinates.x1,y:this.boundingRect.y2-this.titleFontSize-5,maxWidth:this.lineCoordinates.width, maxHeight:this.titleFontSize,angle:0,text:this.title,horizontalAlign:"center",fontSize:this.titleFontSize,fontFamily:this.titleFontFamily,fontWeight:this.titleFontWeight,fontColor:this.titleFontColor,fontStyle:this.titleFontStyle,textBaseline:"top"}),this._titleTextBlock.measureText(),this._titleTextBlock.x=this.lineCoordinates.x1+this.lineCoordinates.width/2-this._titleTextBlock.width/2,this._titleTextBlock.render(!0))}else if("top"===this._position){this.ctx.lineWidth=this.tickThickness;this.ctx.strokeStyle= this.tickColor;for(e=0;e<this._labels.length;e++)f=this._labels[e],f.position<this.minimum||f.position>this.maximum||(d=this.getPixelCoordinatesOnAxis(f.position),this.tickThickness&&(this.ctx.beginPath(),this.ctx.moveTo(d.x<<0,d.y<<0),this.ctx.lineTo(d.x<<0,d.y-this.tickLength<<0),this.ctx.stroke()),a&&0!==c++%2||(0===f.textBlock.angle?(d.x-=f.textBlock.width/2,d.y-=this.tickLength+f.textBlock.height/2):(d.x-=0<this.labelAngle?f.textBlock.width*Math.cos(Math.PI/180*this.labelAngle):0,d.y-=this.tickLength+ Math.abs(0<this.labelAngle?f.textBlock.width*Math.sin(Math.PI/180*this.labelAngle)+5:5)),f.textBlock.x=d.x,f.textBlock.y=d.y,f.textBlock.render(!0)));this.title&&(this._titleTextBlock=new D(this.ctx,{x:this.lineCoordinates.x1,y:this.boundingRect.y1,maxWidth:this.lineCoordinates.width,maxHeight:this.titleFontSize,angle:0,text:this.title,horizontalAlign:"center",fontSize:this.titleFontSize,fontFamily:this.titleFontFamily,fontWeight:this.titleFontWeight,fontColor:this.titleFontColor,fontStyle:this.titleFontStyle, textBaseline:"top"}),this._titleTextBlock.measureText(),this._titleTextBlock.x=this.lineCoordinates.x1+this.lineCoordinates.width/2-this._titleTextBlock.width/2,this._titleTextBlock.render(!0))}else if("left"===this._position){this.ctx.lineWidth=this.tickThickness;this.ctx.strokeStyle=this.tickColor;for(e=0;e<this._labels.length;e++)f=this._labels[e],f.position<this.minimum||f.position>this.maximum||(d=this.getPixelCoordinatesOnAxis(f.position),this.tickThickness&&(this.ctx.beginPath(),this.ctx.moveTo(d.x<< 0,d.y<<0),this.ctx.lineTo(d.x-this.tickLength<<0,d.y<<0),this.ctx.stroke()),a&&0!==c++%2||(f.textBlock.x=d.x-f.textBlock.width*Math.cos(Math.PI/180*this.labelAngle)-this.tickLength-5,f.textBlock.y=d.y-f.textBlock.width*Math.sin(Math.PI/180*this.labelAngle),f.textBlock.render(!0)));this.title&&(this._titleTextBlock=new D(this.ctx,{x:this.boundingRect.x1+5,y:this.lineCoordinates.y2,maxWidth:this.lineCoordinates.height,maxHeight:this.titleFontSize,angle:-90,text:this.title,horizontalAlign:"center",fontSize:this.titleFontSize, fontFamily:this.titleFontFamily,fontWeight:this.titleFontWeight,fontColor:this.titleFontColor,fontStyle:this.titleFontStyle,textBaseline:"top"}),this._titleTextBlock.measureText(),this._titleTextBlock.y=this.lineCoordinates.height/2+this._titleTextBlock.width/2+this.lineCoordinates.y1,this._titleTextBlock.render(!0))}else if("right"===this._position){this.ctx.lineWidth=this.tickThickness;this.ctx.strokeStyle=this.tickColor;for(e=0;e<this._labels.length;e++)f=this._labels[e],f.position<this.minimum|| f.position>this.maximum||(d=this.getPixelCoordinatesOnAxis(f.position),this.tickThickness&&(this.ctx.beginPath(),this.ctx.moveTo(d.x<<0,d.y<<0),this.ctx.lineTo(d.x+this.tickLength<<0,d.y<<0),this.ctx.stroke()),a&&0!==c++%2||(f.textBlock.x=d.x+this.tickLength+5,f.textBlock.y=d.y,f.textBlock.render(!0)));this.title&&(this._titleTextBlock=new D(this.ctx,{x:this.boundingRect.x2-5,y:this.lineCoordinates.y2,maxWidth:this.lineCoordinates.height,maxHeight:this.titleFontSize,angle:90,text:this.title,horizontalAlign:"center", fontSize:this.titleFontSize,fontFamily:this.titleFontFamily,fontWeight:this.titleFontWeight,fontColor:this.titleFontColor,fontStyle:this.titleFontStyle,textBaseline:"top"}),this._titleTextBlock.measureText(),this._titleTextBlock.y=this.lineCoordinates.height/2-this._titleTextBlock.width/2+this.lineCoordinates.y1,this._titleTextBlock.render(!0))}};x.prototype.renderInterlacedColors=function(){var a,d,b=this.chart.getPlotArea();if(("bottom"===this._position||"top"===this._position)&&this.interlacedColor){var c= 0;this.ctx.fillStyle=this.interlacedColor;for(c=0;c<this._labels.length;c+=2)a=this.getPixelCoordinatesOnAxis(this._labels[c].position),d=c+1>=this._labels.length?this.getPixelCoordinatesOnAxis(this.maximum):this.getPixelCoordinatesOnAxis(this._labels[c+1].position),this.ctx.fillRect(a.x,b.y1,Math.abs(d.x-a.x),Math.abs(b.y1-b.y2))}else if(("left"===this._position||"right"===this._position)&&this.interlacedColor){this.ctx.fillStyle=this.interlacedColor;for(c=0;c<this._labels.length;c+=2)d=this.getPixelCoordinatesOnAxis(this._labels[c].position), a=c+1>=this._labels.length?this.getPixelCoordinatesOnAxis(this.maximum):this.getPixelCoordinatesOnAxis(this._labels[c+1].position),this.ctx.fillRect(b.x1,a.y,Math.abs(b.x1-b.x2),Math.abs(a.y-d.y))}};x.prototype.renderGrid=function(){var a,d=this.chart.getPlotArea();if("bottom"===this._position||"top"===this._position){if(this.gridThickness&&0<this.gridThickness){this.ctx.lineWidth=this.gridThickness;this.ctx.strokeStyle=this.gridColor;this.ctx.beginPath();for(b=0;b<this._labels.length;b++)this._labels[b].position< this.minimum||this._labels[b].position>this.maximum||(a=this.getPixelCoordinatesOnAxis(this._labels[b].position),this.ctx.moveTo(a.x<<0,d.y1<<0),this.ctx.lineTo(a.x<<0,d.y2<<0),this.ctx.stroke())}}else if(("left"===this._position||"right"===this._position)&&this.gridThickness&&0<this.gridThickness){this.ctx.lineWidth=this.gridThickness;this.ctx.strokeStyle=this.gridColor;this.ctx.beginPath();for(var b=0;b<this._labels.length;b++)this._labels[b].position<this.minimum||this._labels[b].position>this.maximum|| (a=this.getPixelCoordinatesOnAxis(this._labels[b].position),this.ctx.moveTo(d.x1<<0,a.y<<0),this.ctx.lineTo(d.x2<<0,a.y<<0),this.ctx.stroke())}};x.prototype.renderAxisLine=function(){if("bottom"===this._position||"top"===this._position)this.lineThickness&&(this.ctx.lineWidth=this.lineThickness,this.ctx.strokeStyle=this.lineColor?this.lineColor:"black",this.ctx.beginPath(),this.ctx.moveTo(this.lineCoordinates.x1,this.lineCoordinates.y1),this.ctx.lineTo(this.lineCoordinates.x2,this.lineCoordinates.y2), this.ctx.stroke());else if(("left"===this._position||"right"===this._position)&&this.lineThickness)this.ctx.lineWidth=this.lineThickness,this.ctx.strokeStyle=this.lineColor,this.ctx.beginPath(),this.ctx.moveTo(this.lineCoordinates.x1,this.lineCoordinates.y1),this.ctx.lineTo(this.lineCoordinates.x2,this.lineCoordinates.y2),this.ctx.stroke()};x.prototype.getPixelCoordinatesOnAxis=function(a){var d={},b=this.lineCoordinates.width,c=this.lineCoordinates.height;if("bottom"===this._position||"top"===this._position)b/= Math.abs(this.maximum-this.minimum),d.x=this.lineCoordinates.x1+b*(a-this.minimum),d.y=this.lineCoordinates.y1;if("left"===this._position||"right"===this._position)b=c/Math.abs(this.maximum-this.minimum),d.y=this.lineCoordinates.y2-b*(a-this.minimum),d.x=this.lineCoordinates.x2;return d};x.prototype.calculateValueToPixelConvertionParameters=function(){var a={pixelPerUnit:null,minimum:null,reference:null},d=this.lineCoordinates.width,b=this.lineCoordinates.height;a.minimum=this.minimum;if("bottom"=== this._position||"top"===this._position)a.pixelPerUnit=d/Math.abs(this.maximum-this.minimum),a.reference=this.lineCoordinates.x1;if("left"===this._position||"right"===this._position)a.pixelPerUnit=-1*b/Math.abs(this.maximum-this.minimum),a.reference=this.lineCoordinates.y2;this.convertionParameters=a};x.prototype.calculateAxisParameters=function(){var a=this.chart.layoutManager.getFreeSpace();"bottom"===this._position||"top"===this._position?(this.maxWidth=a.width,this.maxHeight=a.height):(this.maxWidth= a.height,this.maxHeight=a.width);var a="axisX"===this.type?500>this.maxWidth?8:Math.max(6,Math.floor(this.maxWidth/62)):Math.floor(this.maxWidth/40),d,b,c,e;"axisX"===this.type?(d=null!==this.sessionVariables.internalMinimum?this.sessionVariables.internalMinimum:this.dataInfo.viewPortMin,b=null!==this.sessionVariables.internalMaximum?this.sessionVariables.internalMaximum:this.dataInfo.viewPortMax,0===b-d&&(b+=1),c=Infinity!==this.dataInfo.minDiff?this.dataInfo.minDiff:1):"axisY"===this.type&&(d="undefined"=== typeof this._options.minimum?this.dataInfo.viewPortMin:this._options.minimum,b="undefined"===typeof this._options.maximum?this.dataInfo.viewPortMax:this._options.maximum,0===b-d?(b+=5,d-=5):(0!==b&&(b+=Math.abs(0.05)),0!==d&&(d-=Math.abs(0.05))),this.includeZero&&"undefined"===typeof this._options.minimum&&0<d&&(d=0),this.includeZero&&"undefined"===typeof this._options.maximum&&0>b&&(b=0));"axisX"===this.type&&"dateTime"===this.chart.plotInfo.axisXValueType?(e=b-d,this.intervalType||(e/1<=a?(this.interval= 1,this.intervalType="millisecond"):e/2<=a?(this.interval=2,this.intervalType="millisecond"):e/5<=a?(this.interval=5,this.intervalType="millisecond"):e/10<=a?(this.interval=10,this.intervalType="millisecond"):e/20<=a?(this.interval=20,this.intervalType="millisecond"):e/50<=a?(this.interval=50,this.intervalType="millisecond"):e/100<=a?(this.interval=100,this.intervalType="millisecond"):e/200<=a?(this.interval=200,this.intervalType="millisecond"):e/250<=a?(this.interval=250,this.intervalType="millisecond"): e/300<=a?(this.interval=300,this.intervalType="millisecond"):e/400<=a?(this.interval=400,this.intervalType="millisecond"):e/500<=a?(this.interval=500,this.intervalType="millisecond"):e/(1*y.secondDuration)<=a?(this.interval=1,this.intervalType="second"):e/(2*y.secondDuration)<=a?(this.interval=2,this.intervalType="second"):e/(5*y.secondDuration)<=a?(this.interval=5,this.intervalType="second"):e/(10*y.secondDuration)<=a?(this.interval=10,this.intervalType="second"):e/(15*y.secondDuration)<=a?(this.interval= 15,this.intervalType="second"):e/(20*y.secondDuration)<=a?(this.interval=20,this.intervalType="second"):e/(30*y.secondDuration)<=a?(this.interval=30,this.intervalType="second"):e/(1*y.minuteDuration)<=a?(this.interval=1,this.intervalType="minute"):e/(2*y.minuteDuration)<=a?(this.interval=2,this.intervalType="minute"):e/(5*y.minuteDuration)<=a?(this.interval=5,this.intervalType="minute"):e/(10*y.minuteDuration)<=a?(this.interval=10,this.intervalType="minute"):e/(15*y.minuteDuration)<=a?(this.interval= 15,this.intervalType="minute"):e/(20*y.minuteDuration)<=a?(this.interval=20,this.intervalType="minute"):e/(30*y.minuteDuration)<=a?(this.interval=30,this.intervalType="minute"):e/(1*y.hourDuration)<=a?(this.interval=1,this.intervalType="hour"):e/(2*y.hourDuration)<=a?(this.interval=2,this.intervalType="hour"):e/(3*y.hourDuration)<=a?(this.interval=3,this.intervalType="hour"):e/(6*y.hourDuration)<=a?(this.interval=6,this.intervalType="hour"):e/(1*y.dayDuration)<=a?(this.interval=1,this.intervalType= "day"):e/(2*y.dayDuration)<=a?(this.interval=2,this.intervalType="day"):e/(4*y.dayDuration)<=a?(this.interval=4,this.intervalType="day"):e/(1*y.weekDuration)<=a?(this.interval=1,this.intervalType="week"):e/(2*y.weekDuration)<=a?(this.interval=2,this.intervalType="week"):e/(3*y.weekDuration)<=a?(this.interval=3,this.intervalType="week"):e/(1*y.monthDuration)<=a?(this.interval=1,this.intervalType="month"):e/(2*y.monthDuration)<=a?(this.interval=2,this.intervalType="month"):e/(3*y.monthDuration)<=a? (this.interval=3,this.intervalType="month"):e/(6*y.monthDuration)<=a?(this.interval=6,this.intervalType="month"):(this.interval=e/(1*y.yearDuration)<=a?1:e/(2*y.yearDuration)<=a?2:e/(4*y.yearDuration)<=a?4:Math.floor(x.getNiceNumber(e/(a-1),!0)/y.yearDuration),this.intervalType="year")),this.minimum=null!==this.sessionVariables.internalMinimum?this.sessionVariables.internalMinimum:d-c/2,this.maximum=this.sessionVariables.internalMaximum?this.sessionVariables.internalMaximum:b+c/2,this.valueFormatString|| ("year"===this.intervalType?this.valueFormatString="YYYY":"month"===this.intervalType?this.valueFormatString="MMM YYYY":"week"===this.intervalType?this.valueFormatString="MMM DD YYYY":"day"===this.intervalType?this.valueFormatString="MMM DD YYYY":"hour"===this.intervalType?this.valueFormatString="hh:mm TT":"minute"===this.intervalType?this.valueFormatString="hh:mm TT":"second"===this.intervalType?this.valueFormatString="hh:mm:ss TT":"millisecond"===this.intervalType&&(this.valueFormatString="f'ms'")), this.intervalStartPosition=this.getLabelStartPoint(new Date(this.minimum),this.intervalType,this.interval)):(this.intervalType="number",e=x.getNiceNumber(b-d,!1),this.interval=this._options&&this._options.interval?this._options.interval:x.getNiceNumber(e/(a-1),!0),this.minimum=null!==this.sessionVariables.internalMinimum?this.sessionVariables.internalMinimum:Math.floor(d/this.interval)*this.interval,this.maximum=null!==this.sessionVariables.internalMaximum?this.sessionVariables.internalMaximum:Math.ceil(b/ this.interval)*this.interval,"axisX"===this.type?(null===this.sessionVariables.internalMinimum&&(this.minimum=d-c/2),this.sessionVariables.internalMaximum||(this.maximum=b+c/2),this.intervalStartPosition=Math.floor((this.minimum+this.interval)/this.interval)*this.interval):"axisY"===this.type&&(this.intervalStartPosition=this.minimum));"axisX"===this.type&&(this._absoluteMinimum=this._options&&"undefined"!==typeof this._options.minimum?this._options.minimum:this.dataInfo.min-c/2,this._absoluteMaximum= this._options&&"undefined"!==typeof this._options.maximum?this._options.maximum:this.dataInfo.max+c/2);if(!this.valueFormatString&&(this.valueFormatString="#,##0.##",e=Math.abs(this.maximum-this.minimum),1>e&&(d=Math.floor(Math.abs(Math.log(e)/Math.LN10))+2,2<d)))for(b=0;b<d-2;b++)this.valueFormatString+="#"};x.prototype._getFontString=function(){return this.labelFontStyle+" "+this.labelFontWeight+" "+this.labelFontSize+"px "+this.labelFontFamily};x.getNiceNumber=function(a,d){var b=Math.floor(Math.log(a)/ Math.LN10),c=a/Math.pow(10,b);return(d?1.5>c?1:3>c?2:7>c?5:10:1>=c?1:2>=c?2:5>=c?5:10)*Math.pow(10,b)};x.prototype.getLabelStartPoint=function(){var a=M(this.interval,this.intervalType),a=new Date(Math.floor(this.minimum/a)*a);if("millisecond"!==this.intervalType)if("second"===this.intervalType)0<a.getMilliseconds()&&(a.setSeconds(a.getSeconds()+1),a.setMilliseconds(0));else if("minute"===this.intervalType){if(0<a.getSeconds()||0<a.getMilliseconds())a.setMinutes(a.getMinutes()+1),a.setSeconds(0), a.setMilliseconds(0)}else if("hour"===this.intervalType){if(0<a.getMinutes()||0<a.getSeconds()||0<a.getMilliseconds())a.setHours(a.getHours()+1),a.setMinutes(0),a.setSeconds(0),a.setMilliseconds(0)}else if("day"===this.intervalType){if(0<a.getHours()||0<a.getMinutes()||0<a.getSeconds()||0<a.getMilliseconds())a.setDate(a.getDate()+1),a.setHours(0),a.setMinutes(0),a.setSeconds(0),a.setMilliseconds(0)}else if("week"===this.intervalType){if(0<a.getDay()||0<a.getHours()||0<a.getMinutes()||0<a.getSeconds()|| 0<a.getMilliseconds())a.setDate(a.getDate()+(7-a.getDay())),a.setHours(0),a.setMinutes(0),a.setSeconds(0),a.setMilliseconds(0)}else if("month"===this.intervalType){if(1<a.getDate()||0<a.getHours()||0<a.getMinutes()||0<a.getSeconds()||0<a.getMilliseconds())a.setMonth(a.getMonth()+1),a.setDate(1),a.setHours(0),a.setMinutes(0),a.setSeconds(0),a.setMilliseconds(0)}else if("year"===this.intervalType&&(0<a.getMonth()||1<a.getDate()||0<a.getHours()||0<a.getMinutes()||0<a.getSeconds()||0<a.getMilliseconds()))a.setFullYear(a.getFullYear()+ 1),a.setMonth(0),a.setDate(1),a.setHours(0),a.setMinutes(0),a.setSeconds(0),a.setMilliseconds(0);return a};K(I,G);I.prototype._initialize=function(){if(this.enabled){this.container=document.createElement("div");this.container.style.height="auto";this.container.style.position="absolute";this.container.style.boxShadow="1px 1px 2px 2px rgba(0,0,0,0.1)";this.container.style.zIndex="1000";this.container.style.pointerEvents="none";this.container.style.display="none";var a;a='<div style=" width: auto;height: auto;min-width: 50px;'; a+="line-height: 20px;";a+="padding: 5px;";a+="font-family: 'Muli', sans-serif;";a+="font-weight: 400;";a+="font-style: italic;";a+="font-size: 14px;";a+="color: #000000;";a+="text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.1);";a+="text-align: left;";a+="border: 2px solid gray;";a+="background: rgba(255,255,255,.9);";a+="text-indent: 0px;";a+="white-space: nowrap;";a+="border-radius: 10px;";a+='} "> Sample Tooltip</div>';this.container.innerHTML=a;this.contentDiv=this.container.firstChild;this.container.style.borderRadius= this.contentDiv.style.borderRadius;this.chart._canvasJSContainer.appendChild(this.container)}};I.prototype.mouseMoveHandler=function(a,d){var b=this;clearTimeout(this._timerId);this._timerId=setTimeout(function(){b._updateToolTip(a,d)},5)};I.prototype._updateToolTip=function(a,d){var b=null,c=null,e=[],f=0;if(this.shared){f="xySwapped"===this.chart.plotInfo.axisPlacement?(this.chart.axisX.maximum-this.chart.axisX.minimum)/this.chart.axisX.lineCoordinates.height*(this.chart.axisX.lineCoordinates.y2- d)+this.chart.axisX.minimum:(this.chart.axisX.maximum-this.chart.axisX.minimum)/this.chart.axisX.lineCoordinates.width*(a-this.chart.axisX.lineCoordinates.x1)+this.chart.axisX.minimum;b=[];for(c=0;c<this.chart.data.length;c++)if(g={},(g=this.chart.data[c].findDataPointByX(f,!0))&&0<=g.index)g.dataSeries=this.chart.data[c],b.push(g);if(0===b.length)return;b.sort(function(a,b){return a.distance-b.distance});f=b[0];for(c=0;c<b.length;c++)b[c].dataPoint.x.valueOf()===f.dataPoint.x.valueOf()&&e.push(b[c]); b=null}else{g=this.chart._eventManager.ghostCtx.getImageData(a,d,2,2).data;b=!0;for(c=0;4>c;c++)if(g[c]!==g[c+4]|g[c]!==g[c+8]|g[c]!==g[c+12]){b=!1;break}g=b?g[0]<<16|g[1]<<8|g[2]:0;if(0<g&&"undefined"!==typeof this.chart._eventManager.objectMap[g]){eventObject=this.chart._eventManager.objectMap[g];if(this.currentSeriesIndex===eventObject.dataSeriesIndex&&this.currentDataPointIndex===eventObject.dataPointIndex)return;this.currentSeriesIndex=eventObject.dataSeriesIndex;this.currentDataPointIndex=0<= eventObject.dataPointIndex?eventObject.dataPointIndex:-1}else this.currentDataPointIndex=-1;if(0<=this.currentSeriesIndex){var c=this.chart.data[this.currentSeriesIndex],g={};if(0<=this.currentDataPointIndex)b=c.dataPoints[this.currentDataPointIndex],g.dataSeries=c,g.dataPoint=b,g.index=this.currentDataPointIndex,g.distance=Math.abs(b.x-f);else if("line"===c.type||"area"===c.type||"stackedArea"===c.type||"stackedArea100"===c.type)f=(this.chart.axisX.maximum-this.chart.axisX.minimum)/this.chart.axisX.lineCoordinates.width* (a-this.chart.axisX.lineCoordinates.x1)+this.chart.axisX.minimum.valueOf(),g=c.findDataPointByX(f,!0),g.dataSeries=c,this.currentDataPointIndex=g.index,b=g.dataPoint;else return;e.push(g)}}0<e.length&&(this.highlightObjects(e),f="",f=this.content&&"function"===typeof this.content?this.content({entries:e}):this.getToolTipInnerHTML({entries:e}),this.contentDiv.innerHTML=f,this.contentDiv.innerHTML=f,f=!1,"none"===this.container.style.display&&(f=!0,this.container.style.display="block"),this.contentDiv.style.borderColor= this.borderColor?this.borderColor:e[0].dataPoint.color?e[0].dataPoint.color:e[0].dataSeries.color?e[0].dataSeries.color:e[0].dataSeries._colorSet[e[0].index%e[0].dataSeries._colorSet.length],toolTipLeft="pie"===e[0].dataSeries.type||"doughnut"===e[0].dataSeries.type||"bar"===e[0].dataSeries.type||"stackedBar"===e[0].dataSeries.type||"stackedBar100"===e[0].dataSeries.type?a-10-this.container.clientWidth:this.chart.axisX.lineCoordinates.width/Math.abs(this.chart.axisX.maximum-this.chart.axisX.minimum)* Math.abs(e[0].dataPoint.x-this.chart.axisX.minimum)+this.chart.axisX.lineCoordinates.x1+0.5-this.container.clientWidth<<0,toolTipLeft=0<toolTipLeft?toolTipLeft+"px":toolTipLeft+this.container.clientWidth+20+"px",e=1===e.length&&!this.shared&&("line"===e[0].dataSeries.type||"area"===e[0].dataSeries.type||"stackedArea"===e[0].dataSeries.type||"stackedArea100"===e[0].dataSeries.type)?e[0].dataSeries.axisY.lineCoordinates.y2-e[0].dataSeries.axisY.lineCoordinates.height/Math.abs(e[0].dataSeries.axisY.maximum- e[0].dataSeries.axisY.minimum)*Math.abs(e[0].dataPoint.y-e[0].dataSeries.axisY.minimum)+0.5<<0:"bar"===e[0].dataSeries.type||"stackedBar"===e[0].dataSeries.type||"stackedBar100"===e[0].dataSeries.type?e[0].dataSeries.axisX.lineCoordinates.y2-e[0].dataSeries.axisX.lineCoordinates.height/Math.abs(e[0].dataSeries.axisX.maximum-e[0].dataSeries.axisX.minimum)*Math.abs(e[0].dataPoint.x-e[0].dataSeries.axisX.minimum)+0.5<<0:d,e=-e+10,0<e+this.container.clientHeight+5&&(e-=e+this.container.clientHeight+5- 0),this.container.style.left=toolTipLeft,this.container.style.bottom=e+"px",!this.animationEnabled||f?this.disableAnimation():this.enableAnimation())};I.prototype.highlightObjects=function(a){var d=this.chart.overlaidCanvasCtx;this.chart.resetOverlayedCanvas();var b=this.chart.getPlotArea();d.beginPath();d.rect(b.x1,b.y1,b.width,b.height);d.clip();for(b=0;b<a.length;b++){var c=a[b];if((c=this.chart._eventManager.objectMap[c.dataSeries.dataPointIds[c.index]])&&c.objectType&&"dataPoint"===c.objectType){var e= this.chart.data[c.dataSeriesIndex],f=c.dataPointIndex;if("line"===e.type||"scatter"===e.type||"area"===e.type||"stackedArea"===e.type||"stackedArea100"===e.type)e=e.getMarkerProperties(f,c.x1,c.y1,this.chart.overlaidCanvasCtx),e.size=Math.max(1.5*e.size<<0,10),H.drawMarkers([e]);else if("bubble"===e.type)e=e.getMarkerProperties(f,c.x1,c.y1,this.chart.overlaidCanvasCtx),e.size=c.size,e.color="white",e.borderColor="white",d.globalAlpha=0.3,H.drawMarkers([e]),d.globalAlpha=1;else if("column"===e.type|| "stackedColumn"===e.type||"stackedColumn100"===e.type||"bar"===e.type||"stackedBar"===e.type||"stackedBar100"===e.type)d.globalAlpha=0.3,C(d,c.x1,c.y1,c.x2,c.y2,"white",!1,!1,!1,!1),d.globalAlpha=1;else if("pie"===e.type||"doughnut"===e.type)d.globalAlpha=0.3,L(d,c.center,c.radius,"white",e.type,c.startAngle,c.endAngle),d.globalAlpha=1}}d.globalAlpha=1;d.restore()};I.prototype.getToolTipInnerHTML=function(a){a=a.entries;var d="",b=null,c=null,e=0,f="";if(1<a.length){for(var g=!0,k=0;k<a.length;k++)if(a[k].dataSeries.toolTipContent|| a[k].dataPoint.toolTipContent){g=!1;break}for(k=0;k<a.length;k++){b=a[k].dataSeries;c=a[k].dataPoint;e=a[k].index;f="";0===k&&g&&(f+="undefined"!==typeof this.chart.axisX.labels[c.x]?this.chart.axisX.labels[c.x]:"{x}",f+="</br>");if("line"===b.type||"area"===b.type||"column"===b.type||"bar"===b.type||"scatter"===b.type||"stackedColumn"===b.type||"stackedColumn100"===b.type||"stackedBar"===b.type||"stackedBar100"===b.type||"stackedArea"===b.type||"stackedArea100"===b.type)f+=c.toolTipContent?c.toolTipContent: b.toolTipContent?b.toolTipContent:this.content?f:"<span style='\"'color:{color};'\"'>{name}:</span>&nbsp;&nbsp;{y}";else if("bubble"===b.type)f+=c.toolTipContent?c.toolTipContent:b.toolTipContent?b.toolTipContent:this.content?f:"<span style='\"'color:{color};'\"'>{name}:</span>&nbsp;&nbsp;{y}, &nbsp;&nbsp;{z}";else if("pie"===b.type||"doughnut"===b.type)f+=c.toolTipContent?c.toolTipContent:b.toolTipContent?b.toolTipContent:this.content?f:"&nbsp;&nbsp;{y}";d+=this.chart.replaceKeywordsWithValue(f, c,b,e);k<a.length-1&&(d+="</br>")}}else{b=a[0].dataSeries;c=a[0].dataPoint;e=a[0].index;if("line"===b.type||"area"===b.type||"column"===b.type||"bar"===b.type||"scatter"===b.type||"stackedColumn"===b.type||"stackedColumn100"===b.type||"stackedBar"===b.type||"stackedBar100"===b.type||"stackedArea"===b.type||"stackedArea100"===b.type)f=c.toolTipContent?c.toolTipContent:b.toolTipContent?b.toolTipContent:this.content?f:"<span style='\"'color:{color};'\"'>"+(c.label?"{label}":"{x}")+" :</span>&nbsp;&nbsp;{y}"; else if("bubble"===b.type)f=c.toolTipContent?c.toolTipContent:b.toolTipContent?b.toolTipContent:this.content?f:"<span style='\"'color:{color};'\"'>"+(c.label?"{label}":"{x}")+":</span>&nbsp;&nbsp;{y}, &nbsp;&nbsp;{z}";else if("pie"===b.type||"doughnut"===b.type)f=c.toolTipContent?c.toolTipContent:b.toolTipContent?b.toolTipContent:this.content?f:(c.name?"{name}:&nbsp;&nbsp;":c.label?"{label}:&nbsp;&nbsp;":"")+"{y}";d+=this.chart.replaceKeywordsWithValue(f,c,b,e)}return d};I.prototype.enableAnimation= function(){this.container.style.WebkitTransition||(this.container.style.WebkitTransition="left .2s ease-out, bottom .2s ease-out",this.container.style.MozTransition="left .2s ease-out, bottom .2s ease-out",this.container.style.MsTransition="left .2s ease-out, bottom .2s ease-out",this.container.style.transition="left .2s ease-out, bottom .2s ease-out")};I.prototype.disableAnimation=function(){this.container.style.WebkitTransition&&(this.container.style.WebkitTransition="",this.container.style.MozTransition= "",this.container.style.MsTransition="",this.container.style.transition="")};I.prototype.hide=function(){this.container.style.display="none";this.currentSeriesIndex=-1;this.chart.resetOverlayedCanvas()};t.prototype.replaceKeywordsWithValue=function(a,d,b,c){var e=this;return a.replace(/\{\s*[a-zA-Z]+\s*\}|"[^"]*"|'[^']*'/g,function(a){if('"'===a[0]&&'"'===a[a.length-1]||"'"===a[0]&&"'"===a[a.length-1])return a.slice(1,a.length-1);a=N(a.slice(1,a.length-1));var g=null;if("color"===a)return d.color? d.color:b.color?b.color:b._colorSet[c%b._colorSet.length];if(d.hasOwnProperty(a))g=d;else if(b.hasOwnProperty(a))g=b;else return"";return"x"===a?e.axisX&&"dateTime"===e.plotInfo.axisXValueType?W(g[a],d.xValueFormatString?d.xValueFormatString:b.xValueFormatString?b.xValueFormatString:e.axisX.valueFormatString?e.axisX.valueFormatString:"DD MM YY"):X(g[a],d.xValueFormatString?d.xValueFormatString:b.xValueFormatString?b.xValueFormatString:"#,##0.##"):"y"===a?X(g[a],d.xValueFormatString?d.xValueFormatString: b.xValueFormatString?b.xValueFormatString:"#,###.##"):g[a]})};P.prototype.reset=function(){this.lastObjectId=0;this.objectMap=[];this.rectangularRegionEventSubscriptions=[];this.previousDataPointEventObject=null;this.ghostCtx.clearRect(0,0,this.ghostCanvas.width,this.ghostCanvas.height);this.ghostCtx.beginPath()};P.prototype.getNewObjectTrackingId=function(){return++this.lastObjectId};P.prototype.mouseEventHandler=function(a){if(!("mousemove"!==a.type&&"click"!==a.type)){var d=null,b=null,c=null, e=-1,f=!1,g=!1,k=ca(a),b=this.ghostCtx.getImageData(k.x,k.y,1,1).data;if(240<b[3])if(b=b[0]<<16|b[1]<<8|b[2],"undefined"!==typeof this.objectMap[b]&&"dataPoint"===this.objectMap[b].objectType){d=this.objectMap[b];b=this.chart.data[d.dataSeriesIndex];c=b.dataPoints[d.dataPointIndex];e=d.dataPointIndex;if(null===this.previousDataPointEventObject||this.previousDataPointEventObject.dataSeriesIndex!==d.dataSeriesIndex||this.previousDataPointEventObject.dataPointIndex!==d.dataPointIndex)if(this.previousDataPointEventObject&& (f=!0),c.mouseover&&c.mouseover.call(c,{x:k.x,y:k.y,dataPoint:c,dataSeries:b,dataPointIndex:e}),b.mouseover&&(null===this.previousDataPointEventObject||this.previousDataPointEventObject.dataSeriesIndex!==d.dataSeriesIndex))b.mouseover&&b.mouseover.call(b,{x:k.x,y:k.y,dataPoint:c,dataSeries:b,dataPointIndex:e}),this.previousDataPointEventObject&&(g=!0);"mousemove"===a.type?(c.mousemove&&c.mousemove.call(c,{x:k.x,y:k.y,dataPoint:c,dataSeries:b,dataPointIndex:e}),b.mousemove&&b.mousemove.call(b,{x:k.x, y:k.y,dataPoint:c,dataSeries:b,dataPointIndex:e})):"click"===a.type&&(c.click&&c.click.call(c,{x:k.x,y:k.y,dataPoint:c,dataSeries:b,dataPointIndex:e}),b.click&&b.click.call(b,{x:k.x,y:k.y,dataPoint:c,dataSeries:b,dataPointIndex:e}),this.chart.pieDoughnutClickHandler&&this.chart.pieDoughnutClickHandler.call(b,{x:k.x,y:k.y,dataPoint:c,dataSeries:b,dataPointIndex:e}))}else this.previousDataPointEventObject&&(g=f=!0);else this.previousDataPointEventObject&&(g=f=!0);if(f||g)a=this.chart.data[this.previousDataPointEventObject.dataSeriesIndex], b=a.dataPoints[this.previousDataPointEventObject.dataPointIndex],c=this.previousDataPointEventObject.dataPointIndex,f&&b.mouseout&&b.mouseout.call(b,{x:k.x,y:k.y,dataPoint:b,dataSeries:a,dataPointIndex:c}),g&&a.mouseout&&a.mouseout.call(a,{x:k.x,y:k.y,dataPoint:b,dataSeries:a,dataPointIndex:c});this.previousDataPointEventObject=d}};var H={drawMarker:function(a,d,b,c,e,f,g,k){if(b){var h=1;b.fillStyle=f?f:"#000000";b.strokeStyle=g?g:"#000000";b.lineWidth=k?k:0;"circle"===c?(b.beginPath(),b.arc(a,d, e/2,0,360,!1),f&&b.fill(),k&&(g?b.stroke():(h=b.globalAlpha,b.globalAlpha=0.15,b.strokeStyle="black",b.stroke(),b.globalAlpha=h))):"square"===c?(b.beginPath(),b.rect(a-e/2,d-e/2,e,e),f&&b.fill(),k&&(g?b.stroke():(h=b.globalAlpha,b.globalAlpha=0.15,b.strokeStyle="black",b.stroke(),b.globalAlpha=h))):"triangle"===c?(b.beginPath(),b.moveTo(a-e/2,d+e/2),b.lineTo(a+e/2,d+e/2),b.lineTo(a,d-e/2),b.closePath(),f&&b.fill(),k&&(g?b.stroke():(h=b.globalAlpha,b.globalAlpha=0.15,b.strokeStyle="black",b.stroke(), b.globalAlpha=h))):"cross"===c&&(b.strokeStyle=f,b.lineWidth=e/4,b.beginPath(),b.moveTo(a-e/2,d-e/2),b.lineTo(a+e/2,d+e/2),b.stroke(),b.moveTo(a+e/2,d-e/2),b.lineTo(a-e/2,d+e/2),b.stroke())}},drawMarkers:function(a){for(var d=0;d<a.length;d++){var b=a[d];H.drawMarker(b.x,b.y,b.ctx,b.type,b.size,b.color,b.borderColor,b.borderThickness)}}},da={Chart:function(a,d){var b=new t(a,d,this);this.render=function(){b.render()};this.options=b._options},addColorSet:function(a,d){S[a]=d}};da.Chart.version="1.0.0 Beta 3"; window.CanvasJS=da})();
import React from 'react'; import { mount } from 'enzyme'; import { MonthlyCashFlowRow } from '../../../forms/cashflow'; describe('<MonthlyCashFlowRow>', () => { it('renders', () => { const props = { inputProps: {}, baseValue: 0, updateClientValue: jest.fn(), rowProps: {}, }; expect(() => { mount(<MonthlyCashFlowRow { ...props } />); }).not.toThrow(); }); });
// flow-typed signature: 9a683c921265d5e24f5022039bd63cb7 // flow-typed version: <<STUB>>/neutrino_v^8.3.0/flow_v0.76.0 /** * This is an autogenerated libdef stub for: * * 'neutrino' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'neutrino' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'neutrino/bin/base' { declare module.exports: any; } declare module 'neutrino/bin/build' { declare module.exports: any; } declare module 'neutrino/bin/execute' { declare module.exports: any; } declare module 'neutrino/bin/inspect' { declare module.exports: any; } declare module 'neutrino/bin/neutrino' { declare module.exports: any; } declare module 'neutrino/bin/start' { declare module.exports: any; } declare module 'neutrino/bin/test' { declare module.exports: any; } declare module 'neutrino/src/api' { declare module.exports: any; } declare module 'neutrino/src/build' { declare module.exports: any; } declare module 'neutrino/src/devServer' { declare module.exports: any; } declare module 'neutrino/src/index' { declare module.exports: any; } declare module 'neutrino/src/inspect' { declare module.exports: any; } declare module 'neutrino/src/start' { declare module.exports: any; } declare module 'neutrino/src/test' { declare module.exports: any; } declare module 'neutrino/src/utils' { declare module.exports: any; } declare module 'neutrino/src/watch' { declare module.exports: any; } declare module 'neutrino/src/webpack' { declare module.exports: any; } // Filename aliases declare module 'neutrino/bin/base.js' { declare module.exports: $Exports<'neutrino/bin/base'>; } declare module 'neutrino/bin/build.js' { declare module.exports: $Exports<'neutrino/bin/build'>; } declare module 'neutrino/bin/execute.js' { declare module.exports: $Exports<'neutrino/bin/execute'>; } declare module 'neutrino/bin/inspect.js' { declare module.exports: $Exports<'neutrino/bin/inspect'>; } declare module 'neutrino/bin/neutrino.js' { declare module.exports: $Exports<'neutrino/bin/neutrino'>; } declare module 'neutrino/bin/start.js' { declare module.exports: $Exports<'neutrino/bin/start'>; } declare module 'neutrino/bin/test.js' { declare module.exports: $Exports<'neutrino/bin/test'>; } declare module 'neutrino/src/api.js' { declare module.exports: $Exports<'neutrino/src/api'>; } declare module 'neutrino/src/build.js' { declare module.exports: $Exports<'neutrino/src/build'>; } declare module 'neutrino/src/devServer.js' { declare module.exports: $Exports<'neutrino/src/devServer'>; } declare module 'neutrino/src/index.js' { declare module.exports: $Exports<'neutrino/src/index'>; } declare module 'neutrino/src/inspect.js' { declare module.exports: $Exports<'neutrino/src/inspect'>; } declare module 'neutrino/src/start.js' { declare module.exports: $Exports<'neutrino/src/start'>; } declare module 'neutrino/src/test.js' { declare module.exports: $Exports<'neutrino/src/test'>; } declare module 'neutrino/src/utils.js' { declare module.exports: $Exports<'neutrino/src/utils'>; } declare module 'neutrino/src/watch.js' { declare module.exports: $Exports<'neutrino/src/watch'>; } declare module 'neutrino/src/webpack.js' { declare module.exports: $Exports<'neutrino/src/webpack'>; }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon([/*#__PURE__*/_jsx("path", { d: "M4 19h14V5H4v14zm8-12h4v3h-4V7zm0 4h4v6h-4v-6zM6 7h5v5H6V7zm0 6h5v4H6v-4z", opacity: ".3" }, "0"), /*#__PURE__*/_jsx("path", { d: "M6 13h5v4H6zm0-6h5v5H6zm6 0h4v3h-4zm0 4h4v6h-4zm10-2V7h-2V5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-2h2v-2h-2v-2h2v-2h-2V9h2zm-4 10H4V5h14v14z" }, "1")], 'DeveloperBoardTwoTone');
import string from './string'; export default string;
;(function() { var Game = function() { var screen = document.getElementById("screen").getContext('2d'); this.size = { x: screen.canvas.width, y: screen.canvas.height }; this.bodies = createInvaders(this).concat(new Player(this)); this.shootSound = document.getElementById('shoot-sound'); var self = this; var tick = function() { self.update(); self.draw(screen); requestAnimationFrame(tick); }; tick(); }; Game.prototype = { update: function() { reportCollisions(this.bodies); for (var i = 0; i < this.bodies.length; i++) { if (this.bodies[i].update !== undefined) { this.bodies[i].update(); } } }, draw: function(screen) { screen.clearRect(0, 0, this.size.x, this.size.y); for (var i = 0; i < this.bodies.length; i++) { if (this.bodies[i].draw !== undefined) { this.bodies[i].draw(screen); } } }, invadersBelow: function(invader) { return this.bodies.filter(function(b) { return b instanceof Invader && Math.abs(invader.center.x - b.center.x) < b.size.x && b.center.y > invader.center.y; }).length > 0; }, addBody: function(body) { this.bodies.push(body); }, removeBody: function(body) { var bodyIndex = this.bodies.indexOf(body); if (bodyIndex !== -1) { this.bodies.splice(bodyIndex, 1); } } }; var Invader = function(game, center) { this.game = game; this.center = center; this.size = { x: 15, y: 15 }; this.patrolX = 0; this.speedX = 0.3; }; Invader.prototype = { update: function() { if (this.patrolX < 0 || this.patrolX > 30) { this.speedX = -this.speedX; } if (Math.random() > 0.995 && !this.game.invadersBelow(this)) { var bullet = new Bullet(this.game, { x: this.center.x, y: this.center.y + this.size.y / 2 }, { x: Math.random() - 0.5, y: 2 }); this.game.addBody(bullet); } this.center.x += this.speedX; this.patrolX += this.speedX; }, draw: function(screen) { drawRect(screen, this); }, collision: function() { this.game.removeBody(this); } }; var createInvaders = function(game) { var invaders = []; for (var i = 0; i < 24; i++) { var x = 35 + (i % 8) * 30; var y = 35 + (i % 3) * 30; invaders.push(new Invader(game, { x: x, y: y})); } return invaders; }; var Player = function(game) { this.game = game; this.size = { x: 15, y: 15 }; this.center = { x: this.game.size.x / 2, y: this.game.size.y - 35 }; this.keyboarder = new Keyboarder(); }; Player.prototype = { update: function() { if (this.keyboarder.isDown(this.keyboarder.KEYS.LEFT)) { this.center.x -= 2; } else if (this.keyboarder.isDown(this.keyboarder.KEYS.RIGHT)) { this.center.x += 2; } if (this.keyboarder.isDown(this.keyboarder.KEYS.SPACE)) { var bullet = new Bullet(this.game, { x: this.center.x, y: this.center.y - this.size.y - 10 }, { x: 0, y: -7 }); this.game.addBody(bullet); this.game.shootSound.load(); this.game.shootSound.play(); } }, draw: function(screen) { drawRect(screen, this); }, collision: function() { this.game.removeBody(this); } }; var Bullet = function(game, center, velocity) { this.game = game; this.center = center; this.size = { x: 3, y: 3 }; this.velocity = velocity; }; Bullet.prototype = { update: function() { this.center.x += this.velocity.x; this.center.y += this.velocity.y; var screenRect = { center: { x: this.game.size.x / 2, y: this.game.size.y / 2 }, size: this.game.size }; if (!isColliding(this, screenRect)) { this.game.removeBody(this); } }, draw: function(screen) { drawRect(screen, this); }, collision: function() { this.game.removeBody(this); } }; var Keyboarder = function() { var keyState = {}; window.addEventListener('keydown', function(e) { keyState[e.keyCode] = true; }); window.addEventListener('keyup', function(e) { keyState[e.keyCode] = false; }); this.isDown = function(keyCode) { return keyState[keyCode] === true; }; this.KEYS = { LEFT: 37, RIGHT: 39, SPACE: 32 }; }; var drawRect = function(screen, body) { screen.fillRect(body.center.x - body.size.x / 2, body.center.y - body.size.y / 2, body.size.x, body.size.y); }; var isColliding = function(b1, b2) { return !( b1 === b2 || b1.center.x + b1.size.x / 2 <= b2.center.x - b2.size.x / 2 || b1.center.y + b1.size.y / 2 <= b2.center.y - b2.size.y / 2 || b1.center.x - b1.size.x / 2 >= b2.center.x + b2.size.x / 2 || b1.center.y - b1.size.y / 2 >= b2.center.y + b2.size.y / 2 ); }; var reportCollisions = function(bodies) { var bodyPairs = []; for (var i = 0; i < bodies.length; i++) { for (var j = i + 1; j < bodies.length; j++) { if (isColliding(bodies[i], bodies[j])) { bodyPairs.push([bodies[i], bodies[j]]); } } } for (var i = 0; i < bodyPairs.length; i++) { if (bodyPairs[i][0].collision !== undefined) { bodyPairs[i][0].collision(bodyPairs[i][1]); } if (bodyPairs[i][1].collision !== undefined) { bodyPairs[i][1].collision(bodyPairs[i][0]); } } }; window.addEventListener('load', function() { new Game(); }); })();
'use strict' const argCommand = require('../cmd-helpers').argCommand module.exports = (send) => { return { wantlist (cb) { return send('bitswap/wantlist', {}, null, null, cb) }, stat (cb) { return send('bitswap/stat', {}, null, null, cb) }, unwant: argCommand(send, 'bitswap/unwant') } }
/** * @private */ Ext.define('Ext.ux.grid.plugin.grouping.DragZone', { extend: 'Ext.dd.DragZone', groupColumnSelector: '.' + Ext.baseCSSPrefix + 'group-column', groupColumnInnerSelector: '.' + Ext.baseCSSPrefix + 'group-column-inner', maxProxyWidth: 120, dragging: false, constructor: function(panel) { this.panel = panel; this.ddGroup = this.getDDGroup(); this.callParent([panel.el]); }, getDDGroup: function() { // return the column header dd group so we can allow column droping inside the grouping panel return 'header-dd-zone-' + this.panel.up('gridpanel').id; }, getDragData: function(e) { if (e.getTarget(this.groupColumnInnerSelector)) { var header = e.getTarget(this.groupColumnSelector), headerCmp, headerCol, ddel; if (header) { headerCmp = Ext.getCmp(header.id); headerCol = Ext.getCmp(headerCmp.idColumn); if (!this.panel.dragging) { ddel = document.createElement('div'); ddel.innerHTML = headerCmp.text; return { ddel: ddel, header: headerCol, groupcol: headerCmp }; } } } return false; }, onBeforeDrag: function() { return !(this.panel.dragging || this.disabled); }, onInitDrag: function() { this.panel.dragging = true; this.callParent(arguments); }, onDragDrop: function() { if(!this.dragData.dropLocation){ this.panel.dragging = false; this.callParent(arguments); return; } /* when a column is dragged out from the grouping panel we have to do the following: 1. remove the column from grouping panel 2. adjust the grid groupers */ var dropCol = this.dragData.dropLocation.header, dragCol = this.dragData.header, pos = -1; if(dropCol instanceof Ext.grid.column.Column){ dropCol.show(); pos = this.panel.items.findIndex('idColumn', dragCol.id); this.panel.remove(this.panel.items.getAt(pos)); this.panel.notifyGroupChange(); } this.panel.dragging = false; this.callParent(arguments); }, afterRepair: function() { this.callParent(); this.panel.dragging = false; }, getRepairXY: function() { return this.dragData.header.el.getXY(); }, disable: function() { this.disabled = true; }, enable: function() { this.disabled = false; } });
/** * lodash 4.0.6 (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 */ var keysIn = require('lodash.keysin'), rest = require('lodash.rest'); /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** `Object#toString` result references. */ var funcTag = '[object Function]', genTag = '[object GeneratorFunction]'; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** * 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) { value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1; length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } /** 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/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) { object[key] = value; } } /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * This function is like `copyObject` except that it accepts a function to * customize copied values. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObjectWith(source, props, object, customizer) { object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : source[key]; assignValue(object, key, newValue); } return object; } /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return rest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = typeof customizer == 'function' ? (length--, customizer) : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a * [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) that affects * Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq(object[index], value); } return false; } /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'user': 'fred' }; * var other = { 'user': 'fred' }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } /** * 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(getLength(value)) && !isFunction(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 correctly classified, * 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 which returns 'object' for typed array and weak map constructors, // and PhantomJS 1.9 which returns 'function' for `NodeList` instances. var tag = isObject(value) ? objectToString.call(value) : ''; return tag == funcTag || tag == genTag; } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/6.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](https://es5.github.io/#x8) 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'); } /** * This method is like `_.assignIn` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined` assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extendWith * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignInWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { copyObjectWith(source, keysIn(source), object, customizer); }); module.exports = assignInWith;
import s from 'underscore.string'; import { BaseRaw } from './BaseRaw'; export class LivechatVisitorsRaw extends BaseRaw { getVisitorsBetweenDate({ start, end, department }) { const query = { _updatedAt: { $gte: new Date(start), $lt: new Date(end), }, ...department && department !== 'undefined' && { department }, }; return this.find(query, { fields: { _id: 1 } }); } findByNameRegexWithExceptionsAndConditions(searchTerm, exceptions = [], conditions = {}, options = {}) { if (!Array.isArray(exceptions)) { exceptions = [exceptions]; } const nameRegex = new RegExp(`^${ s.escapeRegExp(searchTerm).trim() }`, 'i'); const match = { $match: { name: nameRegex, _id: { $nin: exceptions, }, ...conditions, }, }; const { fields, sort, offset, count } = options; const project = { $project: { custom_name: { $concat: ['$username', ' - ', '$name'] }, ...fields, }, }; const order = { $sort: sort || { name: 1 } }; const params = [match, project, order]; if (offset) { params.push({ $skip: offset }); } if (count) { params.push({ $limit: count }); } return this.col.aggregate(params); } /** * Find visitors by their email or phone or username or name * @return [{object}] List of Visitors from db */ findVisitorsByEmailOrPhoneOrNameOrUsername(_emailOrPhoneOrNameOrUsername, options) { const query = { $or: [{ 'visitorEmails.address': new RegExp(`^${ s.escapeRegExp(_emailOrPhoneOrNameOrUsername) }$`, 'i'), }, { 'phone.phoneNumber': _emailOrPhoneOrNameOrUsername, }, { name: new RegExp(`^${ s.escapeRegExp(_emailOrPhoneOrNameOrUsername).trim() }`, 'i'), }, { username: _emailOrPhoneOrNameOrUsername, }], }; return this.find(query, options); } }
import dateRangeArray from "date-range-array"; const a: Array<string> = dateRangeArray("2017-06-01", "2017-06-03"); //=> ['2017-06-01', '2017-06-02', '2017-06-03'] // $FlowExpectedError const c: Array<string> = dateRangeArray("2017-06-01"); const d: Array<string> = dateRangeArray("2017-06-01", "2017-06-03");
var HelloComponent = React.createClass( { render: function() { var el = ( <div> Hello <ChildrenComponent/> </div> ); return el; } }); var ChildrenComponent = React.createClass( { render: function() { var createChild = function(n) { return (<ChildComponent input={n}/>); }; var elArray = [0,1,2,3,4,5,6,7,8,9].map(createChild); var el = (<div>{elArray}</div>); return el; } }); var ChildComponent = React.createClass( { render: function() { var el = (<div>child{this.props.input}</div>); return el; } }); var mount = React.render(<HelloComponent/>, document.body);
/** * @module og/entity/BaseBillboard */ 'use strict'; import * as utils from '../utils/shared.js'; import { Vec3 } from '../math/Vec3.js'; /** * Base prototype for billboard and label classes. * @class * @param {Object} [options] - Options: * @param {og.Vec3|Array.<number>} [options.position] - Billboard spatial position. * @param {number} [options.rotation] - Screen angle rotaion. * @param {og.Vec4|string|Array.<number>} [options.color] - Billboard color. * @param {og.Vec3|Array.<number>} [options.alignedAxis] - Billboard aligned vector. * @param {og.Vec3|Array.<number>} [options.offset] - Billboard center screen offset. * @param {boolean} [options.visibility] - Visibility. */ class BaseBillboard { constructor(options) { options = options || {}; /** * Object unic identifier. * @public * @readonly * @type {number} */ this.id = BaseBillboard._staticCounter++; /** * Billboard center cartesian position. * @protected * @type {og.Vec3} */ this._position = utils.createVector3(options.position); this._positionHigh = new Vec3(); this._positionLow = new Vec3(); Vec3.doubleToTwoFloats(this._position, this._positionHigh, this._positionLow); /** * Screen space rotation angle. * @protected * @type {number} */ this._rotation = options.rotation || 0; /** * RGBA color. * @protected * @type {og.Vec4} */ this._color = utils.createColorRGBA(options.color); /** * Cartesian aligned axis vector. * @protected * @type {og.Vec3} */ this._alignedAxis = utils.createVector3(options.alignedAxis); /** * Billboard center screen space offset. Where x,y - screen space offset and z - depth offset. * @protected * @type {og.math.Vecto3} */ this._offset = utils.createVector3(options.offset); /** * Billboard visibility. * @protected * @type {boolean} */ this._visibility = options.visibility != undefined ? options.visibility : true; /** * Entity instance that holds this billboard. * @protected * @type {og.Entity} */ this._entity = null; /** * Handler that stores and renders this billboard object. * @protected * @type {og.BillboardHandler} */ this._handler = null; /** * Billboard handler array index. * @protected * @type {number} */ this._handlerIndex = -1; } static get _staticCounter() { if (!this._counter && this._counter !== 0) { this._counter = 0; } return this._counter; } static set _staticCounter(n) { this._counter = n; } /** * Sets billboard position. * @public * @param {number} x - X coordinate. * @param {number} y - Y coordinate. * @param {number} z - Z coordinate. */ setPosition(x, y, z) { this._position.x = x; this._position.y = y; this._position.z = z; Vec3.doubleToTwoFloats(position, this._positionHigh, this._positionLow); this._handler && this._handler.setPositionArr(this._handlerIndex, this._positionHigh, this._positionLow); } /** * Sets billboard position. * @public * @param {og.Vec3} position - Cartesian coordinates. */ setPosition3v(position) { this._position.x = position.x; this._position.y = position.y; this._position.z = position.z; Vec3.doubleToTwoFloats(position, this._positionHigh, this._positionLow); this._handler && this._handler.setPositionArr(this._handlerIndex, this._positionHigh, this._positionLow); } /** * Returns billboard position. * @public * @returns {og.Vec3} */ getPosition() { return this._position; } /** * Sets screen space offset. * @public * @param {number} x - X offset. * @param {number} y - Y offset. * @param {number} [z] - Z offset. */ setOffset(x, y, z) { this._offset.x = x; this._offset.y = y; (z != undefined) && (this._offset.z = z); this._handler && this._handler.setOffsetArr(this._handlerIndex, this._offset); } /** * Sets screen space offset. * @public * @param {og.Vec2} offset - Offset size. */ setOffset3v(offset) { this._offset.x = offset.x; this._offset.y = offset.y; (offset.z != undefined) && (this._offset.z = offset.z); this._handler && this._handler.setOffsetArr(this._handlerIndex, offset); } /** * Returns billboard screen space offset size. * @public * @returns {og.Vec3} */ getOffset() { return this._offset; } /** * Sets billboard screen space rotation in radians. * @public * @param {number} rotation - Screen space rotation in radians. */ setRotation(rotation) { this._rotation = rotation; this._handler && this._handler.setRotationArr(this._handlerIndex, rotation); } /** * Gets screen space rotation. * @public * @returns {number} */ getRotation() { return this._rotation; } /** * Sets billboard opacity. * @public * @param {number} a - Billboard opacity. */ setOpacity(a) { this._color.w = a; this.setColor(this._color.x, this._color.y, this._color.z, a); } /** * Sets RGBA color. Each channel from 0.0 to 1.0. * @public * @param {number} r - Red. * @param {number} g - Green. * @param {number} b - Blue. * @param {number} a - Alpha. */ setColor(r, g, b, a) { this._color.x = r; this._color.y = g; this._color.z = b; (a != undefined) && (this._color.w = a); this._handler && this._handler.setRgbaArr(this._handlerIndex, this._color); } /** * Sets RGBA color. Each channel from 0.0 to 1.0. * @public * @param {og.Vec4} color - RGBA vector. */ setColor4v(color) { this._color.x = color.x; this._color.y = color.y; this._color.z = color.z; (color.w != undefined) && (this._color.w = color.w); this._handler && this._handler.setRgbaArr(this._handlerIndex, color); } /** * Sets billboard color. * @public * @param {string} color - HTML style color. */ setColorHTML(color) { this.setColor4v(utils.htmlColorToRgba(color)); } /** * Returns RGBA color. * @public * @returns {og.Vec4} */ getColor() { return this._color; } /** * Sets billboard visibility. * @public * @param {boolean} visibility - Visibility flag. */ setVisibility(visibility) { this._visibility = visibility; this._handler && this._handler.setVisibility(this._handlerIndex, visibility); } /** * Returns billboard visibility. * @public * @returns {boolean} */ getVisibility() { return this._visibility; } /** * Sets billboard cartesian aligned vector. * @public * @param {number} x - Aligned vector X coordinate. * @param {number} y - Aligned vector Y coordinate. * @param {number} z - Aligned vector Z coordinate. */ setAlignedAxis(x, y, z) { this._alignedAxis.x = x; this._alignedAxis.y = y; this._alignedAxis.z = z; this._handler && this._handler.setAlignedAxisArr(this._handlerIndex, this._alignedAxis); } /** * Sets billboard aligned vector. * @public * @param {og.math.Vecto3} alignedAxis - Vector to align. */ setAlignedAxis3v(alignedAxis) { this._alignedAxis.x = alignedAxis.x; this._alignedAxis.y = alignedAxis.y; this._alignedAxis.z = alignedAxis.z; this._handler && this._handler.setAlignedAxisArr(this._handlerIndex, alignedAxis); } /** * Returns aligned vector. * @public * @returns {og.Vec3} */ getAlignedAxis() { return this._alignedAxis; } /** * Removes billboard from hander. * @public */ remove() { this._entity = null; this._handler && this._handler.remove(this); } /** * Sets billboard picking color. * @public * @param {og.Vec3} color - Picking color. */ setPickingColor3v(color) { this._handler && this._handler.setPickingColorArr(this._handlerIndex, color); } }; export { BaseBillboard };
System.register(['../validation/validation-group-builder', '../validation/validation-result', '../validation/validation-locale'], function (_export) { 'use strict'; var ValidationGroupBuilder, ValidationResult, ValidationLocale, ValidationGroup; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } return { setters: [function (_validationValidationGroupBuilder) { ValidationGroupBuilder = _validationValidationGroupBuilder.ValidationGroupBuilder; }, function (_validationValidationResult) { ValidationResult = _validationValidationResult.ValidationResult; }, function (_validationValidationLocale) { ValidationLocale = _validationValidationLocale.ValidationLocale; }], execute: function () { ValidationGroup = (function () { function ValidationGroup(subject, observerLocator, config) { var _this = this; _classCallCheck(this, ValidationGroup); this.result = new ValidationResult(); this.subject = subject; this.validationProperties = []; this.config = config; this.builder = new ValidationGroupBuilder(observerLocator, this); this.onValidateCallbacks = []; this.onPropertyValidationCallbacks = []; this.isValidating = false; this.onDestroy = config.onLocaleChanged(function () { _this.validate(false, true); }); if (this.subject.__proto__._validationMetadata) { this.subject.__proto__._validationMetadata.setup(this); } } ValidationGroup.prototype.destroy = function destroy() { for (var i = this.validationProperties.length - 1; i >= 0; i--) { this.validationProperties[i].destroy(); } this.onDestroy(); }; ValidationGroup.prototype.clear = function clear() { this.validationProperties.forEach(function (prop) { prop.clear(); }); this.result.clear(); }; ValidationGroup.prototype.onBreezeEntity = function onBreezeEntity() { var _this2 = this; var breezeEntity = this.subject; var me = this; this.onPropertyValidate(function (propertyBindingPath) { _this2.passes(function () { breezeEntity.entityAspect.validateProperty(propertyBindingPath); var errors = breezeEntity.entityAspect.getValidationErrors(propertyBindingPath); if (errors.length === 0) return true;else return errors[0].errorMessage; }); }); this.onValidate(function () { breezeEntity.entityAspect.validateEntity(); return {}; }); breezeEntity.entityAspect.validationErrorsChanged.subscribe(function () { breezeEntity.entityAspect.getValidationErrors().forEach(function (validationError) { var propertyName = validationError.propertyName; if (!me.result.properties[propertyName]) { me.ensure(propertyName); } var currentResultProp = me.result.addProperty(propertyName); if (currentResultProp.isValid) { currentResultProp.setValidity({ isValid: false, message: validationError.errorMessage, failingRule: 'breeze', latestValue: currentResultProp.latestValue }, true); } }); }); }; ValidationGroup.prototype.validate = function validate() { var _this3 = this; var forceDirty = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0]; var forceExecution = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1]; this.isValidating = true; var promise = Promise.resolve(true); var _loop = function (i) { var validatorProperty = _this3.validationProperties[i]; promise = promise.then(function () { return validatorProperty.validateCurrentValue(forceDirty, forceExecution); }); }; for (var i = this.validationProperties.length - 1; i >= 0; i--) { _loop(i); } promise = promise['catch'](function () { console.log("Should never get here: a validation property should always resolve to true/false!"); throw Error("Should never get here: a validation property should always resolve to true/false!"); }); this.onValidateCallbacks.forEach(function (onValidateCallback) { promise = promise.then(function () { return _this3.config.locale(); }).then(function (locale) { return Promise.resolve(onValidateCallback.validationFunction()).then(function (callbackResult) { for (var prop in callbackResult) { if (!_this3.result.properties[prop]) { _this3.ensure(prop); } var resultProp = _this3.result.addProperty(prop); var result = callbackResult[prop]; var newPropResult = { latestValue: resultProp.latestValue }; if (result === true || result === null || result === '') { if (!resultProp.isValid && resultProp.failingRule === 'onValidateCallback') { newPropResult.failingRule = null; newPropResult.message = ''; newPropResult.isValid = true; resultProp.setValidity(newPropResult, true); } } else { if (resultProp.isValid) { newPropResult.failingRule = 'onValidateCallback'; newPropResult.isValid = false; if (typeof result === 'string') { newPropResult.message = result; } else { newPropResult.message = locale.translate(newPropResult.failingRule); } resultProp.setValidity(newPropResult, true); } } } _this3.result.checkValidity(); }, function (a, b, c, d, e) { _this3.result.isValid = false; if (onValidateCallback.validationFunctionFailedCallback) { onValidateCallback.validationFunctionFailedCallback(a, b, c, d, e); } }); }); }); promise = promise.then(function () { _this3.isValidating = false; if (_this3.result.isValid) { return Promise.resolve(_this3.result); } else { return Promise.reject(_this3.result); } }); return promise; }; ValidationGroup.prototype.onValidate = function onValidate(validationFunction, validationFunctionFailedCallback) { this.onValidateCallbacks.push({ validationFunction: validationFunction, validationFunctionFailedCallback: validationFunctionFailedCallback }); return this; }; ValidationGroup.prototype.onPropertyValidate = function onPropertyValidate(validationFunction) { this.onPropertyValidationCallbacks.push(validationFunction); return this; }; ValidationGroup.prototype.ensure = function ensure(bindingPath, configCallback) { this.builder.ensure(bindingPath, configCallback); this.onPropertyValidationCallbacks.forEach(function (callback) { callback(bindingPath); }); return this; }; ValidationGroup.prototype.isNotEmpty = function isNotEmpty() { return this.builder.isNotEmpty(); }; ValidationGroup.prototype.canBeEmpty = function canBeEmpty() { return this.builder.canBeEmpty(); }; ValidationGroup.prototype.isGreaterThanOrEqualTo = function isGreaterThanOrEqualTo(minimumValue) { return this.builder.isGreaterThanOrEqualTo(minimumValue); }; ValidationGroup.prototype.isGreaterThan = function isGreaterThan(minimumValue) { return this.builder.isGreaterThan(minimumValue); }; ValidationGroup.prototype.isBetween = function isBetween(minimumValue, maximumValue) { return this.builder.isBetween(minimumValue, maximumValue); }; ValidationGroup.prototype.isLessThanOrEqualTo = function isLessThanOrEqualTo(maximumValue) { return this.builder.isLessThanOrEqualTo(maximumValue); }; ValidationGroup.prototype.isLessThan = function isLessThan(maximumValue) { return this.builder.isLessThan(maximumValue); }; ValidationGroup.prototype.isEqualTo = function isEqualTo(otherValue, otherValueLabel) { return this.builder.isEqualTo(otherValue, otherValueLabel); }; ValidationGroup.prototype.isNotEqualTo = function isNotEqualTo(otherValue, otherValueLabel) { return this.builder.isNotEqualTo(otherValue, otherValueLabel); }; ValidationGroup.prototype.isEmail = function isEmail() { return this.builder.isEmail(); }; ValidationGroup.prototype.isURL = function isURL() { return this.builder.isURL(); }; ValidationGroup.prototype.isIn = function isIn(collection) { return this.builder.isIn(collection); }; ValidationGroup.prototype.hasMinLength = function hasMinLength(minimumValue) { return this.builder.hasMinLength(minimumValue); }; ValidationGroup.prototype.hasMaxLength = function hasMaxLength(maximumValue) { return this.builder.hasMaxLength(maximumValue); }; ValidationGroup.prototype.hasLengthBetween = function hasLengthBetween(minimumValue, maximumValue) { return this.builder.hasLengthBetween(minimumValue, maximumValue); }; ValidationGroup.prototype.isNumber = function isNumber() { return this.builder.isNumber(); }; ValidationGroup.prototype.containsNoSpaces = function containsNoSpaces() { return this.builder.containsNoSpaces(); }; ValidationGroup.prototype.containsOnlyDigits = function containsOnlyDigits() { return this.builder.containsOnlyDigits(); }; ValidationGroup.prototype.containsOnly = function containsOnly(regex) { return this.builder.containsOnly(regex); }; ValidationGroup.prototype.containsOnlyAlpha = function containsOnlyAlpha() { return this.builder.containsOnlyAlpha(); }; ValidationGroup.prototype.containsOnlyAlphaOrWhitespace = function containsOnlyAlphaOrWhitespace() { return this.builder.containsOnlyAlphaOrWhitespace(); }; ValidationGroup.prototype.containsOnlyLetters = function containsOnlyLetters() { return this.builder.containsOnlyAlpha(); }; ValidationGroup.prototype.containsOnlyLettersOrWhitespace = function containsOnlyLettersOrWhitespace() { return this.builder.containsOnlyAlphaOrWhitespace(); }; ValidationGroup.prototype.containsOnlyAlphanumerics = function containsOnlyAlphanumerics() { return this.builder.containsOnlyAlphanumerics(); }; ValidationGroup.prototype.containsOnlyAlphanumericsOrWhitespace = function containsOnlyAlphanumericsOrWhitespace() { return this.builder.containsOnlyAlphanumericsOrWhitespace(); }; ValidationGroup.prototype.isStrongPassword = function isStrongPassword(minimumComplexityLevel) { return this.builder.isStrongPassword(minimumComplexityLevel); }; ValidationGroup.prototype.matches = function matches(regex) { return this.builder.matches(regex); }; ValidationGroup.prototype.passes = function passes(customFunction, threshold) { return this.builder.passes(customFunction, threshold); }; ValidationGroup.prototype.passesRule = function passesRule(validationRule) { return this.builder.passesRule(validationRule); }; ValidationGroup.prototype['if'] = function _if(conditionExpression, threshold) { return this.builder['if'](conditionExpression, threshold); }; ValidationGroup.prototype['else'] = function _else() { return this.builder['else'](); }; ValidationGroup.prototype.endIf = function endIf() { return this.builder.endIf(); }; ValidationGroup.prototype['switch'] = function _switch(conditionExpression) { return this.builder['switch'](conditionExpression); }; ValidationGroup.prototype['case'] = function _case(caseLabel) { return this.builder['case'](caseLabel); }; ValidationGroup.prototype['default'] = function _default() { return this.builder['default'](); }; ValidationGroup.prototype.endSwitch = function endSwitch() { return this.builder.endSwitch(); }; ValidationGroup.prototype.withMessage = function withMessage(message) { return this.builder.withMessage(message); }; return ValidationGroup; })(); _export('ValidationGroup', ValidationGroup); } }; });
'use strict'; var assert = require('assert'); var should = require('should'); var application = require('..'); var app; describe('.getCollection', function () { describe('when a collection name is specified.', function () { beforeEach(function () { app = new application.App(); }); it('should get the specified collection:', function (cb) { app.page('foo', 'this is foo...'); app.page('bar', 'this is bar...'); app.page('baz', 'this is baz...'); var pages = app.getCollection('pages'); pages.should.have.properties(['foo', 'bar', 'baz']); cb(); }); }); describe('when a task is running.', function () { beforeEach(function () { app = new application.App(); }); it.only('should get files from the specified task collection', function (cb) { app.task('test_one', function () { var stream = app.src('test/fixtures/templates/partials/*.hbs'); stream.on('end', function () { var collection = app.getCollection(); // assert(Object.keys(collection).length === 3); // assert(Object.keys(app.files).length === 3); // collection.should.have.properties(['a', 'b', 'c']); // app.files.should.have.properties(['a', 'b', 'c']); // app.files.should.equal(collection); }); return stream; }); app.task('default', ['test_one'], function () { cb(); }); app.run('default'); }); it('should get files from another task:', function (cb) { app.task('test_one', function () { var stream = app.src('test/fixtures/templates/partials/*.hbs'); stream.on('end', function () { var collection = app.getCollection(); assert(Object.keys(collection).length === 3); assert(Object.keys(app.files).length === 3); collection.should.have.properties(['a', 'b', 'c']); app.files.should.have.properties(['a', 'b', 'c']); app.files.should.equal(collection); }); return stream; }); app.task('test_two', function () { var stream = app.src('test/fixtures/templates/partials/*.hbs'); stream.on('end', function () { var collection = app.getCollection(); assert(Object.keys(collection).length === 3); assert(Object.keys(app.files).length === 3); collection.should.have.properties(['a', 'b', 'c']); app.files.should.have.properties(['a', 'b', 'c']); app.files.should.equal(collection); }); return stream; }); app.task('default', ['test_one', 'test_two'], function () { cb(); }); app.run('default'); }); }); });
/** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import renderer from 'react-test-renderer'; import App from '../src/App'; it('generates a snapshot with correctly transformed dependencies', () => { const tree = renderer.create(<App />).toJSON(); expect(tree).toMatchSnapshot(); });
/** The public interface of the builder which interprets and converts the SKIP keyword This is the main entrance of building SKIP part */ var BaseModel = require('../base/BaseModel.js'); var util = require('util'); var debug = require('debug')('connector:builder'); var spaces = " ";//4 spaces var SkipBuilder = function(skipNum){ var currentSkipNumber = skipNum; this.getSkipNumber = function(){ return currentSkipNumber; }; }; util.inherits(SkipBuilder, BaseModel); /** The main entrance method interpreting and building the clauses */ SkipBuilder.prototype.buildClause = function(){ var self = this; var skipNum = this.getSkipNumber(); var constants = this.getConstants(); return constants.KEYWORD_LEVEL1_OFFSET.toUpperCase() + " " + skipNum; }; module.exports = SkipBuilder;
/*! * jQuery JavaScript Library v1.8.0 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: Thu Aug 09 2012 16:24:48 GMT-0400 (Eastern Daylight Time) */ (function( window, undefined ) { var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Use the correct document accordingly with window argument (sandbox) document = window.document, location = window.location, navigator = window.navigator, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // Save a reference to some core methods core_push = Array.prototype.push, core_slice = Array.prototype.slice, core_indexOf = Array.prototype.indexOf, core_toString = Object.prototype.toString, core_hasOwn = Object.prototype.hasOwnProperty, core_trim = String.prototype.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source, // Used for detecting and trimming whitespace core_rnotwhite = /\S/, core_rspace = /\s+/, // IE doesn't match non-breaking spaces with \s rtrim = core_rnotwhite.test("\xA0") ? (/^[\s\xA0]+|[\s\xA0]+$/g) : /^\s+|\s+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return ( letter + "" ).toUpperCase(); }, // The ready event handler and self cleanup method DOMContentLoaded = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); } else if ( document.readyState === "complete" ) { // we're here because readyState === "complete" in oldIE // which is good enough for us to call the dom ready! document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = ( context && context.nodeType ? context.ownerDocument || context : document ); // scripts is true for back-compat selector = jQuery.parseHTML( match[1], doc, true ); if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { this.attr.call( selector, context, true ); } return jQuery.merge( this, selector ); // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.8.0", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, eq: function( i ) { i = +i; return i === -1 ? this.slice( i ) : this.slice( i, i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ), "slice", core_slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ core_toString.call(obj) ] || "object"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // scripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, scripts ) { var parsed; if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { scripts = context; context = 0; } context = context || document; // Single tag if ( (parsed = rsingleTag.exec( data )) ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] ); return jQuery.merge( [], (parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes ); }, parseJSON: function( data ) { if ( !data || typeof data !== "string") { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && core_rnotwhite.test( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var name, i = 0, length = obj.length, isObj = length === undefined || jQuery.isFunction( obj ); if ( args ) { if ( isObj ) { for ( name in obj ) { if ( callback.apply( obj[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( obj[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in obj ) { if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : text.toString().replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var type, ret = results || []; if ( arr != null ) { // The window, strings (and functions) also have 'length' // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 type = jQuery.type( arr ); if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) { core_push.call( ret, arr ); } else { jQuery.merge( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, key, ret = [], i = 0, length = elems.length, // jquery objects are treated as arrays isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( key in elems ) { value = callback( elems[ key ], key, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, pass ) { var exec, bulk = key == null, i = 0, length = elems.length; // Sets many values if ( key && typeof key === "object" ) { for ( i in key ) { jQuery.access( elems, fn, i, key[i], 1, emptyGet, value ); } chainable = 1; // Sets one value } else if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = pass === undefined && jQuery.isFunction( value ); if ( bulk ) { // Bulk operations only iterate when executing function values if ( exec ) { exec = fn; fn = function( elem, key, value ) { return exec.call( jQuery( elem ), value ); }; // Otherwise they run against the entire set } else { fn.call( elems, value ); fn = null; } } if ( fn ) { for (; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } } chainable = 1; } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" || ( document.readyState !== "loading" && document.addEventListener ) ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready, 1 ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); // All jQuery objects should point back to these rootjQuery = jQuery(document); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.split( core_rspace ), function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { if ( jQuery.isFunction( arg ) && ( !options.unique || !self.has( arg ) ) ) { list.push( arg ); } else if ( arg && arg.length ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Control if a given callback is in the list has: function( fn ) { return jQuery.inArray( fn, list ) > -1; }, // Remove all callbacks from the list empty: function() { list = []; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( list && ( !fired || stack ) ) { if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ]( jQuery.isFunction( fn ) ? function() { var returned = fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); } } : newDefer[ action ] ); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return typeof obj === "object" ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] = list.fire deferred[ tuple[0] ] = list.fire; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function() { var support, all, a, select, opt, input, fragment, eventName, i, isSupported, clickFn, div = document.createElement("div"); // Preliminary tests div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; all = div.getElementsByTagName("*"); a = div.getElementsByTagName("a")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; // Can't get basic test support if ( !all || !all.length || !a ) { return {}; } // First batch of supports tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: ( div.firstChild.nodeType === 3 ), // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: ( a.getAttribute("href") === "/a" ), // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.5/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: ( input.value === "on" ), // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // Tests for enctype support on a form(#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode boxModel: ( document.compatMode === "CSS1Compat" ), // Will be defined later submitBubbles: true, changeBubbles: true, focusinBubbles: false, deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, boxSizingReliable: true, pixelPosition: false }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete div.test; } catch( e ) { support.deleteExpando = false; } if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { div.attachEvent( "onclick", clickFn = function() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; }); div.cloneNode( true ).fireEvent("onclick"); div.detachEvent( "onclick", clickFn ); } // Check if a radio maintains its value // after being appended to the DOM input = document.createElement("input"); input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; input.setAttribute( "checked", "checked" ); // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "name", "t" ); div.appendChild( input ); fragment = document.createDocumentFragment(); fragment.appendChild( div.lastChild ); // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; fragment.removeChild( input ); fragment.appendChild( div ); // Technique from Juriy Zaytsev // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ // We only care about the case where non-standard event systems // are used, namely in IE. Short-circuiting here helps us to // avoid an eval call (in setAttribute) which can cause CSP // to go haywire. See: https://developer.mozilla.org/en/Security/CSP if ( div.attachEvent ) { for ( i in { submit: true, change: true, focusin: true }) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } // Run tests that need a body at doc ready jQuery(function() { var container, div, tds, marginDiv, divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px"; body.insertBefore( container, body.firstChild ); // Construct the test element div = document.createElement("div"); container.appendChild( div ); // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). // (only IE 8 fails this test) div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Check if empty table cells still have offsetWidth/Height // (IE <= 8 fail this test) support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; support.boxSizing = ( div.offsetWidth === 4 ); support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); // NOTE: To any future maintainer, window.getComputedStyle was used here // instead of getComputedStyle because it gave a better gzip size. // The difference between window.getComputedStyle and getComputedStyle is // 7 bytes if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. For more // info see bug #3333 // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = document.createElement("div"); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; div.appendChild( marginDiv ); support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== "undefined" ) { // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout // (IE < 8 does this) div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = "block"; div.style.overflow = "visible"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); container.style.zoom = 1; } // Null elements to avoid leaks in IE body.removeChild( container ); container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE fragment.removeChild( div ); all = a = select = opt = input = fragment = div = null; return support; })(); var rbrace = /^(?:\{.*\}|\[.*\])$/, rmultiDash = /([A-Z])/g; jQuery.extend({ cache: {}, deletedIds: [], // Please use with caution uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ internalKey ] = id = jQuery.deletedIds.pop() || ++jQuery.uuid; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( getByName ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, l, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } for ( i = 0, l = name.length; i < l; i++ ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) } else if ( jQuery.support.deleteExpando || cache != cache.window ) { delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var parts, part, attr, name, l, elem = this[0], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attr = elem.attributes; for ( l = attr.length; i < l; i++ ) { name = attr[i].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } parts = key.split( ".", 2 ); parts[1] = parts[1] ? "." + parts[1] : ""; part = parts[1] + "!"; return jQuery.access( this, function( value ) { if ( value === undefined ) { data = this.triggerHandler( "getData" + part, [ parts[0] ] ); // Try to fetch any internally stored data first if ( data === undefined && elem ) { data = jQuery.data( elem, key ); data = dataAttr( elem, key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } parts[1] = value; this.each(function() { var self = jQuery( this ); self.triggerHandler( "setData" + part, parts ); jQuery.data( this, key, value ); self.triggerHandler( "changeData" + part, parts ); }); }, null, value, arguments.length > 1, null, false ); }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), 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(); } 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 ( !queue.length && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery.removeData( elem, type + "queue", true ); jQuery.removeData( elem, key, true ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { if ( (tmp = jQuery._data( elements[ i ], type + "queueHooks" )) && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, fixSpecified, rclass = /[\t\r\n]/g, rreturn = /\r/g, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea|)$/i, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classNames, i, l, elem, setClass, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call(this, j, this.className) ); }); } if ( value && typeof value === "string" ) { classNames = value.split( core_rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 ) { if ( !elem.className && classNames.length === 1 ) { elem.className = value; } else { setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { var removes, className, elem, c, cl, i, l; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call(this, j, this.className) ); }); } if ( (value && typeof value === "string") || value === undefined ) { removes = ( value || "" ).split( core_rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 && elem.className ) { className = (" " + elem.className + " ").replace( rclass, " " ); // loop over each item in the removal list for ( c = 0, cl = removes.length; c < cl; c++ ) { // Remove until there is nothing to remove, while ( className.indexOf(" " + removes[ c ] + " ") > -1 ) { className = className.replace( " " + removes[ c ] + " " , " " ); } } elem.className = value ? jQuery.trim( className ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.split( core_rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val, self = jQuery(this); if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, i, max, option, index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one"; // Nothing was selected if ( index < 0 ) { return null; } // Loop through all the selected options i = one ? index : 0; max = one ? index + 1 : options.length; for ( ; i < max; i++ ) { option = options[ i ]; // Don't return options that are disabled or in a disabled optgroup if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } // Fixes Bug #2551 -- select.val() broken in IE after form.reset() if ( one && !values.length && options.length ) { return jQuery( options[ index ] ).val(); } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, // Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9 attrFn: {}, attr: function( elem, name, value, pass ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, "" + value ); return value; } } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }, removeAttr: function( elem, value ) { var propName, attrNames, name, isBool, i = 0; if ( value && elem.nodeType === 1 ) { attrNames = value.split( core_rspace ); for ( ; i < attrNames.length; i++ ) { name = attrNames[ i ]; if ( name ) { propName = jQuery.propFix[ name ] || name; isBool = rboolean.test( name ); // See #9699 for explanation of this approach (setting first, then removal) // Do not do this for boolean attributes (see #10870) if ( !isBool ) { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); // Set corresponding property to false for boolean attributes if ( isBool && propName in elem ) { elem[ propName ] = false; } } } } }, attrHooks: { type: { set: function( elem, value ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to it's default in case type is set after value // This is for element creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } }, // Use the value property for back compat // Use the nodeHook for button elements in IE6/7 (#1954) value: { get: function( elem, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.get( elem, name ); } return name in elem ? elem.value : null; }, set: function( elem, value, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.set( elem, value, name ); } // Does not return so that setAttribute is also used elem.value = value; } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return ( elem[ name ] = value ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Hook for boolean attributes boolHook = { get: function( elem, name ) { // Align boolean attributes with corresponding properties // Fall back to attribute presence where some booleans are not supported var attrNode, property = jQuery.prop( elem, name ); return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { var propName; if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { // value is true since we know at this point it's type boolean and not false // Set boolean attributes to the same name and set the DOM property propName = jQuery.propFix[ name ] || name; if ( propName in elem ) { // Only set the IDL specifically if it already exists on the element elem[ propName ] = true; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { fixSpecified = { name: true, id: true, coords: true }; // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function( elem, name ) { var ret; ret = elem.getAttributeNode( name ); return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ? ret.value : undefined; }, set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { ret = document.createAttribute( name ); elem.setAttributeNode( ret ); } return ( ret.value = value + "" ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function( elem, value, name ) { if ( value === "" ) { value = "false"; } nodeHook.set( elem, value, name ); } }; } // Some attributes require a special call on IE if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret === null ? undefined : ret; } }); }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Normalize to lowercase since IE uppercases css property names return elem.style.cssText.toLowerCase() || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = "" + value ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }); }); var rformElems = /^(?:textarea|input|select)$/i, rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/, rhoverHack = /(?:^|\s)hover(\.\S+|)\b/, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, hoverHack = function( events ) { return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); }; /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { add: function( elem, types, handler, data, selector ) { var elemData, eventHandle, events, t, tns, type, namespaces, handleObj, handleObjIn, handlers, special; // Don't attach events to noData or text/comment nodes (allow plain objects tho) if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first events = elemData.events; if ( !events ) { elemData.events = events = {}; } eventHandle = elemData.handle; if ( !eventHandle ) { elemData.handle = eventHandle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = jQuery.trim( hoverHack(types) ).split( " " ); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = tns[1]; namespaces = ( tns[2] || "" ).split( "." ).sort(); // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: tns[1], data: data, handler: handler, guid: handler.guid, selector: selector, namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first handlers = events[ type ]; if ( !handlers ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var t, tns, type, origType, namespaces, origCount, j, events, special, eventType, handleObj, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = jQuery.trim( hoverHack( types || "" ) ).split(" "); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = origType = tns[1]; namespaces = tns[2]; // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector? special.delegateType : special.bindType ) || type; eventType = events[ type ] || []; origCount = eventType.length; namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null; // Remove matching events for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !namespaces || namespaces.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { eventType.splice( j--, 1 ); if ( handleObj.selector ) { eventType.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( eventType.length === 0 && origCount !== eventType.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery.removeData( elem, "events", true ); } }, // Events that are safe to short-circuit if no handlers are attached. // Native DOM events should not be added, they may have inline handlers. customEvent: { "getData": true, "setData": true, "changeData": true }, trigger: function( event, data, elem, onlyHandlers ) { // Don't do events on text and comment nodes if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { return; } // Event object or event type var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType, type = event.type || event, namespaces = []; // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "!" ) >= 0 ) { // Exclusive events trigger only for the exact event (no namespaces) type = type.slice(0, -1); exclusive = true; } if ( type.indexOf( "." ) >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { // No jQuery handlers for this event type, and it can't have inline handlers return; } // Caller can pass in an Event, Object, or just an event type string event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal new jQuery.Event( type, event ) : // Just the event type (string) new jQuery.Event( type ); event.type = type; event.isTrigger = true; event.exclusive = exclusive; event.namespace = namespaces.join( "." ); event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null; ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; // Handle a global trigger if ( !elem ) { // TODO: Stop taunting the data cache; remove global events and always attach to document cache = jQuery.cache; for ( i in cache ) { if ( cache[ i ].events && cache[ i ].events[ type ] ) { jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); } } return; } // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data != null ? jQuery.makeArray( data ) : []; data.unshift( event ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) eventPath = [[ elem, special.bindType || type ]]; if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; for ( old = elem; cur; cur = cur.parentNode ) { eventPath.push([ cur, bubbleType ]); old = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( old === (elem.ownerDocument || document) ) { eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); } } // Fire handlers on the event path for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { cur = eventPath[i][0]; event.type = eventPath[i][1]; handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Note that this is a bare JS function and not a jQuery handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) // IE<9 dies on focus/blur to hidden element (#1486) if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method old = elem[ ontype ]; if ( old ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( old ) { elem[ ontype ] = old; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event || window.event ); var i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related, handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), delegateCount = handlers.delegateCount, args = [].slice.call( arguments ), run_all = !event.exclusive && !event.namespace, special = jQuery.event.special[ event.type ] || {}, handlerQueue = []; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers that should run if there are delegated events // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && !(event.button && event.type === "click") ) { // Pregenerate a single jQuery object for reuse with .is() jqcur = jQuery(this); jqcur.context = this; for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { // Don't process clicks (ONLY) on disabled elements (#6911, #8165, #xxxx) if ( cur.disabled !== true || event.type !== "click" ) { selMatch = {}; matches = []; jqcur[0] = cur; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; sel = handleObj.selector; if ( selMatch[ sel ] === undefined ) { selMatch[ sel ] = jqcur.is( sel ); } if ( selMatch[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, matches: matches }); } } } } // Add the remaining (directly-bound) handlers if ( handlers.length > delegateCount ) { handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); } // Run delegates first; they may want to stop propagation beneath us for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { matched = handlerQueue[ i ]; event.currentTarget = matched.elem; for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { handleObj = matched.matches[ j ]; // Triggered event must either 1) be non-exclusive and have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { event.data = handleObj.data; event.handleObj = handleObj; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, // Includes some event props shared by KeyEvent and MouseEvent // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, originalEvent = event, fixHook = jQuery.event.fixHooks[ event.type ] || {}, copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = jQuery.Event( originalEvent ); for ( i = copy.length; i; ) { prop = copy[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Target should not be a text node (#504, Safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8) event.metaKey = !!event.metaKey; return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { ready: { // Make sure the ready event is setup setup: jQuery.bindReady }, load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { delegateType: "focusin" }, blur: { delegateType: "focusout" }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; // Some plugins are using, but it's undocumented/deprecated and will be removed. // The 1.7 special event interface should provide all the hooks needed now. jQuery.event.handle = jQuery.event.dispatch; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 – // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === "undefined" ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) } else { e.returnValue = false; } }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj, selector = handleObj.selector; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "_submit_attached" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "_submit_attached", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "_change_attached", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // && selector != null // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, live: function( types, data, fn ) { jQuery( this.context ).on( types, this.selector, data, fn ); return this; }, die: function( types, fn ) { jQuery( this.context ).off( types, this.selector || "**", fn ); return this; }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { return jQuery.event.trigger( type, data, this[0], true ); } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, guid = fn.guid || jQuery.guid++, i = 0, toggler = function( event ) { // Figure out which function to execute var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; }; // link all the functions, so any of them can unbind this click handler toggler.guid = guid; while ( i < args.length ) { args[ i++ ].guid = guid; } return this.click( toggler ); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; if ( rkeyEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; } if ( rmouseEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; } }); /*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function( window, undefined ) { var cachedruns, dirruns, sortOrder, siblingCheck, assertGetIdNotName, document = window.document, docElem = document.documentElement, strundefined = "undefined", hasDuplicate = false, baseHasDuplicate = true, done = 0, slice = [].slice, push = [].push, expando = ( "sizcache" + Math.random() ).replace( ".", "" ), // Regex // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors) // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors operators = "([*^$|!~]?=)", attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|((?:[^,]|\\\\,|(?:,(?=[^\\[]*\\]))|(?:,(?=[^\\(]*\\))))*))\\)|)", pos = ":(nth|eq|gt|lt|first|last|even|odd)(?:\\((\\d*)\\)|)(?=[^-]|$)", combinators = whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*", groups = "(?=[^\\x20\\t\\r\\n\\f])(?:\\\\.|" + attributes + "|" + pseudos.replace( 2, 7 ) + "|[^\\\\(),])+", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcombinators = new RegExp( "^" + combinators ), // All simple (non-comma) selectors, excluding insignifant trailing whitespace rgroups = new RegExp( groups + "?(?=" + whitespace + "*,|$)", "g" ), // A selector, or everything after leading whitespace // Optionally followed in either case by a ")" for terminating sub-selectors rselector = new RegExp( "^(?:(?!,)(?:(?:^|,)" + whitespace + "*" + groups + ")*?|" + whitespace + "*(.*?))(\\)|$)" ), // All combinators and selector components (attribute test, tag, pseudo, etc.), the latter appearing together when consecutive rtokens = new RegExp( groups.slice( 19, -6 ) + "\\x20\\t\\r\\n\\f>+~])+|" + combinators, "g" ), // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/, rsibling = /[\x20\t\r\n\f]*[+~]/, rendsWithNot = /:not\($/, rheader = /h\d/i, rinputs = /input|select|textarea|button/i, rbackslash = /\\(?!\\)/g, matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "[-", "[-\\*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|nth|last|first)-child(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "POS": new RegExp( pos, "ig" ), // For use in libraries implementing .is() "needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" ) }, classCache = {}, cachedClasses = [], compilerCache = {}, cachedSelectors = [], // Mark a function for use in filtering markFunction = function( fn ) { fn.sizzleFilter = true; return fn; }, // Returns a function to use in pseudos for input types createInputFunction = function( type ) { return function( elem ) { // Check the input's nodeName and type return elem.nodeName.toLowerCase() === "input" && elem.type === type; }; }, // Returns a function to use in pseudos for buttons createButtonFunction = function( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; }, // Used for testing something on an element assert = function( fn ) { var pass = false, div = document.createElement("div"); try { pass = fn( div ); } catch (e) {} // release memory in IE div = null; return pass; }, // Check if attributes should be retrieved by attribute nodes assertAttributes = assert(function( div ) { div.innerHTML = "<select></select>"; var type = typeof div.lastChild.getAttribute("multiple"); // IE8 returns a string for some attributes even when not present return type !== "boolean" && type !== "string"; }), // Check if getElementById returns elements by name // Check if getElementsByName privileges form controls or returns elements by ID assertUsableName = assert(function( div ) { // Inject content div.id = expando + 0; div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; docElem.insertBefore( div, docElem.firstChild ); // Test var pass = document.getElementsByName && // buggy browsers will return fewer than the correct 2 document.getElementsByName( expando ).length === // buggy browsers will return more than the correct 0 2 + document.getElementsByName( expando + 0 ).length; assertGetIdNotName = !document.getElementById( expando ); // Cleanup docElem.removeChild( div ); return pass; }), // Check if the browser returns only elements // when doing getElementsByTagName("*") assertTagNameNoComments = assert(function( div ) { div.appendChild( document.createComment("") ); return div.getElementsByTagName("*").length === 0; }), // Check if getAttribute returns normalized href attributes assertHrefNotNormalized = assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }), // Check if getElementsByClassName can be trusted assertUsableClassName = assert(function( div ) { // Opera can't find a second classname (in 9.6) div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { return false; } // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; return div.getElementsByClassName("e").length !== 1; }); var Sizzle = function( selector, context, results, seed ) { results = results || []; context = context || document; var match, elem, xml, m, nodeType = context.nodeType; if ( nodeType !== 1 && nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } xml = isXML( context ); if ( !xml && !seed ) { if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) { push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); return results; } } } // All others return select( selector, context, results, seed, xml ); }; var Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, match: matchExpr, order: [ "ID", "TAG" ], attrHandle: {}, createPseudo: markFunction, find: { "ID": assertGetIdNotName ? function( id, context, xml ) { if ( typeof context.getElementById !== strundefined && !xml ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } } : function( id, context, xml ) { if ( typeof context.getElementById !== strundefined && !xml ) { var m = context.getElementById( id ); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; } }, "TAG": assertTagNameNoComments ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { var elem, tmp = [], i = 0; for ( ; (elem = results[i]); i++ ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; } }, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( rbackslash, "" ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr.CHILD 1 type (only|nth|...) 2 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 3 xn-component of xn+y argument ([+-]?\d*n|) 4 sign of xn-component 5 x of xn-component 6 sign of y-component 7 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1] === "nth" ) { // nth-child requires argument if ( !match[2] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) ); match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" ); // other types prohibit arguments } else if ( match[2] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var argument, unquoted = match[4]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Relinquish our claim on characters in `unquoted` from a closing parenthesis on if ( unquoted && (argument = rselector.exec( unquoted )) && argument.pop() ) { match[0] = match[0].slice( 0, argument[0].length - unquoted.length - 1 ); unquoted = argument[0].slice( 0, -1 ); } // Quoted or unquoted, we have the full argument // Return only captures needed by the pseudo filter method (type and argument) match.splice( 2, 3, unquoted || match[3] ); return match; } }, filter: { "ID": assertGetIdNotName ? function( id ) { id = id.replace( rbackslash, "" ); return function( elem ) { return elem.getAttribute("id") === id; }; } : function( id ) { id = id.replace( rbackslash, "" ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === id; }; }, "TAG": function( nodeName ) { if ( nodeName === "*" ) { return function() { return true; }; } nodeName = nodeName.replace( rbackslash, "" ).toLowerCase(); return function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className ]; if ( !pattern ) { pattern = classCache[ className ] = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" ); cachedClasses.push( className ); // Avoid too large of a cache if ( cachedClasses.length > Expr.cacheLength ) { delete classCache[ cachedClasses.shift() ]; } } return function( elem ) { return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); }; }, "ATTR": function( name, operator, check ) { if ( !operator ) { return function( elem ) { return Sizzle.attr( elem, name ) != null; }; } return function( elem ) { var result = Sizzle.attr( elem, name ), value = result + ""; if ( result == null ) { return operator === "!="; } switch ( operator ) { case "=": return value === check; case "!=": return value !== check; case "^=": return check && value.indexOf( check ) === 0; case "*=": return check && value.indexOf( check ) > -1; case "$=": return check && value.substr( value.length - check.length ) === check; case "~=": return ( " " + value + " " ).indexOf( check ) > -1; case "|=": return value === check || value.substr( 0, check.length + 1 ) === check + "-"; } }; }, "CHILD": function( type, argument, first, last ) { if ( type === "nth" ) { var doneName = done++; return function( elem ) { var parent, diff, count = 0, node = elem; if ( first === 1 && last === 0 ) { return true; } parent = elem.parentNode; if ( parent && (parent[ expando ] !== doneName || !elem.sizset) ) { for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.sizset = ++count; if ( node === elem ) { break; } } } parent[ expando ] = doneName; } diff = elem.sizset - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } }; } return function( elem ) { var node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; /* falls through */ case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; } }; }, "PSEUDO": function( pseudo, argument, context, xml ) { // 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 var fn = Expr.pseudos[ pseudo ] || Expr.pseudos[ pseudo.toLowerCase() ]; if ( !fn ) { Sizzle.error( "unsupported pseudo: " + pseudo ); } // The user may set fn.sizzleFilter to indicate // that arguments are needed to create the filter function // just as Sizzle does if ( !fn.sizzleFilter ) { return fn; } return fn( argument, context, xml ); } }, pseudos: { "not": markFunction(function( selector, context, xml ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var matcher = compile( selector.replace( rtrim, "$1" ), context, xml ); return function( elem ) { return !matcher( elem ); }; }), "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; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") var nodeType; elem = elem.firstChild; while ( elem ) { if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) { return false; } elem = elem.nextSibling; } return true; }, "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "header": function( elem ) { return rheader.test( elem.nodeName ); }, "text": function( elem ) { var type, attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && (type = elem.type) === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type ); }, // Input types "radio": createInputFunction("radio"), "checkbox": createInputFunction("checkbox"), "file": createInputFunction("file"), "password": createInputFunction("password"), "image": createInputFunction("image"), "submit": createButtonFunction("submit"), "reset": createButtonFunction("reset"), "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "focus": function( elem ) { var doc = elem.ownerDocument; return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href); }, "active": function( elem ) { return elem === elem.ownerDocument.activeElement; } }, setFilters: { "first": function( elements, argument, not ) { return not ? elements.slice( 1 ) : [ elements[0] ]; }, "last": function( elements, argument, not ) { var elem = elements.pop(); return not ? elements : [ elem ]; }, "even": function( elements, argument, not ) { var results = [], i = not ? 1 : 0, len = elements.length; for ( ; i < len; i = i + 2 ) { results.push( elements[i] ); } return results; }, "odd": function( elements, argument, not ) { var results = [], i = not ? 0 : 1, len = elements.length; for ( ; i < len; i = i + 2 ) { results.push( elements[i] ); } return results; }, "lt": function( elements, argument, not ) { return not ? elements.slice( +argument ) : elements.slice( 0, +argument ); }, "gt": function( elements, argument, not ) { return not ? elements.slice( 0, +argument + 1 ) : elements.slice( +argument + 1 ); }, "eq": function( elements, argument, not ) { var elem = elements.splice( +argument, 1 ); return not ? elements : elem; } } }; // Deprecated Expr.setFilters["nth"] = Expr.setFilters["eq"]; // Back-compat Expr.filters = Expr.pseudos; // IE6/7 return a modified href if ( !assertHrefNotNormalized ) { Expr.attrHandle = { "href": function( elem ) { return elem.getAttribute( "href", 2 ); }, "type": function( elem ) { return elem.getAttribute("type"); } }; } // Add getElementsByName if usable if ( assertUsableName ) { Expr.order.push("NAME"); Expr.find["NAME"] = function( name, context ) { if ( typeof context.getElementsByName !== strundefined ) { return context.getElementsByName( name ); } }; } // Add getElementsByClassName if usable if ( assertUsableClassName ) { Expr.order.splice( 1, 0, "CLASS" ); Expr.find["CLASS"] = function( className, context, xml ) { if ( typeof context.getElementsByClassName !== strundefined && !xml ) { return context.getElementsByClassName( className ); } }; } // If slice is not available, provide a backup try { slice.call( docElem.childNodes, 0 )[0].nodeType; } catch ( e ) { slice = function( i ) { var elem, results = []; for ( ; (elem = this[i]); i++ ) { results.push( elem ); } return results; }; } var 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; }; // Element contains another var contains = Sizzle.contains = docElem.compareDocumentPosition ? function( a, b ) { return !!( a.compareDocumentPosition( b ) & 16 ); } : docElem.contains ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) ); } : function( a, b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } return false; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ var getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( nodeType ) { if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes } else { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } return ret; }; Sizzle.attr = function( elem, name ) { var attr, xml = isXML( elem ); if ( !xml ) { name = name.toLowerCase(); } if ( Expr.attrHandle[ name ] ) { return Expr.attrHandle[ name ]( elem ); } if ( assertAttributes || xml ) { return elem.getAttribute( name ); } attr = elem.getAttributeNode( name ); return attr ? typeof elem[ name ] === "boolean" ? elem[ name ] ? name : null : attr.specified ? attr.value : null : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; // Check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function() { return (baseHasDuplicate = 0); }); if ( docElem.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return ( !a.compareDocumentPosition || !b.compareDocumentPosition ? a.compareDocumentPosition : a.compareDocumentPosition(b) & 4 ) ? -1 : 1; }; } else { sortOrder = function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return a.sourceIndex - b.sourceIndex; } var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // If the nodes are siblings (or identical) we can do a quick check if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; siblingCheck = function( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; }; } // Document sorting and removing duplicates Sizzle.uniqueSort = function( results ) { var elem, i = 1; if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( ; (elem = results[i]); i++ ) { if ( elem === results[ i - 1 ] ) { results.splice( i--, 1 ); } } } } return results; }; function multipleContexts( selector, contexts, results, seed ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results, seed ); } } function handlePOSGroup( selector, posfilter, argument, contexts, seed, not ) { var results, fn = Expr.setFilters[ posfilter.toLowerCase() ]; if ( !fn ) { Sizzle.error( posfilter ); } if ( selector || !(results = seed) ) { multipleContexts( selector || "*", contexts, (results = []), seed ); } return results.length > 0 ? fn( results, argument, not ) : []; } function handlePOS( selector, context, results, seed, groups ) { var match, not, anchor, ret, elements, currentContexts, part, lastIndex, i = 0, len = groups.length, rpos = matchExpr["POS"], // This is generated here in case matchExpr["POS"] is extended rposgroups = new RegExp( "^" + rpos.source + "(?!" + whitespace + ")", "i" ), // This is for making sure non-participating // matching groups are represented cross-browser (IE6-8) setUndefined = function() { var i = 1, len = arguments.length - 2; for ( ; i < len; i++ ) { if ( arguments[i] === undefined ) { match[i] = undefined; } } }; for ( ; i < len; i++ ) { // Reset regex index to 0 rpos.exec(""); selector = groups[i]; ret = []; anchor = 0; elements = seed; while ( (match = rpos.exec( selector )) ) { lastIndex = rpos.lastIndex = match.index + match[0].length; if ( lastIndex > anchor ) { part = selector.slice( anchor, match.index ); anchor = lastIndex; currentContexts = [ context ]; if ( rcombinators.test(part) ) { if ( elements ) { currentContexts = elements; } elements = seed; } if ( (not = rendsWithNot.test( part )) ) { part = part.slice( 0, -5 ).replace( rcombinators, "$&*" ); } if ( match.length > 1 ) { match[0].replace( rposgroups, setUndefined ); } elements = handlePOSGroup( part, match[1], match[2], currentContexts, elements, not ); } } if ( elements ) { ret = ret.concat( elements ); if ( (part = selector.slice( anchor )) && part !== ")" ) { if ( rcombinators.test(part) ) { multipleContexts( part, ret, results, seed ); } else { Sizzle( part, context, results, seed ? seed.concat(elements) : elements ); } } else { push.apply( results, ret ); } } else { Sizzle( selector, context, results, seed ); } } // Do not sort if this is a single filter return len === 1 ? results : Sizzle.uniqueSort( results ); } function tokenize( selector, context, xml ) { var tokens, soFar, type, groups = [], i = 0, // Catch obvious selector issues: terminal ")"; nonempty fallback match // rselector never fails to match *something* match = rselector.exec( selector ), matched = !match.pop() && !match.pop(), selectorGroups = matched && selector.match( rgroups ) || [""], preFilters = Expr.preFilter, filters = Expr.filter, checkContext = !xml && context !== document; for ( ; (soFar = selectorGroups[i]) != null && matched; i++ ) { groups.push( tokens = [] ); // Need to make sure we're within a narrower context if necessary // Adding a descendant combinator will generate what is needed if ( checkContext ) { soFar = " " + soFar; } while ( soFar ) { matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { soFar = soFar.slice( match[0].length ); // Cast descendant combinators to space matched = tokens.push({ part: match.pop().replace( rtrim, " " ), captures: match }); } // Filters for ( type in filters ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match, context, xml )) ) ) { soFar = soFar.slice( match.shift().length ); matched = tokens.push({ part: type, captures: match }); } } if ( !matched ) { break; } } } if ( !matched ) { Sizzle.error( selector ); } return groups; } function addCombinator( matcher, combinator, context ) { var dir = combinator.dir, doneName = done++; if ( !matcher ) { // If there is no matcher to check, check against the context matcher = function( elem ) { return elem === context; }; } return combinator.first ? function( elem, context ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 ) { return matcher( elem, context ) && elem; } } } : function( elem, context ) { var cache, dirkey = doneName + "." + dirruns, cachedkey = dirkey + "." + cachedruns; while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 ) { if ( (cache = elem[ expando ]) === cachedkey ) { return elem.sizset; } else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) { if ( elem.sizset ) { return elem; } } else { elem[ expando ] = cachedkey; if ( matcher( elem, context ) ) { elem.sizset = true; return elem; } elem.sizset = false; } } } }; } function addMatcher( higher, deeper ) { return higher ? function( elem, context ) { var result = deeper( elem, context ); return result && higher( result === true ? elem : result, context ); } : deeper; } // ["TAG", ">", "ID", " ", "CLASS"] function matcherFromTokens( tokens, context, xml ) { var token, matcher, i = 0; for ( ; (token = tokens[i]); i++ ) { if ( Expr.relative[ token.part ] ) { matcher = addCombinator( matcher, Expr.relative[ token.part ], context ); } else { token.captures.push( context, xml ); matcher = addMatcher( matcher, Expr.filter[ token.part ].apply( null, token.captures ) ); } } return matcher; } function matcherFromGroupMatchers( matchers ) { return function( elem, context ) { var matcher, j = 0; for ( ; (matcher = matchers[j]); j++ ) { if ( matcher(elem, context) ) { return true; } } return false; }; } var compile = Sizzle.compile = function( selector, context, xml ) { var tokens, group, i, cached = compilerCache[ selector ]; // Return a cached group function if already generated (context dependent) if ( cached && cached.context === context ) { return cached; } // Generate a function of recursive functions that can be used to check each element group = tokenize( selector, context, xml ); for ( i = 0; (tokens = group[i]); i++ ) { group[i] = matcherFromTokens( tokens, context, xml ); } // Cache the compiled function cached = compilerCache[ selector ] = matcherFromGroupMatchers( group ); cached.context = context; cached.runs = cached.dirruns = 0; cachedSelectors.push( selector ); // Ensure only the most recent are cached if ( cachedSelectors.length > Expr.cacheLength ) { delete compilerCache[ cachedSelectors.shift() ]; } return cached; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { return Sizzle( expr, null, null, [ elem ] ).length > 0; }; var select = function( selector, context, results, seed, xml ) { // Remove excessive whitespace selector = selector.replace( rtrim, "$1" ); var elements, matcher, i, len, elem, token, type, findContext, notTokens, match = selector.match( rgroups ), tokens = selector.match( rtokens ), contextNodeType = context.nodeType; // POS handling if ( matchExpr["POS"].test(selector) ) { return handlePOS( selector, context, results, seed, match ); } if ( seed ) { elements = slice.call( seed, 0 ); // To maintain document order, only narrow the // set if there is one group } else if ( match && match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID if ( tokens.length > 1 && contextNodeType === 9 && !xml && (match = matchExpr["ID"].exec( tokens[0] )) ) { context = Expr.find["ID"]( match[1], context, xml )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().length ); } findContext = ( (match = rsibling.exec( tokens[0] )) && !match.index && context.parentNode ) || context; // Get the last token, excluding :not notTokens = tokens.pop(); token = notTokens.split(":not")[0]; for ( i = 0, len = Expr.order.length; i < len; i++ ) { type = Expr.order[i]; if ( (match = matchExpr[ type ].exec( token )) ) { elements = Expr.find[ type ]( (match[1] || "").replace( rbackslash, "" ), findContext, xml ); if ( elements == null ) { continue; } if ( token === notTokens ) { selector = selector.slice( 0, selector.length - notTokens.length ) + token.replace( matchExpr[ type ], "" ); if ( !selector ) { push.apply( results, slice.call(elements, 0) ); } } break; } } } // Only loop over the given elements once // If selector is empty, we're already done if ( selector ) { matcher = compile( selector, context, xml ); dirruns = matcher.dirruns++; if ( elements == null ) { elements = Expr.find["TAG"]( "*", (rsibling.test( selector ) && context.parentNode) || context ); } for ( i = 0; (elem = elements[i]); i++ ) { cachedruns = matcher.runs++; if ( matcher(elem, context) ) { results.push( elem ); } } } return results; }; if ( document.querySelectorAll ) { (function() { var disconnectedMatch, oldSelect = select, rescape = /'|\\/g, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, rbuggyQSA = [], // matchesSelector(:active) reports false when true (IE9/Opera 11.5) // A support test would require too much code (would include document ready) // just skip matchesSelector for :active rbuggyMatches = [":active"], matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector; // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { div.innerHTML = "<select><option selected></option></select>"; // IE8 - Some boolean attributes are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here (do not put tests after this one) if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Opera 10-12/IE9 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<p test=''></p>"; if ( div.querySelectorAll("[test^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here (do not put tests after this one) div.innerHTML = "<input type='hidden'>"; if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push(":enabled", ":disabled"); } }); rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); select = function( selector, context, results, seed, xml ) { // Only use querySelectorAll when not filtering, // when this is not xml, // and when no QSA bugs apply if ( !seed && !xml && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { if ( context.nodeType === 9 ) { try { push.apply( results, slice.call(context.querySelectorAll( selector ), 0) ); return results; } catch(qsaError) {} // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { var old = context.getAttribute("id"), nid = old || expando, newContext = rsibling.test( selector ) && context.parentNode || context; if ( old ) { nid = nid.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } try { push.apply( results, slice.call( newContext.querySelectorAll( selector.replace( rgroups, "[id='" + nid + "'] $&" ) ), 0 ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } return oldSelect( selector, context, results, seed, xml ); }; if ( matches ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead try { matches.call( div, "[test!='']:sizzle" ); rbuggyMatches.push( Expr.match.PSEUDO ); } catch ( e ) {} }); // rbuggyMatches always contains :active, so no need for a length check rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") ); Sizzle.matchesSelector = function( elem, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); // rbuggyMatches always contains :active, so no need for an existence check if ( !isXML( elem ) && !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 || 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, null, null, [ elem ] ).length > 0; }; } })(); } // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); var runtil = /Until$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, isSimple = /^.[^:#\[\.,]*$/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, l, length, n, r, ret, self = this; if ( typeof selector !== "string" ) { return jQuery( selector ).filter(function() { for ( i = 0, l = self.length; i < l; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }); } ret = this.pushStack( "", "find", selector ); for ( i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( n = length; n < ret.length; n++ ) { for ( r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". rneedsContext.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { cur = this[i]; while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } cur = cur.parentNode; } } ret = ret.length > 1 ? jQuery.unique( ret ) : ret; return this.pushStack( ret, "closest", selectors ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); jQuery.fn.andSelf = jQuery.fn.addBack; // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( this.length > 1 && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, core_slice.call( arguments ).join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return ( elem === qualifier ) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, rnocache = /<(?:script|object|embed|option|style)/i, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rcheckableType = /^(?:checkbox|radio)$/, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "X<div>", "</div>" ]; } jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( !isDisconnected( this[0] ) ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } if ( arguments.length ) { var set = jQuery.clean( arguments ); return this.pushStack( jQuery.merge( set, this ), "before", this.selector ); } }, after: function() { if ( !isDisconnected( this[0] ) ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } if ( arguments.length ) { var set = jQuery.clean( arguments ); return this.pushStack( jQuery.merge( this, set ), "after", this.selector ); } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName( "*" ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function( value ) { if ( !isDisconnected( this[0] ) ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery( value ).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery( this ).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } return this.length ? this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : this; }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { // Flatten any nested arrays args = [].concat.apply( [], args ); var results, first, fragment, iNoClone, i = 0, value = args[0], scripts = [], l = this.length; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call( this, i, table ? self.html() : undefined ); self.domManip( args, table, callback ); }); } if ( this[0] ) { results = jQuery.buildFragment( args, this, scripts ); fragment = results.fragment; first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). // Fragments from the fragment cache must always be cloned and never used in place. for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) { callback.call( table && jQuery.nodeName( this[i], "table" ) ? findOrAppend( this[i], "tbody" ) : this[i], i === iNoClone ? fragment : jQuery.clone( fragment, true, true ) ); } } // Fix #11809: Avoid leaking memory fragment = first = null; if ( scripts.length ) { jQuery.each( scripts, function( i, elem ) { if ( elem.src ) { if ( jQuery.ajax ) { jQuery.ajax({ url: elem.src, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } else { jQuery.error("no ajax"); } } else { jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } }); } } return this; } }); function findOrAppend( elem, tag ) { return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function cloneFixAttributes( src, dest ) { var nodeName; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want if ( dest.clearAttributes ) { dest.clearAttributes(); } // mergeAttributes, in contrast, only merges back on the // original attributes, not the events if ( dest.mergeAttributes ) { dest.mergeAttributes( src ); } nodeName = dest.nodeName.toLowerCase(); if ( nodeName === "object" ) { // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; // IE blanks contents when cloning scripts } else if ( nodeName === "script" && dest.text !== src.text ) { dest.text = src.text; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); } jQuery.buildFragment = function( args, context, scripts ) { var fragment, cacheable, cachehit, first = args[ 0 ]; // Set context from what may come in as undefined or a jQuery collection or a node context = context || document; context = (context[0] || context).ownerDocument || context[0] || context; // Ensure that an attr object doesn't incorrectly stand in as a document object // Chrome and Firefox seem to allow this to occur and will throw exception // Fixes #8950 if ( typeof context.createDocumentFragment === "undefined" ) { context = document; } // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501 if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document && first.charAt(0) === "<" && !rnocache.test( first ) && (jQuery.support.checkClone || !rchecked.test( first )) && (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { // Mark cacheable and look for a hit cacheable = true; fragment = jQuery.fragments[ first ]; cachehit = fragment !== undefined; } if ( !fragment ) { fragment = context.createDocumentFragment(); jQuery.clean( args, context, fragment, scripts ); // Update the cache, but only store false // unless this is a second parsing of the same content if ( cacheable ) { jQuery.fragments[ first ] = cachehit && fragment; } } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), l = insert.length, parent = this.length === 1 && this[0].parentNode; if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( ; i < l; i++ ) { elems = ( i > 0 ? this.clone(true) : this ).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( typeof elem.getElementsByTagName !== "undefined" ) { return elem.getElementsByTagName( "*" ); } else if ( typeof elem.querySelectorAll !== "undefined" ) { return elem.querySelectorAll( "*" ); } else { return []; } } // Used in clean, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var srcElements, destElements, i, clone; if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // IE copies events bound via attachEvent when using cloneNode. // Calling detachEvent on the clone will also remove the events // from the original. In order to get around this, we use some // proprietary methods to clear the events. Thanks to MooTools // guys for this hotness. cloneFixAttributes( elem, clone ); // Using Sizzle here is crazy slow, so we use getElementsByTagName instead srcElements = getAll( elem ); destElements = getAll( clone ); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for ( i = 0; srcElements[i]; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { cloneFixAttributes( srcElements[i], destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { cloneCopyEvent( elem, clone ); if ( deepDataAndEvents ) { srcElements = getAll( elem ); destElements = getAll( clone ); for ( i = 0; srcElements[i]; ++i ) { cloneCopyEvent( srcElements[i], destElements[i] ); } } } srcElements = destElements = null; // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { var j, safe, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags, i = 0, ret = []; // Ensure that context is a document if ( !context || typeof context.createDocumentFragment === "undefined" ) { context = document; } // Use the already-created safe fragment if context permits for ( safe = context === document && safeFragment; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" ) { if ( !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else { // Ensure a safe container in which to render the html safe = safe || createSafeFragment( context ); div = div || safe.appendChild( context.createElement("div") ); // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Go to html and back, then peel off extra wrappers tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; depth = wrap[0]; div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> hasBody = rtbody.test(elem); tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; // Remember the top-level container for proper cleanup div = safe.lastChild; } } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } } // Fix #11356: Clear elements from safeFragment if ( div ) { safe.removeChild( div ); elem = div = safe = null; } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { for ( i = 0; (elem = ret[i]) != null; i++ ) { if ( jQuery.nodeName( elem, "input" ) ) { fixDefaultChecked( elem ); } else if ( typeof elem.getElementsByTagName !== "undefined" ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } } // Append elements to a provided document fragment if ( fragment ) { // Special handling of each script element handleScript = function( elem ) { // Check if we consider it executable if ( !elem.type || rscriptType.test( elem.type ) ) { // Detach the script and store it in the scripts array (if provided) or the fragment // Return truthy to indicate that it has been handled return scripts ? scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) : fragment.appendChild( elem ); } }; for ( i = 0; (elem = ret[i]) != null; i++ ) { // Check if we're done after handling an executable script if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) { // Append to fragment and handle embedded scripts fragment.appendChild( elem ); if ( typeof elem.getElementsByTagName !== "undefined" ) { // handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript ); // Splice the scripts into ret after their former ancestor and advance our index beyond them ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); i += jsTags.length; } } } } return ret; }, cleanData: function( elems, /* internal */ acceptData ) { var data, id, elem, type, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } jQuery.deletedIds.push( id ); } } } } } }); // Limit scope pollution from any deprecated API (function() { var matched, browser; // Use of jQuery.browser is frowned upon. // More details: http://api.jquery.com/jQuery.browser // jQuery.uaMatch maintained for back-compat jQuery.uaMatch = function( ua ) { ua = ua.toLowerCase(); var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) || /(webkit)[ \/]([\w.]+)/.exec( ua ) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) || /(msie) ([\w.]+)/.exec( ua ) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || []; return { browser: match[ 1 ] || "", version: match[ 2 ] || "0" }; }; matched = jQuery.uaMatch( navigator.userAgent ); browser = {}; if ( matched.browser ) { browser[ matched.browser ] = true; browser.version = matched.version; } // Deprecated, use jQuery.browser.webkit instead // Maintained for back-compat only if ( browser.webkit ) { browser.safari = true; } jQuery.browser = browser; jQuery.sub = function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); return jQuerySub; }; })(); var curCSS, iframe, iframeDoc, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, rposition = /^(top|right|bottom|left)$/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ), elemdisplay = {}, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400, lineHeight: 1 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ], eventsToggle = jQuery.fn.toggle; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var elem, display, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && elem.style.display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { display = curCSS( elem, "display" ); if ( !values[ index ] && display !== "none" ) { jQuery._data( elem, "olddisplay", display ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state, fn2 ) { var bool = typeof state === "boolean"; if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) { return eventsToggle.apply( this, arguments ); } return this.each(function() { if ( bool ? state : isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Exclude the following css properties to add px cssNumber: { "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, numeric, extra ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( numeric || extra !== undefined ) { num = parseFloat( val ); return numeric || jQuery.isNumeric( num ) ? num || 0 : val; } return val; }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); // NOTE: To any future maintainer, we've used both window.getComputedStyle // and getComputedStyle here to produce a better gzip size if ( window.getComputedStyle ) { curCSS = function( elem, name ) { var ret, width, minWidth, maxWidth, computed = getComputedStyle( elem, null ), style = elem.style; if ( computed ) { ret = computed[ name ]; if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { curCSS = function( elem, name ) { var left, rsLeft, ret = elem.currentStyle && elem.currentStyle[ name ], style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rsLeft = elem.runtimeStyle && elem.runtimeStyle.left; // Put in the new values to get a computed value out if ( rsLeft ) { elem.runtimeStyle.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { // we use jQuery.css instead of curCSS here // because of the reliableMarginRight CSS hook! val += jQuery.css( elem, extra + cssExpand[ i ], true ); } // From this point on we use curCSS for maximum performance (relevant in animations) if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } else { // at this point, extra isn't content, so add padding val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, valueIsBorderBox = true, isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"; if ( val <= 0 ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { if ( elemdisplay[ nodeName ] ) { return elemdisplay[ nodeName ]; } var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ), display = elem.css("display"); elem.remove(); // If the simple way fails, // get element's real default display by attaching it to a temp iframe if ( display === "none" || display === "" ) { // Use the already-created iframe if possible iframe = document.body.appendChild( iframe || jQuery.extend( document.createElement("iframe"), { frameBorder: 0, width: 0, height: 0 }) ); // Create a cacheable copy of the iframe document on first call. // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML // document to it; WebKit & Firefox won't allow reusing the iframe document. if ( !iframeDoc || !iframe.createElement ) { iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; iframeDoc.write("<!doctype html><html><body>"); iframeDoc.close(); } elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) ); display = curCSS( elem, "display" ); document.body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { if ( elem.offsetWidth !== 0 || curCSS( elem, "display" ) !== "none" ) { return getWidthOrHeight( elem, name, extra ); } else { return jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }); } } }, set: function( elem, value, extra ) { return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box" ) : 0 ); } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there there is no filter style applied in a css rule, we are done if ( currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { return curCSS( elem, "marginRight" ); } }); } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { var ret = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ], expanded = {}; for ( i = 0; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, rselectTextarea = /^(?:select|textarea)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } var // Document location ajaxLocation, // Document location segments ajaxLocParts, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rts = /([?&])_=[^&]*/, rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = ["*/"] + ["*"]; // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, list, placeBefore, dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ), i = 0, length = dataTypes.length; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression for ( ; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var selection, list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ); for ( ; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } // Don't do a request if no elements are being requested if ( !this.length ) { return this; } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( typeof params === "object" ) { type = "POST"; } // Request the remote document jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params, complete: function( jqXHR, status ) { if ( callback ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); } } }).done(function( responseText ) { // Save response for use in complete callback response = arguments; // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append( responseText.replace( rscript, "" ) ) // Locate the specified elements .find( selector ) : // If not, just inject the full result responseText ); }); return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.on( o, f ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; }); jQuery.extend({ getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { if ( settings ) { // Building a settings object ajaxExtend( target, jQuery.ajaxSettings ); } else { // Extending ajaxSettings settings = target; target = jQuery.ajaxSettings; } ajaxExtend( target, settings ); return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded; charset=UTF-8", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": allTypes }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // List of data converters // 1) key format is "source_type destination_type" (a single space in-between) // 2) the catchall symbol "*" can be used for source_type converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { context: true, url: true } }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // ifModified key ifModifiedKey, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events // It's the callbackContext if one was provided in the options // and if it's a DOM node or a jQuery collection globalEventContext = callbackContext !== s && ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { var lname = name.toLowerCase(); name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match === undefined ? null : match; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Cancel the request abort: function( statusText ) { statusText = statusText || strAbort; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ ifModifiedKey ] = modified; } modified = jqXHR.getResponseHeader("Etag"); if ( modified ) { jQuery.etag[ ifModifiedKey ] = modified; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { isSuccess = ajaxConvert( s, response ); statusText = isSuccess.state; success = isSuccess.data; error = isSuccess.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( !statusText || status ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = "" + ( nativeStatusText || statusText ); // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } // Attach deferreds deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; jqXHR.complete = completeDeferred.add; // Status-dependent callbacks jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { for ( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.always( tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace ); // Determine if a cross-domain request is in order if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Get ifModifiedKey before adding the anti-cache parameter ifModifiedKey = s.url; // Add anti-cache in url if needed if ( s.cache === false ) { var ts = jQuery.now(), // try replacing _= if it is there ret = s.url.replace( rts, "$1_=" + ts ); // if nothing was replaced, add timestamp to the end s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { ifModifiedKey = ifModifiedKey || s.url; if ( jQuery.lastModified[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); } if ( jQuery.etag[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); } } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout( function(){ jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } return jqXHR; }, // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { var conv, conv2, current, tmp, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(), prev = dataTypes[ 0 ], converters = {}, i = 0; // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } // Convert to each sequential dataType, tolerating list modification for ( ; (current = dataTypes[++i]); ) { // There's only work to do if current dataType is non-auto if ( current !== "*" ) { // Convert response if prev dataType is non-auto and differs from current 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.splice( i--, 0, current ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s["throws"] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } // Update prev for next iteration prev = current; } } return { state: "success", data: response }; } var oldCallbacks = [], rquestion = /\?/, rjsonp = /(=)\?(?=&|$)|\?\?/, nonce = jQuery.now(); // 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, data = s.data, url = s.url, hasCallback = s.jsonp !== false, replaceInUrl = hasCallback && rjsonp.test( url ), replaceInData = hasCallback && !replaceInUrl && typeof data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( data ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; overwritten = window[ callbackName ]; // Insert callback into url or form data if ( replaceInUrl ) { s.url = url.replace( rjsonp, "$1" + callbackName ); } else if ( replaceInData ) { s.data = data.replace( rjsonp, "$1" + callbackName ); } else if ( hasCallback ) { s.url += ( rquestion.test( 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 window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value 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"; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( head && script.parentNode ) { head.removeChild( script ); } // Dereference the script script = undefined; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( 0, 1 ); } } }; } }); var xhrCallbacks, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject ? function() { // Abort all pending requests for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( 0, 1 ); } } : false, xhrId = 0; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties (function( xhr ) { jQuery.extend( jQuery.support, { ajax: !!xhr, cors: !!xhr && ( "withCredentials" in xhr ) }); })( jQuery.ajaxSettings.xhr() ); // Create transport if the browser can provide an xhr if ( jQuery.support.ajax ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( _ ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responseHeaders, responses, xml; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) try { responses.text = xhr.responseText; } catch( _ ) { } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.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 setTimeout( callback, 0 ); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback(0,1); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var end, unit, prevScale, tween = this.createTween( prop, value ), parts = rfxnum.exec( value ), target = tween.cur(), start = +target || 0, scale = 1; if ( parts ) { end = +parts[2]; unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" && start ) { // Iteratively approximate from a nonzero starting point // Prefer the current property, because this process will be trivial if it uses the same units // Fallback to end or a simple constant start = jQuery.css( tween.elem, prop, true ) || end || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below prevScale = scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zeroes from tween.cur() scale = tween.cur() / target; // Stop looping if we've hit the mark or scale is unchanged } while ( scale !== 1 && scale !== prevScale ); } tween.unit = unit; tween.start = start; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }, 0 ); return ( fxNow = jQuery.now() ); } function createTweens( animation, props ) { jQuery.each( props, function( prop, value ) { var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( collection[ index ].call( animation, prop, value ) ) { // we're done with this property return; } } }); } function Animation( elem, properties, options ) { var result, index = 0, tweenerIndex = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), percent = 1 - ( remaining / animation.duration || 0 ), index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end, easing ) { 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; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } createTweens( animation, props ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { anim: animation, queue: animation.opts.queue, elem: elem }) ); // 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 ); } 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; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { var index, prop, value, length, dataShow, tween, hooks, oldfire, anim = this, style = elem.style, orig = {}, handled = [], hidden = elem.nodeType && isHidden( elem ); // 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 if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.support.shrinkWrapBlocks ) { anim.done(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( index in props ) { value = props[ index ]; if ( rfxtypes.exec( value ) ) { delete props[ index ]; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } handled.push( index ); } } length = handled.length; if ( length ) { dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} ); if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery.removeData( elem, "fxshow", true ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( index = 0 ; index < length ; index++ ) { prop = handled[ index ]; tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 ); orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } 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 || "swing"; 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 ]; this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); 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; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing any value as a 4th 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, false, "" ); // 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.style && ( 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; } } } }; // Remove in 2.0 - this supports IE8's 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.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" || // special check for .toggle( handler, handler, ... ) ( !i && jQuery.isFunction( speed ) && jQuery.isFunction( easing ) ) ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); 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 resolve immediately if ( empty ) { anim.stop( true ); } }; 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 ); } }); } }); // 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 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; } // 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.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.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) && !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.interval = 13; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } var rroot = /^(?:body|html)$/i; jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var box, docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft, top, left, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } if ( (body = doc.body) === elem ) { return jQuery.offset.bodyOffset( elem ); } docElem = doc.documentElement; // Make sure we're not dealing with a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return { top: 0, left: 0 }; } box = elem.getBoundingClientRect(); win = getWindow( doc ); clientTop = docElem.clientTop || body.clientTop || 0; clientLeft = docElem.clientLeft || body.clientLeft || 0; scrollTop = win.pageYOffset || docElem.scrollTop; scrollLeft = win.pageXOffset || docElem.scrollLeft; top = box.top + scrollTop - clientTop; left = box.left + scrollLeft - clientLeft; return { top: top, left: left }; }; jQuery.offset = { bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.css(body, "marginTop") ) || 0; left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[0] ) { return; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent || document.body; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // 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 jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, value, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable ); }; }); }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use a proper concatenation script that understands anonymous // AMD modules. A named AMD is safest and most robust way to register. // Lowercase jquery is used because AMD module names are derived from // file names, and jQuery is normally delivered in a lowercase file name. // Do this after creating the global so that if an AMD module wants to call // noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window );
// test-createkey.js // © 2012 Harald Rudell <harald@therudells.com> MIT License var createkey = require('../lib/createkey') // https://github.com/haraldrudell/mochawrapper var assert = require('mochawrapper') exports['Create Key:'] = { 'Exports': function () { assert.exportsTest(createkey, 1) }, 'Same': function () { var a1 = 'a' var a2 = 'a' var a1key = createkey.createKey(a1, a2) var a2key = createkey.createKey(a2, a1) assert.equal(a1key, a2key) }, 'Different': function () { var a1 = 'a' var a2 = 'b' var a1key = createkey.createKey(a1, a2) var a2key = createkey.createKey(a2, a1) assert.notEqual(a1key, a2key) }, }
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang("a11yhelp","th",{title:"Accessibility Instructions",contents:"Help Contents. To close this dialog press ESC.",legend:[{name:"ทั่วไป",items:[{name:"แถบเครื่องมือสำหรับเครื่องมือช่วยพิมพ์",legend:"Press ${toolbarFocus} to navigate to the toolbar. Move to the next and previous toolbar group with TAB and SHIFT-TAB. Move to the next and previous toolbar button with RIGHT ARROW or LEFT ARROW. Press SPACE or ENTER to activate the toolbar button."},{name:"Editor Dialog",legend:"Inside a dialog, press TAB to navigate to next dialog field, press SHIFT + TAB to move to previous field, press ENTER to submit dialog, press ESC to cancel dialog. For dialogs that have multiple tab pages, press ALT + F10 to navigate to tab-list. Then move to next tab with TAB OR RIGTH ARROW. Move to previous tab with SHIFT + TAB or LEFT ARROW. Press SPACE or ENTER to select the tab page."}, {name:"Editor Context Menu",legend:"Press ${contextMenu} or APPLICATION KEY to open context-menu. Then move to next menu option with TAB or DOWN ARROW. Move to previous option with SHIFT+TAB or UP ARROW. Press SPACE or ENTER to select the menu option. Open sub-menu of current option with SPACE or ENTER or RIGHT ARROW. Go back to parent menu item with ESC or LEFT ARROW. Close context menu with ESC."},{name:"Editor List Box",legend:"Inside a list-box, move to next list item with TAB OR DOWN ARROW. Move to previous list item with SHIFT + TAB or UP ARROW. Press SPACE or ENTER to select the list option. Press ESC to close the list-box."}, {name:"Editor Element Path Bar",legend:"Press ${elementsPathFocus} to navigate to the partials-portfolio path bar. Move to next element button with TAB or RIGHT ARROW. Move to previous button with SHIFT+TAB or LEFT ARROW. Press SPACE or ENTER to select the element in editor."}]},{name:"คำสั่ง",items:[{name:"เลิกทำคำสั่ง",legend:"วาง ${undo}"},{name:"คำสั่งสำหรับทำซ้ำ",legend:"วาง ${redo}"},{name:"คำสั่งสำหรับตัวหนา",legend:"วาง ${bold}"},{name:"คำสั่งสำหรับตัวเอียง",legend:"วาง ${italic}"},{name:"คำสั่งสำหรับขีดเส้นใต้", legend:"วาง ${underline}"},{name:"คำสั่งสำหรับลิงก์",legend:"วาง ${link}"},{name:" Toolbar Collapse command",legend:"Press ${toolbarCollapse}"},{name:" Access previous focus space command",legend:"Press ${accessPreviousSpace} to access the closest unreachable focus space before the caret, for example: two adjacent HR partials-portfolio. Repeat the key combination to reach distant focus spaces."},{name:" Access next focus space command",legend:"Press ${accessNextSpace} to access the closest unreachable focus space after the caret, for example: two adjacent HR partials-portfolio. Repeat the key combination to reach distant focus spaces."}, {name:" Accessibility Help",legend:"Press ${a11yHelp}"}]}],backspace:"Backspace",tab:"Tab",enter:"Enter",shift:"Shift",ctrl:"Ctrl",alt:"Alt",pause:"Pause",capslock:"Caps Lock",escape:"Escape",pageUp:"Page Up",pageDown:"Page Down",end:"End",home:"Home",leftArrow:"Left Arrow",upArrow:"Up Arrow",rightArrow:"Right Arrow",downArrow:"Down Arrow",insert:"Insert","delete":"Delete",leftWindowKey:"Left Windows key",rightWindowKey:"Right Windows key",selectKey:"Select key",numpad0:"Numpad 0",numpad1:"Numpad 1", numpad2:"Numpad 2",numpad3:"Numpad 3",numpad4:"Numpad 4",numpad5:"Numpad 5",numpad6:"Numpad 6",numpad7:"Numpad 7",numpad8:"Numpad 8",numpad9:"Numpad 9",multiply:"Multiply",add:"Add",subtract:"Subtract",decimalPoint:"Decimal Point",divide:"Divide",f1:"F1",f2:"F2",f3:"F3",f4:"F4",f5:"F5",f6:"F6",f7:"F7",f8:"F8",f9:"F9",f10:"F10",f11:"F11",f12:"F12",numLock:"Num Lock",scrollLock:"Scroll Lock",semiColon:"Semicolon",equalSign:"Equal Sign",comma:"Comma",dash:"Dash",period:"Period",forwardSlash:"Forward Slash", graveAccent:"Grave Accent",openBracket:"Open Bracket",backSlash:"Backslash",closeBracket:"Close Bracket",singleQuote:"Single Quote"});
const logging = require('../../../../../shared/logging'); const commands = require('../../../schema').commands; const createLog = type => msg => logging[type](msg); function createColumnMigration({table, column, dbIsInCorrectState, operation, operationVerb, columnDefinition}) { return function columnMigrations({transacting}) { return transacting.schema.hasColumn(table, column) .then(dbIsInCorrectState) .then((isInCorrectState) => { const log = createLog(isInCorrectState ? 'warn' : 'info'); log(`${operationVerb} ${table}.${column}`); if (!isInCorrectState) { return operation(table, column, transacting, columnDefinition); } }); }; } module.exports.up = function (options) { return options.transacting.schema.hasColumn('posts', 'type').then((hasTypeColumn) => { if (!hasTypeColumn) { // no-op'd post.page->post.type migrations were never run return Promise.resolve(); } return createColumnMigration({ table: 'posts', column: 'type', dbIsInCorrectState(columnExists) { return columnExists === false; }, operation: commands.dropColumn, operationVerb: 'Removing' })(options); }); }; // `up` only runs in order to fix a previous migration so we don't want to do // anything in `down` because it would put previously-fine sites into the wrong // state module.exports.down = () => Promise.resolve(); module.exports.config = { transaction: true };
var searchData= [ ['privatefuncptr',['privateFuncPtr',['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/structHackProxy.html#aee31a33e4df4d2c3ffb20a916cdd542a',1,'HackPrivate::privateFuncPtr()'],['/home/shannaracat/dev/gitlab/workspace_oss/LostInCompilation/docs/doxygen/shacat/html/structHackProxy.html#aee31a33e4df4d2c3ffb20a916cdd542a',1,'HackProxy::privateFuncPtr()']]] ];
'use strict' const TCP = require('libp2p-tcp') const MulticastDNS = require('libp2p-mdns') const WS = require('libp2p-websockets') const Bootstrap = require('libp2p-bootstrap') const spdy = require('libp2p-spdy') const KadDHT = require('libp2p-kad-dht') const mplex = require('libp2p-mplex') const secio = require('libp2p-secio') const defaultsDeep = require('@nodeutils/defaults-deep') const libp2p = require('../../..') function mapMuxers (list) { return list.map((pref) => { if (typeof pref !== 'string') { return pref } switch (pref.trim().toLowerCase()) { case 'spdy': return spdy case 'mplex': return mplex default: throw new Error(pref + ' muxer not available') } }) } function getMuxers (muxers) { const muxerPrefs = process.env.LIBP2P_MUXER if (muxerPrefs && !muxers) { return mapMuxers(muxerPrefs.split(',')) } else if (muxers) { return mapMuxers(muxers) } else { return [mplex, spdy] } } class Node extends libp2p { constructor (_options) { const defaults = { modules: { transport: [ TCP, WS ], streamMuxer: getMuxers(_options.muxer), connEncryption: [ secio ], peerDiscovery: [ MulticastDNS, Bootstrap ], dht: KadDHT }, config: { peerDiscovery: { mdns: { interval: 10000, enabled: false }, bootstrap: { interval: 10000, enabled: false, list: _options.bootstrapList } }, dht: { kBucketSize: 20 } } } super(defaultsDeep(_options, defaults)) } } module.exports = Node
const User = require('../models/User'); exports.getpeople = (req, res) => { User.find((err, docs) => { res.render('missions', { people: docs }); }); };
'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 _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactIconBase = require('react-icon-base'); var _reactIconBase2 = _interopRequireDefault(_reactIconBase); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var TiPuzzle = function TiPuzzle(props) { return _react2.default.createElement( _reactIconBase2.default, _extends({ viewBox: '0 0 40 40' }, props), _react2.default.createElement( 'g', null, _react2.default.createElement('path', { d: 'm27.1 18.8c0.6 0 1.2 0.2 1.6 0.6 0.9 0.6 1.3-0.1 1.3-0.6v-3c0-1.3-1.1-2.5-2.5-2.5h-4.6c-0.6 0-1.2-0.3-0.6-1.2 0.4-0.5 0.6-1.1 0.6-1.7 0-1.6-1.7-2.9-3.7-2.9s-3.8 1.3-3.8 2.9c0 0.5 0.2 1 0.4 1.4 0.9 1.1 0.3 1.5-0.4 1.5h-4.6c-1.3 0-2.5 1.2-2.5 2.5v2.9c0 0.7 0.5 1.3 1.6 0.5 0.4-0.3 0.9-0.5 1.4-0.5 1.6 0 2.9 1.7 2.9 3.8s-1.3 3.7-2.9 3.7c-0.7 0-1.2-0.2-1.7-0.6-0.9-0.6-1.3 0.1-1.3 0.6v4.6c0 1.4 1.2 2.5 2.5 2.5h4.6c0.7 0 1.3-0.4 0.4-1.5-0.2-0.4-0.4-0.9-0.4-1.4 0-1.6 1.7-2.9 3.8-2.9s3.7 1.3 3.7 2.9c0 0.6-0.2 1.2-0.6 1.7-0.6 0.9 0 1.2 0.6 1.2h4.6c1.4 0 2.5-1.1 2.5-2.5v-4.5c0-0.7-0.4-1.3-1.5-0.5-0.5 0.3-0.9 0.5-1.4 0.5-1.6 0-2.9-1.7-2.9-3.8s1.3-3.7 2.9-3.7z' }) ) ); }; exports.default = TiPuzzle; module.exports = exports['default'];
var useObjectID = function(value,record) { if ( record.get('ObjectID') ) { return record.get('ObjectID'); } return 0; }; var shiftDayBeginningToEnd = function(day) { return Rally.util.DateTime.add(Rally.util.DateTime.add(Rally.util.DateTime.add(day,'hour',23), 'minute',59),'second',59); }; Ext.define('mockStory',{ extend: 'Ext.data.Model', fields: [ {name:'ObjectID', type: 'int'}, {name:'Name',type:'string'}, {name:'PlanEstimate',type:'int'}, {name:'id',type:'int',convert:useObjectID}, {name:'ScheduleState',type:'string',defaultValue:'Defined'}, {name:'Iteration', type: 'auto'} ] }); Ext.define('mockIteration',{ extend: 'Ext.data.Model', fields: [ {name:'ObjectID', type: 'int'}, {name:'Name',type:'string'}, {name:'StartDate',type:'auto'}, {name:'EndDate',type:'auto'}, {name: 'Project', type: 'auto'}, {name:'id',type:'int',convert:useObjectID} ] }); Ext.define('mockCFD',{ extend: 'Ext.data.Model', fields: [ {name:'CardCount',type:'int'}, {name:'CardEstimateTotal',type:'int'}, {name:'CardState',type:'string'}, {name:'CardToDoTotal',type:'int'}, {name:'CreationDate',type:'date'}, {name:'ObjectID',type:'int'}, {name:'TaskEstimateTotal',type:'int'} ] });
/* Copyright (c) 2014-2015 Richard Rodger, MIT License */ 'use strict' var Assert = require('assert') var Lab = require('lab') var Seneca = require('..') var lab = exports.lab = Lab.script() var describe = lab.describe var it = lab.it var assert = Assert var testopts = {log: 'silent'} // Shortcuts var arrayify = Function.prototype.apply.bind(Array.prototype.slice) describe('error', function () { lab.beforeEach(function (done) { process.removeAllListeners('SIGHUP') process.removeAllListeners('SIGTERM') process.removeAllListeners('SIGINT') process.removeAllListeners('SIGBREAK') done() }) it('act_not_found', act_not_found) it('param_caller', param_caller) it('exec_action_throw_basic', exec_action_throw_basic) it('exec_action_throw_nolog', exec_action_throw_nolog) it('exec_action_errhandler_throw', exec_action_errhandler_throw) it('exec_action_result', exec_action_result) it('exec_action_result_nolog', exec_action_result_nolog) it('exec_action_errhandler_result', exec_action_errhandler_result) it('action_callback', action_callback) it('ready_die', ready_die) it('legacy_fail', legacy_fail) function act_not_found (done) { var ctxt = {errlog: null} var si = make_seneca(ctxt) // ~~ CASE: fire-and-forget; err-logged si.act('a:1') // FIX: validate using act events // assert.equal('act_not_found', ctxt.errlog[8]) // ~~ CASE: callback; default ctxt.errlog = null si.act('a:1,default$:{x:1}', function (err, out) { assert.equal(err, null) assert.equal(ctxt.errlog, null) assert.ok(out.x) }) // ~~ CASE: callback; default Array ctxt.errlog = null si.act('a:1,default$:[1,"foo"]', function (err, out) { assert.ok(err === null) assert.ok(ctxt.errlog === null) assert.equal(out[0], 1) assert.ok(out[1], 'foo') }) // ~~ CASE: callback; no-default; err-result; err-logged si.act('a:1', function (err, out) { assert.equal(out, null) assert.equal('act_not_found', err.code) // assert.equal('act_not_found', ctxt.errlog[8]) // ~~ CASE: callback; bad-default; err-result; err-logged si.act('a:1,default$:"foo"', function (err, out) { assert.equal(out, null) assert.equal('act_default_bad', err.code) // assert.equal('act_default_bad', ctxt.errlog[8]) // ~~ CASE: fragile; throws; err-logged si.options({debug: {fragile: true}}) ctxt.errlog = null si.act('a:1', function (ex) { assert.equal('act_not_found', ex.code) // assert.equal('act_not_found', ctxt.errlog[8]) return done() }) }) }) } function param_caller (done) { var ctxt = {errlog: null} var si = make_seneca(ctxt) si.ready(function () { si.add('a:1,b:{required$:true}', function (args, done) { this.good({x: 1}) }) // ~~ CASE: callback; args-invalid; err-result; err-logged si.act('a:1', function (err) { assert.equal('act_invalid_msg', err.code) if (si.options().legacy.logging) { assert.equal('act_invalid_msg', ctxt.errlog[14]) } else { assert.equal('act_invalid_msg', ctxt.errlog.code) } // ~~ CASE: callback; args-valid si.act('a:1,b:1', function (err, out) { assert.equal(err, null) assert.equal(1, out.x) done() }) }) }) } function exec_action_throw_basic (done) { var ctxt = {errlog: null, done: done, log: true, name: 'throw'} var si = make_seneca(ctxt) si.add('a:1', function (args, done) { throw new Error('AAA') }) test_action(si, ctxt) } function exec_action_result (done) { var ctxt = {errlog: null, done: done, log: true, name: 'result'} var si = make_seneca(ctxt) si.add('a:1', function (args, done) { done(new Error('BBB')) }) test_action(si, ctxt) } // REMOVE after Seneca 3.x // err.log = false is a feature of legacy logging function exec_action_throw_nolog (done) { var ctxt = {errlog: null, done: done, log: false, name: 'throw_nolog'} var si = make_seneca(ctxt) if (si.options().legacy.logging) { si.add('a:1', function (args, done) { var err = new Error('CCC') err.log = false throw err }) test_action(si, ctxt) } else { done() } } // REMOVE after Seneca 3.x // err.log = false is a feature of legacy logging function exec_action_result_nolog (done) { var ctxt = {errlog: null, done: done, log: false, name: 'result_nolog'} var si = make_seneca(ctxt) if (si.options().legacy.logging) { si.add('a:1', function (args, done) { var err = new Error('CCC') err.log = false done(err) }) test_action(si, ctxt) } else { done() } } function exec_action_errhandler_throw (done) { var ctxt = {errlog: null} var si = make_seneca(ctxt) var aI = 0 si.options({ errhandler: function (err) { try { assert.equal('act_execute', err.code) assert.equal('a:1', err.details.pattern) assert.ok(err.message.indexOf('AAA' + aI) !== -1) aI++ if (aI > 1) { return true } done() } catch (e) { done(e) return true } } }) si.add('a:1', function (args, done) { throw new Error('AAA' + aI) }) // ~~ CASE: action-throws; callback; errhandler-nostop si.act('a:1', function (err, out) { // Need to use try-catch here as we've subverted the log // to test logging. try { assert.equal(out, null) assert.equal('act_execute', err.code) assert.equal('a:1', err.details.pattern) if (si.options().legacy.logging) { assert.equal('act_execute', ctxt.errlog[14]) } else { assert.equal('act_execute', ctxt.errlog.code) } ctxt.errlog = null // ~~ CASE: action-throws; no-callback; errhandler-nostop si.on('act-err', function (args, err) { if (aI === 1) { try { assert.equal(1, args.a) assert.equal('act_execute', err.code) assert.equal('a:1', err.details.pattern) if (si.options().legacy.logging) { assert.equal('act_execute', ctxt.errlog[14]) } else { assert.equal('act_execute', ctxt.errlog.code) } // ~~ CASE: action-throws; callback; errhandler-stops ctxt.errlog = null si.act('a:1', function () { try { assert.fail() } catch (e) { done(e) } }) } catch (e) { done(e) } } }) si.act('a:1') } catch (e) { done(e) } }) } function exec_action_errhandler_result (done) { var ctxt = {errlog: null} var si = make_seneca(ctxt) var aI = 0 si.options({ errhandler: function (err) { try { assert.equal('act_execute', err.code) assert.equal('a:1', err.details.pattern) assert.ok(err.message.indexOf('AAA' + aI) !== -1) aI++ if (aI > 1) { return true } done() } catch (e) { done(e) return true } } }) si.add('a:1', function (args, done) { done(new Error('AAA' + aI)) }) // ~~ CASE: action-throws; callback; errhandler-nostop si.act('a:1', function (err, out) { // Need to use try-catch here as we've subverted the log // to test logging. try { assert.equal(out, null) assert.equal('act_execute', err.code) assert.equal('a:1', err.details.pattern) if (si.options().legacy.logging) { assert.equal('act_execute', ctxt.errlog[14]) } else { assert.equal('act_execute', ctxt.errlog.code) } ctxt.errlog = null // ~~ CASE: action-throws; no-callback; errhandler-nostop si.on('act-err', function (args, err) { if (aI === 1) { try { assert.equal(1, args.a) assert.equal('act_execute', err.code) assert.equal('a:1', err.details.pattern) if (si.options().legacy.logging) { assert.equal('act_execute', ctxt.errlog[14]) } else { assert.equal('act_execute', ctxt.errlog.code) } // ~~ CASE: action-throws; callback; errhandler-stops ctxt.errlog = null si.act('a:1', function () { try { assert.fail() } catch (e) { done(e) } }) } catch (e) { done(e) } } }) si.act('a:1') } catch (e) { done(e) } }) } function make_seneca (ctxt) { var si = Seneca(testopts) if (si.options().legacy.logging) { si.options({ log: {map: [{level: 'error+', handler: function () { ctxt.errlog = arrayify(arguments) }}]}, trace: { unknown: 'error' }, legacy: { error_codes: false } }) return si } else { var logger = function () {} logger.preload = function () { return { extend: { logger: function (s, d) { ctxt.errlog = d } } } } return Seneca({ trace: { unknown: 'error' }, legacy: { error_codes: false }, internal: { logger: logger }}) } } function test_action (si, ctxt) { try { // ~~ CASE: action; callback; no-errhandler si.act('a:1', function (err, out) { // Need to use try-catch here as we've subverted the log // to test logging. try { assert.equal(out, null) assert.equal('act_execute', err.code, ctxt.name + '-A') assert.equal('a:1', err.details.pattern, ctxt.name + '-B') if (ctxt.log) { if (si.options().legacy.logging) { assert.equal('act_execute', ctxt.errlog[14], ctxt.name + '-C') } else { assert.equal('act_execute', ctxt.errlog.code, ctxt.name + '-C') } } else { assert.equal(ctxt.errlog, null) } ctxt.errlog = null // ~~ CASE: action; no-callback; no-errhandler si.on('act-err', function (args, err) { try { assert.equal(1, args.a) assert.equal('act_execute', err.code, ctxt.name + '-D') assert.equal('a:1', err.details.pattern, ctxt.name + '-E') if (ctxt.log) { if (si.options().legacy.logging) { assert.equal('act_execute', ctxt.errlog[14], ctxt.name + '-F') } else { assert.equal('act_execute', ctxt.errlog.code, ctxt.name + '-F') } } ctxt.done() } catch (e) { ctxt.done(e) } }) si.act('a:1') } catch (e) { ctxt.done(e) } }) } catch (e) { ctxt.done(e) } } function action_callback (done) { var ctxt = {errlog: null} var si = make_seneca(ctxt) var log_it = true si.options({errhandler: function (err) { assert.equal('act_callback', err.code, 'callback-G') assert.equal('seneca: Action a:1 callback threw: DDD.', err.message) if (log_it) { if (si.options().legacy.logging) { assert.equal('act_callback', ctxt.errlog[14], 'callback-H') } else { assert.equal('act_callback', ctxt.errlog.code, 'callback-H') } } else { // REMOVE in Seneca 3.x // e.log = false is a legacy logging feature if (si.options().legacy.logging) { assert.equal(ctxt.errlog, null) } done() } }}) si.ready(function () { si.add('a:1', function (args, done) { this.good({x: 1}) }) setTimeout(function () { // ~~ CASE: action; callback; callback-throws; log si.act('a:1', function (err, out) { assert.equal(err, null) assert.ok(out.x) throw new Error('DDD') }) }, 20) setTimeout(function () { // ~~ CASE: action; callback; callback-throws; no-log si.act('a:1', function (err, out) { assert.equal(err, null) assert.ok(out.x) var e = new Error('DDD') e.log = false log_it = false ctxt.errlog = null throw e }) }, 40) }) } function ready_die (done) { var si = Seneca({ log: 'silent', debug: {undead: true}, errhandler: function (err) { try { assert.ok(err.foo) done() } catch (e) { done(e) } } }) si.ready(function () { var e = new Error('EEE') e.foo = true throw e }) } function legacy_fail (done) { var si = Seneca({ log: 'silent' }) si.options({errhandler: function (err) { try { assert.equal('foo', err.code) assert.deepEqual({bar: 1}, err.details) } catch (e) { done(e) } }}) var err = si.fail('foo', {bar: 1}) assert.equal('foo', err.code) assert.deepEqual({bar: 1}, err.details) si.options({errhandler: function (err) { try { assert.equal('FOO', err.code) assert.deepEqual({BAR: 1}, err.details) } catch (e) { done(e) } }}) err = si.fail('FOO', {BAR: 1}, function (err) { assert.equal('FOO', err.code) assert.deepEqual({BAR: 1}, err.details) setImmediate(done) }) assert.equal('FOO', err.code) assert.deepEqual({BAR: 1}, err.details) } })
import React from 'react'; import { bool, array } from 'prop-types'; export default class ButtonToolbar extends React.Component { static propTypes = { pristine: bool.isRequired, submitting: bool.isRequired, errors: array.isRequired }; render() { const { pristine, submitting, errors } = this.props; const disabled = !!(pristine || errors.length > 0 || submitting); return ( <div> <button type="submit" disabled={disabled}>Submit</button> </div> ); } }
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { CellModule } from '../cell/cell.module'; import { Ng2SmartTableTbodyComponent } from './tbody.component'; import { TbodyCreateCancelComponent } from './cells/create-cancel.component'; import { TbodyEditDeleteComponent } from './cells/edit-delete.component'; var TBODY_COMPONENTS = [ TbodyCreateCancelComponent, TbodyEditDeleteComponent, Ng2SmartTableTbodyComponent, ]; var TBodyModule = (function () { function TBodyModule() { } return TBodyModule; }()); TBodyModule = __decorate([ NgModule({ imports: [ CommonModule, FormsModule, CellModule, ], declarations: TBODY_COMPONENTS.slice(), exports: TBODY_COMPONENTS.slice(), }) ], TBodyModule); export { TBodyModule }; //# sourceMappingURL=tbody.module.js.map
define([ 'aeris/util', 'aeris/api/models/aerisapimodel', 'aeris/errors/apiresponseerror' ], function(_, AerisApiModel, ApiResponseError) { /** * Represents data from multiple Aeris API endpoints * combined into a single model. * * Note that AerisBatchModel does not currently support * per-model actions or queries. * * @class AerisBatchModel * @namespace aeris.api.models * @extends aeris.api.models.AerisApiModel * * @constructor * @override * * @param {Object=} opt_attrs * @param {Object=} opt_options * @param {Object.<string,aeris.api.models.AerisApiModel>} opt_options.models See addModels documentation. * * @param {aeris.api.params.Params} opt_options.params */ var AerisBatchModel = function(opt_attrs, opt_options) { /** * A list of nested models, in the order of the last * API requests. * * @property modelsInOrder_ * @type {Array.<aeris.api.models.AerisApiModel>} * @private */ this.modelsInOrder_ = []; AerisApiModel.call(this, opt_attrs, opt_options); }; _.inherits(AerisBatchModel, AerisApiModel); /** * @method getEndpointUrl_ * @protected * @return {string} */ AerisBatchModel.prototype.getEndpointUrl_ = function() { return _.compact([ this.server_, 'batch', this.id ]).join('/'); }; /** * @method serializeParams_ * @protected * @param {aeris.api.params.models.Params} params * @return {Object} */ AerisBatchModel.prototype.serializeParams_ = function(params) { // Save models in order, // so that we can parse the response based // on the order of the `responses` array // (because javascript does not necessarily maintain order in objects) this.modelsInOrder_ = this.getNestedModels_(); return _.extend(params.toJSON(), { requests: this.getEncodedEndpoints_(this.modelsInOrder_) }); }; /** * Return component models, which * are attributes of the batch model. * * @method getNestedModels_ * @private * @return {Array.<aeris.api.models.AerisApiModel>} */ AerisBatchModel.prototype.getNestedModels_ = function() { return this.values().filter(function(attr) { return attr instanceof AerisApiModel; }); }; /** * @method getEncodedEndpoints_ * @private * @param {Array.<aeris.api.models.AerisApiModel>} apiModels */ AerisBatchModel.prototype.getEncodedEndpoints_ = function(apiModels) { var requests = apiModels.map(function(model) { var endpoint = '/' + model.getEndpoint(); return [ endpoint, this.encodeModelParams_(model) ].join(encodeURIComponent('?')); }, this); return requests.join(','); }; /** * @method encodeModelParams_ * @private * @param {aeris.api.models.AerisApiModel} model * @return {string} Encoded model params. */ AerisBatchModel.prototype.encodeModelParams_ = function(model) { var params = model.getParams().toJSON(); var paramsStr = _.map(params, function(val, key) { return key + '=' + val; }).join('&'); return this.encodeParamsString_(paramsStr); }; /** * @method encodeParamsString_ * @private */ AerisBatchModel.prototype.encodeParamsString_ = function(string) { // Aeris API only needs ? and & encoded. return string. replace('?', '%3F'). replace('&', '%26'); }; /** * Sets batch response data onto nested models * * @override * @method parse * @param {Object} raw Raw response data. * @return {Object} */ AerisBatchModel.prototype.parse = function(raw) { try { var responses = raw.response.responses; this.modelsInOrder_.forEach(function(model, index) { this.updateModelWithResponseData_(model, responses[index]); }, this); } catch (e) { throw new ApiResponseError('Unable to parse batch response data: ' + e.message); } return this.attributes; }; /** * @method updateModelWithResponseData_ * @private * @param {aeris.api.models.AerisApiModel} model * @param {Object} data Response data */ AerisBatchModel.prototype.updateModelWithResponseData_ = function(model, data) { var modelAttrs = model.parse(data); model.set(modelAttrs); }; /** * @method toJSON * @return {Object} */ AerisBatchModel.prototype.toJSON = function() { var json = AerisApiModel.prototype.toJSON.call(this); // toJSON'ify nested models _.each(json, function(val, key) { if (val instanceof AerisApiModel) { json[key] = val.toJSON(); } }); return json; }; return AerisBatchModel; });
module.exports="http://192.168.1.18/nafrhythm";
'use strict'; module.exports.definition = { set: function (v) { this.setProperty('-webkit-transition-property', v); }, get: function () { return this.getPropertyValue('-webkit-transition-property'); }, enumerable: true };
exports.init = function(grunt) { 'use strict'; var fs = require('fs'); var path = require('path'); var flow = require('nue').flow; var as = require('nue').as; var istanbul = require('istanbul'); function flowEnd(err, done) { if (err) { grunt.fail.fatal(err); } else { grunt.log.ok(); } done(); } function makeReporters(options) { var result = []; var reporters = options.reporters && typeof options.reporters === 'object' ? options.reporters : {}; Object.keys(reporters).forEach(function(n) { if(reporters[n]) { result.push({ type : n, options : reporters[n] }); } }); var append = function(t) { if(t && !reporters[t]) { result.push({ type : t, options : options}); reporters[t] = true; } }; append(options.type); var mapping = { 'none' : [], 'detail': ['text'], 'both' : ['text', 'text-summary'] }; var a = mapping[options.print]; if(a) { a.forEach(append); } else { append('text-summary'); } return result; } return { instrument : function(files, options, done) { var outFile = function(file) { return path.join(options.basePath, options.flatten === true ? path.basename(file) : file); }; var instFlow = flow(function readFile(f) { fs.readFile(f.name, 'utf8', this.async({ name : f.name, code : as(1) })); }, function instrument(f) { grunt.verbose.writeln('instrument from ' + f.name); var instrumenter = new istanbul.Instrumenter(options); instrumenter.instrument(f.code, f.name, this.async({ name : f.name, code : as(1) })); }, function write(result) { var out = outFile(result.name); grunt.verbose.writeln('instrument to ' + out); grunt.file.mkdir(path.dirname(out)); fs.writeFile(out, result.code, 'utf8', this.async(as(1))); }, function end() { flowEnd(this.err, this.next.bind(this)); }); var dateCheckFlow = flow(function checkDestExists(f) { grunt.verbose.writeln('checking destination exists ' + f.name); fs.exists(outFile(f.name), this.async({ name : f.name, exists : as(0) })); }, function readStat(f) { if (f.exists) { grunt.verbose.writeln('reading stat for ' + f.name); fs.stat(f.name, this.async({ name : f.name, stat : as(1) })); fs.stat(outFile(f.name), this.async({ name : f.name, stat : as(1) })); } else { grunt.verbose.writeln('instrumented file does not exist ' + f.name); this.end({ name : f.name, instrument : true }); } }, function decision(i, o) { var reinstrument = i.stat.mtime.getTime() > o.stat.mtime.getTime(); grunt.verbose.writeln('make a decision about instrumenting ' + i.name + ': ' + reinstrument); this.end({ name: i.name, instrument: reinstrument }); }, function end(f) { if (f.instrument) { this.exec(instFlow, { name : f.name }, this.async()); } else { flowEnd(this.err, this.next.bind(this)); } }); flow(function(filelist) { this.asyncEach(filelist, function(file, group) { this.exec((options.lazy ? dateCheckFlow : instFlow), { name : file }, group.async(as(1))); }); }, done)(files); }, storeCoverage : function(coverage, options, done) { flow(function write_json(cov) { var json = path.resolve(options.dir, options.json); grunt.file.mkdir(path.dirname(json)); fs.writeFile(json, JSON.stringify(cov), 'utf8', this.async(as(1))); }, function() { flowEnd(this.err, done); })(coverage); }, makeReport : function(files, options, done) { flow(function(filelist) { this.asyncEach(filelist, function(file, group) { grunt.verbose.writeln('read from ' + file); fs.readFile(file, 'utf8', group.async(as(1))); }); }, function report(list) { var collector = new istanbul.Collector(); list.forEach(function(json) { collector.add(JSON.parse(json)); }); makeReporters(options).forEach(function(repoDef) { var reporter = istanbul.Report.create(repoDef.type, repoDef.options); reporter.writeReport(collector, true); }); this.next(); }, function() { flowEnd(this.err, done); })(files); } }; };
import { createStore, compose } from 'redux'; import { persistState } from 'redux-devtools'; import rootReducer from '../reducers'; import DevTools from '../containers/DevTools'; const finalCreateStore = compose( DevTools.instrument(), persistState( window.location.href.match( /[?&]debug_session=([^&]+)\b/ ) ) )(createStore); export default function configureStore(initialState) { const store = finalCreateStore(rootReducer, initialState); if (module.hot) { module.hot.accept('../reducers', () => store.replaceReducer(require('../reducers')) ); } return store; }
var util = require('./util'); var observable = require('./observable'); function Component(opts) { this.opts = opts; this.tpl = opts.tpl || {}; this.el = opts.el ? $(opts.el) : undefined; this.data = opts.data || {}; this.listen = opts.listen || {}; this.events = opts.events || {}; this.handle = opts.handle || {}; this.refs = {}; this.id = util.uniqueId('component'); observable(this); this._listenTo(); this.trigger('init'); } Component.prototype.mount = function(el) { this.el = el ? $(el) : this.el; this.update(); this.trigger('mount'); return this; }; Component.prototype.update = function(data) { this.trigger('update'); this.data = data || this.data; if (this.rid) { var parentEl = this.el; var html = this._html(); var $html = $(html).attr('rid', this.rid); parentEl.append($html[0].outerHTML); this.el = parentEl.find('[rid=' + this.rid + ']'); delete this.rid; }else { this.el.empty().html(this._html()); } this._mountRefs(this); this._bindEvents(); this.trigger('updated'); }; Component.prototype.unmount = function() { this.el.empty(); this.trigger('unmount'); }; Component.prototype._html = function() { return this.tpl(this.data); }; Component.prototype._mountRefs = function(parent) { if (!this.opts.refs) { return; } for (var p in this.opts.refs) { var component; var value = this.opts.refs[p]; if (value.component) { var component = new Component(value.component); if (value.data) { component.data = value.data; } if (value.rid) { component.rid = value.rid; } component.el = $(value.el); }else { component = new Component(value); component.el = $(p); } component.parent = parent; component.mount(); this.refs[p] = component; } }; Component.prototype._bindEvents = function() { for (var e in this.events) { var handleName = this.events[e]; var $el = this.el.find(e.split(' ')[1]); $el.on(e.split(' ')[0], $.proxy(this.handle[handleName], this)); } }; Component.prototype._listenTo = function() { for (var l in this.listen) { var fn = this.listen[l]; this.on(l, fn); } }; module.exports = Component;
var Pipe = function(stream, options) { this.options = options; this._use(stream); return this; }; Pipe.prototype._use = function( stream) { if( !stream ) return; if( !this.current) { this.start = stream; this.current = stream; } else { this.current.pipe(stream); this.current = stream; } }; Pipe.prototype.select = function( path ) { var selectable = require( './io/selectV2.js').exec; this._use(selectable(path)); return this; }; Pipe.prototype.render = function( template, field ) { var render = require( './io/renderV3.js').exec; this._use( render( template, field ) ); return this; }; Pipe.prototype.dump = function( path ) { var dump = require( './io/dumpV2.js').exec; this._use( dump(path, this.options) ); return this; }; Pipe.prototype.transform = function( fnc ) { var transformator = require( './io/transform.js').exec; this._use(transformator(fnc, this.options)); return this; }; Pipe.prototype.validate = function( validateFnc, skipIfBroken ) { var fnc = require( './io/validate.js').exec; this._use( fnc(validateFnc, skipIfBroken, this.options) ); return this; }; Pipe.prototype.asArray = function() { var fnc = require( './io/asArray.js').exec; this._use( fnc() ); return this; }; Pipe.prototype.asSelectable = function() { var fnc = require( './io/asSelectable.js').exec; this._use( fnc() ); return this; }; Pipe.prototype.split = function( ) { var fnc = require( './io/split.js').exec; this._use( fnc() ); return this; }; Pipe.prototype.consume = function( obj ) { if( !this.start ) { console.log( "ILLEGAL STATE ERROR: couldn't consume, because pipe of streams is not well formed."); throw new Error(); } var stream = exports.createPipe(obj); var _ = require( 'underscore' ); if( !stream || _.isNull(stream) ) { console.log( "ILLEGAL STATE ERROR: couldn'create stream. maybe passed object is NULL or corrupt."); throw new Error(); } stream.pipe(this.start); }; /** * @param fnc */ Pipe.prototype.done = function( fnc ) { var finished = require( './io/finished.js').exec; this._use( finished(fnc) ); this.current = null; }; /** * @Deprecated * * @param fnc */ Pipe.prototype.finished = Pipe.prototype.done; exports.Pipe = Pipe; exports.createPipe = function( json ) { var _ = require("underscore"); var streams = require( 'event-stream' ); var isObject = require('./asserts/isObject').check; if( isObject(json, "Couldn't query an object-structure.") ) { return streams.readArray( [json] ); } if( _.isArray(json) ) { return streams.readArray( json ); } throw "UNSUPPORTED TYPE OF OBJECT: " + json; };
const fs = require('fs'); const request = require('superagent'); const geolib = require('geolib'); module.exports = class XBus { constructor() { this.base_url = 'http://webservices.nextbus.com/service/publicJSONFeed'; } async fetch(qs) { try { const res = await request.get(this.base_url).query(qs); return res.body; } catch (err) { console.error(err); return []; } } async getAgencies() { const qs = { command: 'agencyList' }; const res = await this.fetch(qs); return res.agency; } async getAgency(id) { const agencies = await this.getAgencies(); return agencies.find(a => a.tag === id); } async getRoutes(id) { const qs = { command: 'routeList', a: id }; const res = await this.fetch(qs); return res.route; } async getRouteConfig(id, routeId) { const qs = { command: 'routeConfig', a: id, r: routeId }; const res = await this.fetch(qs); return res.route; } async getPredictions(id, stopId) { const qs = { command: 'predictions', a: id, stopId }; const res = await this.fetch(qs); return res.predictions; } async getPredictionsWithRoute(id, stopId, routeTag) { const qs = { command: 'predictions', a: id, stopId, r: routeTag, }; const res = await this.fetch(qs); return res.predictions; } static async findDirection(routeDirection, stopTag) { const direction = {}; if (Array.isArray(routeDirection)) { const inboundRoute = routeDirection.find(d => d.name === 'Inbound'); const outboundRoute = routeDirection.find(d => d.name === 'Outbound'); if (inboundRoute.stop.find(s => s.tag === stopTag)) { direction.name = inboundRoute.name; direction.title = inboundRoute.title; } else { direction.name = outboundRoute.name; direction.title = outboundRoute.title; } } else { direction.name = routeDirection.name; direction.title = routeDirection.title; } return direction; } async getAllStops(agency) { const filepath = `./tmp/stops-${agency}.json`; const stops = []; const ids = []; // use cache if possible if (fs.existsSync(filepath)) { // console.log("we have cache for that"); return JSON.parse(fs.readFileSync(filepath)); } const routes = await this.getRoutes(agency); routes.forEach(async r => { const route = await this.getRouteConfig(agency, r.tag); route.stop.forEach(async s => { const id = s.stopId; if (ids.indexOf(id) === -1) { stops.push({ id, tag: s.tag, name: s.title, lat: s.lat, lng: s.lon, dir: await this.findDirection(route.direction, s.tag), }); } ids.push(id); }); }); // write to file for caching fs.writeFile(filepath, JSON.stringify(stops), err => { if (err) { console.error(err); } else { console.log(`file ${filepath} has been successfully written`); } }); return stops; } static async getNearbyAgencies(location = 'sf-muni') { return location; } async getNearbyStops(location, n) { const agency = await this.getNearbyAgencies(location); const stops = await this.getAllStops(agency); const nearestStops = []; const nearestStopIds = geolib.findNearest(location, stops, 0, n); nearestStopIds.forEach(stop => { nearestStops.push(stops[stop.key]); }); return nearestStops; } async getNearbyPredictions(location, n) { const plist = {}; const agency = await this.getNearbyAgencies(location); const stops = await this.getNearbyStops(location, n); // route / direction / stop / time stops.forEach(async s => { // console.log(`get predtiction for ${s.id}, ${s.tag}: ${s.name} (${s.dir.name})`); const pAtStop = await this.getPredictions(agency, s.id); const addPrediction = p => { if (p.direction) { if (!plist.hasOwnProperty(p.routeTag)) { plist[p.routeTag] = {}; plist[p.routeTag].inbound = []; plist[p.routeTag].outbound = []; } const direction = p.direction.title.startsWith('Inbound') ? 'inbound' : 'outbound'; let time; if (Array.isArray(p.direction.prediction)) { time = p.direction.prediction[0].minutes; } else { time = p.direction.prediction.minutes; } const stop = { id: s.id, tag: p.stopTag, name: p.stopTitle, time, }; plist[p.routeTag][direction].push(stop); } }; if (Array.isArray(pAtStop)) { pAtStop.forEach(p => { addPrediction(p); }); } else { addPrediction(pAtStop); } }); return plist; } };
define(['../internal/baseToString', '../internal/isIterateeCall'], function(baseToString, isIterateeCall) { /** Used to match words to create compound words. */ var reWords = (function() { var upper = '[A-Z\\xc0-\\xd6\\xd8-\\xde]', lower = '[a-z\\xdf-\\xf6\\xf8-\\xff]+'; return RegExp(upper + '{2,}(?=' + upper + lower + ')|' + upper + '?' + lower + '|' + upper + '+|[0-9]+', 'g'); }()); /** * Splits `string` into an array of its words. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to inspect. * @param {RegExp|string} [pattern] The pattern to match words. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Array} Returns the words of `string`. * @example * * _.words('fred, barney, & pebbles'); * // => ['fred', 'barney', 'pebbles'] * * _.words('fred, barney, & pebbles', /[^, ]+/g); * // => ['fred', 'barney', '&', 'pebbles'] */ function words(string, pattern, guard) { if (guard && isIterateeCall(string, pattern, guard)) { pattern = null; } string = baseToString(string); return string.match(pattern || reWords) || []; } return words; });
/** * Redraw the table (i.e. fnDraw) to take account of sorting and filtering, * but retain the current pagination settings. * @name fnStandingRedraw * @anchor fnStandingRedraw * @author Jonathan Hoguet * * @example * $(document).ready(function() { * var oTable = $('.dataTable').dataTable() * oTable.fnStandingRedraw(); * } ); */ $.fn.dataTableExt.oApi.fnStandingRedraw = function(oSettings) { if(oSettings.oFeatures.bServerSide === false){ var before = oSettings._iDisplayStart; oSettings.oApi._fnReDraw(oSettings); // iDisplayStart has been reset to zero - so lets change it back oSettings._iDisplayStart = before; oSettings.oApi._fnCalculateEnd(oSettings); } // draw the 'current' page oSettings.oApi._fnDraw(oSettings); };
//>>built define({buttonOk:"OK",buttonCancel:"Zru\u0161i\u0165",buttonSave:"Ulo\u017ei\u0165",itemClose:"Zatvori\u0165"});
(function ($) { // get window size var $window = $(window); var windowHeight = $window.height(); // update the size of window when resize $window.resize(function () { windowHeight = $window.height(); }); // define a function $.fn.parallax = function (speedFactor, outerHeight) { var $this = $(this); var getHeight; var firstTop; var paddingTop = 0; //get the starting position of each element to have parallax applied to it $this.each(function () { firstTop = $this.offset().top; }); if (outerHeight) { getHeight = function (jqo) { return jqo.outerHeight(true); }; } else { getHeight = function (jqo) { return jqo.height(); }; } // setup defaults if arguments aren't specified if (arguments.length < 1 || speedFactor === null) speedFactor = 0.1; if (arguments.length < 2 || outerHeight === null) outerHeight = true; // function to be called whenever the window/div is scrolled or resized function refresh() { var pos = $window.scrollTop(); // if your using a div wrapped with another div with overlflow:scroll and fixed width // comment above line and uncomment below. // position top alwats retugn a negative balue // var pos = -1 * ($('#content').position().top - 95); $this.each(function () { var $element = $(this); var top = $element.offset().top; var height = getHeight($element); // Check if totally above or totally below viewport if (top + height < pos || top > pos + windowHeight) { return; } // $this.css('backgroundPosition', "0px " + Math.round((firstTop - pos) * speedFactor) + "px"); // comment above and uncomment below two lines for background images. // you can set any property here to make it more dynamic $this.css('margin-top', Math.round((firstTop - pos) * speedFactor) + "px"); $this.css('position', "relative"); }); } $window.bind('scroll', refresh).resize(refresh); // if your using a div wrapped with another div with overlflow:scroll and fixed width // comment above line and uncomment below. // to use this feature you need to add https://github.com/brandonaaron/jquery-mousewheel in to your header. // $('#content').bind('mousewheel', refresh).resize(refresh); refresh(); }; })(jQuery);
var fs = require('fs'); var os = require('os'); var path = require('path'); var dirs = []; dirs.push('/usr/local/share/arduino'); dirs.push('/usr/share/arduino') if(os.platform() === 'darwin'){ dirs.push('/Applications/Arduino.app/Contents/Resources/Java'); dirs.push('/Applications/Arduino.app/Contents/Java/'); // nightly releases of arduino as of 20/07/2014 } else if(os.platform() === 'win32'){ dirs.push('C:\\Program Files (x86)\\Arduino'); dirs.push('C:\\Program Files\\Arduino'); } var ArduinoEnv = module.exports = function(){ this.rootDir = ''; this.version = ''; this.platformPath = ''; this.compilerPath = ''; this.corePath = ''; this.variantPath = ''; } ArduinoEnv.prototype.init = function(root){ this.rootDir = (root) ? root : this._locateRoot(); this.version = this.getVersion(); }; ArduinoEnv.prototype._locateRoot = function(){ var found = ''; dirs.some(function(dir){ if(fs.existsSync(dir)){ found = dir; return true; } }); return found; } ArduinoEnv.prototype.getVersion = function(){ var file = path.join(this.rootDir, 'lib', 'version.txt'); if(!fs.existsSync(file)) { return null; } var v = fs.readFileSync(file, 'utf8').toString(); // return nightly if (v.match(/nightly/)) { return '150'; } v = v.split(/\./).map(function(d){ return d.match(/[0-9]/)[0]; }); while(v.length < 3){ v.push(0); } return v.join(''); }
const { getQueryParams, } = require('./util'); function UrlParser() { for (const key of [ 'parseProvider', 'parse', 'bind', 'create', ]) { this[key] = this[key].bind(this); } this.plugins = {}; } module.exports = UrlParser; UrlParser.prototype.parseProvider = function(url) { var match = url.match( /(?:(?:https?:)?\/\/)?(?:[^.]+\.)?(\w+)\./i ); return match ? match[1] : undefined; }; UrlParser.prototype.parse = function(url) { if (typeof url === 'undefined') { return undefined; } var provider = this.parseProvider(url); var result; var plugin = this.plugins[provider]; if (!provider || !plugin || !plugin.parse) { return undefined; } result = plugin.parse.call( plugin, url, getQueryParams(url) ); if (result) { result = removeEmptyParameters(result); result.provider = plugin.provider; } return result; }; UrlParser.prototype.bind = function(plugin) { this.plugins[plugin.provider] = plugin; if (plugin.alternatives) { for (var i = 0; i < plugin.alternatives.length; i += 1) { this.plugins[plugin.alternatives[i]] = plugin; } } }; UrlParser.prototype.create = function(op) { if (typeof (op) !== 'object' || typeof (op.videoInfo) !== 'object') { return undefined; } var vi = op.videoInfo; var params = op.params; var plugin = this.plugins[vi.provider]; params = (params === 'internal') ? vi.params : params || {}; if (plugin) { op.format = op.format || plugin.defaultFormat; // eslint-disable-next-line no-prototype-builtins if (plugin.formats.hasOwnProperty(op.format)) { return plugin.formats[op.format].apply(plugin, [vi, Object.assign({}, params)]); } } return undefined; }; function removeEmptyParameters(result) { if (result.params && Object.keys(result.params).length === 0) { delete result.params; } return result; }
// Generated by CoffeeScript 1.10.0 var ISOLATION_LEVEL, OPERATION_TYPE, Transaction, WritableTrackingBuffer, isolationLevelByValue, name, value, writeAllHeaders; WritableTrackingBuffer = require('./tracking-buffer/writable-tracking-buffer'); writeAllHeaders = require('./all-headers').writeToTrackingBuffer; /* s2.2.6.8 */ OPERATION_TYPE = { TM_GET_DTC_ADDRESS: 0x00, TM_PROPAGATE_XACT: 0x01, TM_BEGIN_XACT: 0x05, TM_PROMOTE_XACT: 0x06, TM_COMMIT_XACT: 0x07, TM_ROLLBACK_XACT: 0x08, TM_SAVE_XACT: 0x09 }; ISOLATION_LEVEL = { NO_CHANGE: 0x00, READ_UNCOMMITTED: 0x01, READ_COMMITTED: 0x02, REPEATABLE_READ: 0x03, SERIALIZABLE: 0x04, SNAPSHOT: 0x05 }; isolationLevelByValue = {}; for (name in ISOLATION_LEVEL) { value = ISOLATION_LEVEL[name]; isolationLevelByValue[value] = name; } Transaction = (function () { function Transaction(name1, isolationLevel) { this.name = name1; this.isolationLevel = isolationLevel; this.outstandingRequestCount = 1; } Transaction.prototype.beginPayload = function (txnDescriptor) { var buffer, payload; buffer = new WritableTrackingBuffer(100, 'ucs2'); writeAllHeaders(buffer, txnDescriptor, this.outstandingRequestCount); buffer.writeUShort(OPERATION_TYPE.TM_BEGIN_XACT); buffer.writeUInt8(this.isolationLevel); buffer.writeUInt8(this.name.length * 2); buffer.writeString(this.name, 'ucs2'); return payload = { data: buffer.data, toString: (function (_this) { return function () { return "Begin Transaction: name=" + _this.name + ", isolationLevel=" + isolationLevelByValue[_this.isolationLevel]; }; })(this) }; }; Transaction.prototype.commitPayload = function (txnDescriptor) { var buffer, payload; buffer = new WritableTrackingBuffer(100, 'ascii'); writeAllHeaders(buffer, txnDescriptor, this.outstandingRequestCount); buffer.writeUShort(OPERATION_TYPE.TM_COMMIT_XACT); buffer.writeUInt8(this.name.length * 2); buffer.writeString(this.name, 'ucs2'); buffer.writeUInt8(0); return payload = { data: buffer.data, toString: (function (_this) { return function () { return "Commit Transaction: name=" + _this.name; }; })(this) }; }; Transaction.prototype.rollbackPayload = function (txnDescriptor) { var buffer, payload; buffer = new WritableTrackingBuffer(100, 'ascii'); writeAllHeaders(buffer, txnDescriptor, this.outstandingRequestCount); buffer.writeUShort(OPERATION_TYPE.TM_ROLLBACK_XACT); buffer.writeUInt8(this.name.length * 2); buffer.writeString(this.name, 'ucs2'); buffer.writeUInt8(0); return payload = { data: buffer.data, toString: (function (_this) { return function () { return "Rollback Transaction: name=" + _this.name; }; })(this) }; }; Transaction.prototype.savePayload = function (txnDescriptor) { var buffer, payload; buffer = new WritableTrackingBuffer(100, 'ascii'); writeAllHeaders(buffer, txnDescriptor, this.outstandingRequestCount); buffer.writeUShort(OPERATION_TYPE.TM_SAVE_XACT); buffer.writeUInt8(this.name.length * 2); buffer.writeString(this.name, 'ucs2'); return payload = { data: buffer.data, toString: (function (_this) { return function () { return "Save Transaction: name=" + _this.name; }; })(this) }; }; Transaction.prototype.isolationLevelToTSQL = function () { switch (this.isolationLevel) { case ISOLATION_LEVEL.READ_UNCOMMITTED: return 'READ UNCOMMITTED'; case ISOLATION_LEVEL.READ_COMMITTED: return 'READ COMMITTED'; case ISOLATION_LEVEL.REPEATABLE_READ: return 'REPEATABLE READ'; case ISOLATION_LEVEL.SERIALIZABLE: return 'SERIALIZABLE'; case ISOLATION_LEVEL.SNAPSHOT: return 'SNAPSHOT'; } return ''; }; return Transaction; })(); exports.Transaction = Transaction; exports.ISOLATION_LEVEL = ISOLATION_LEVEL;
import './home';
import { BufferGeometry, DynamicDrawUsage, Float32BufferAttribute, MathUtils, Uint32BufferAttribute, Vector3 } from '../../../build/three.module.js'; import { SimplexNoise } from '../math/SimplexNoise.js'; /** * @fileoverview LightningStrike object for creating lightning strikes and voltaic arcs. * * * Usage * * var myRay = new LightningStrike( paramsObject ); * var myRayMesh = new THREE.Mesh( myRay, myMaterial ); * scene.add( myRayMesh ); * ... * myRay.update( currentTime ); * * The "currentTime" can vary its rate, go forwards, backwards or even jump, but it cannot be negative. * * You should normally leave the ray position to (0, 0, 0). You should control it by changing the sourceOffset and destOffset parameters. * * * LightningStrike parameters * * The paramsObject can contain any of the following parameters. * * Legend: * 'LightningStrike' (also called 'ray'): An independent voltaic arc with its ramifications and defined with a set of parameters. * 'Subray': A ramification of the ray. It is not a LightningStrike object. * 'Segment': A linear segment piece of a subray. * 'Leaf segment': A ray segment which cannot be smaller. * * * The following parameters can be changed any time and if they vary smoothly, the ray form will also change smoothly: * * @param {Vector3} sourceOffset The point where the ray starts. * * @param {Vector3} destOffset The point where the ray ends. * * @param {double} timeScale The rate at wich the ray form changes in time. Default: 1 * * @param {double} roughness From 0 to 1. The higher the value, the more wrinkled is the ray. Default: 0.9 * * @param {double} straightness From 0 to 1. The higher the value, the more straight will be a subray path. Default: 0.7 * * @param {Vector3} up0 Ray 'up' direction at the ray starting point. Must be normalized. It should be perpendicular to the ray forward direction but it doesn't matter much. * * @param {Vector3} up1 Like the up0 parameter but at the end of the ray. Must be normalized. * * @param {double} radius0 Radius of the main ray trunk at the start point. Default: 1 * * @param {double} radius1 Radius of the main ray trunk at the end point. Default: 1 * * @param {double} radius0Factor The radius0 of a subray is this factor times the radius0 of its parent subray. Default: 0.5 * * @param {double} radius1Factor The radius1 of a subray is this factor times the radius1 of its parent subray. Default: 0.2 * * @param {minRadius} Minimum value a subray radius0 or radius1 can get. Default: 0.1 * * * The following parameters should not be changed after lightning creation. They can be changed but the ray will change its form abruptly: * * @param {boolean} isEternal If true the ray never extinguishes. Otherwise its life is controlled by the 'birthTime' and 'deathTime' parameters. Default: true if any of those two parameters is undefined. * * @param {double} birthTime The time at which the ray starts its life and begins propagating. Only if isEternal is false. Default: None. * * @param {double} deathTime The time at which the ray ends vanishing and its life. Only if isEternal is false. Default: None. * * @param {double} propagationTimeFactor From 0 to 1. Lifetime factor at which the ray ends propagating and enters the steady phase. For example, 0.1 means it is propagating 1/10 of its lifetime. Default: 0.1 * * @param {double} vanishingTimeFactor From 0 to 1. Lifetime factor at which the ray ends the steady phase and begins vanishing. For example, 0.9 means it is vanishing 1/10 of its lifetime. Default: 0.9 * * @param {double} subrayPeriod Subrays cycle periodically. This is their time period. Default: 4 * * @param {double} subrayDutyCycle From 0 to 1. This is the fraction of time a subray is active. Default: 0.6 * * * These parameters cannot change after lightning creation: * * @param {integer} maxIterations: Greater than 0. The number of ray's leaf segments is 2**maxIterations. Default: 9 * * @param {boolean} isStatic Set to true only for rays which won't change over time and are not attached to moving objects (Rare case). It is used to set the vertex buffers non-dynamic. You can omit calling update() for these rays. * * @param {integer} ramification Greater than 0. Maximum number of child subrays a subray can have. Default: 5 * * @param {integer} maxSubrayRecursion Greater than 0. Maximum level of recursion (subray descendant generations). Default: 3 * * @param {double} recursionProbability From 0 to 1. The lower the value, the less chance each new generation of subrays has to generate new subrays. Default: 0.6 * * @param {boolean} generateUVs If true, the ray geometry will have uv coordinates generated. u runs along the ray, and v across its perimeter. Default: false. * * @param {Object} randomGenerator Set here your random number generator which will seed the SimplexNoise and other decisions during ray tree creation. * It can be used to generate repeatable rays. For that, set also the noiseSeed parameter, and each ray created with that generator and seed pair will be identical in time. * The randomGenerator parameter should be an object with a random() function similar to Math.random, but seedable. * It must have also a getSeed() method, which returns the current seed, and a setSeed( seed ) method, which accepts as seed a fractional number from 0 to 1, as well as any other number. * The default value is an internal generator for some uses and Math.random for others (It is non-repeatable even if noiseSeed is supplied) * * @param {double} noiseSeed Seed used to make repeatable rays (see the randomGenerator) * * @param {function} onDecideSubrayCreation Set this to change the callback which decides subray creation. You can look at the default callback in the code (createDefaultSubrayCreationCallbacks)for more info. * * @param {function} onSubrayCreation This is another callback, more simple than the previous one. It can be used to adapt the form of subrays or other parameters once a subray has been created and initialized. It is used in the examples to adapt subrays to a sphere or to a plane. * * */ var LightningStrike = function ( rayParameters ) { BufferGeometry.call( this ); this.type = 'LightningStrike'; // Set parameters, and set undefined parameters to default values rayParameters = rayParameters || {}; this.init( LightningStrike.copyParameters( rayParameters, rayParameters ) ); // Creates and populates the mesh this.createMesh(); }; LightningStrike.prototype = Object.create( BufferGeometry.prototype ); LightningStrike.prototype.constructor = LightningStrike; LightningStrike.prototype.isLightningStrike = true; // Ray states LightningStrike.RAY_INITIALIZED = 0; LightningStrike.RAY_UNBORN = 1; LightningStrike.RAY_PROPAGATING = 2; LightningStrike.RAY_STEADY = 3; LightningStrike.RAY_VANISHING = 4; LightningStrike.RAY_EXTINGUISHED = 5; LightningStrike.COS30DEG = Math.cos( 30 * Math.PI / 180 ); LightningStrike.SIN30DEG = Math.sin( 30 * Math.PI / 180 ); LightningStrike.createRandomGenerator = function () { var numSeeds = 2053; var seeds = []; for ( var i = 0; i < numSeeds; i ++ ) { seeds.push( Math.random() ); } var generator = { currentSeed: 0, random: function () { var value = seeds[ generator.currentSeed ]; generator.currentSeed = ( generator.currentSeed + 1 ) % numSeeds; return value; }, getSeed: function () { return generator.currentSeed / numSeeds; }, setSeed: function ( seed ) { generator.currentSeed = Math.floor( seed * numSeeds ) % numSeeds; } }; return generator; }; LightningStrike.copyParameters = function ( dest, source ) { source = source || {}; dest = dest || {}; var vecCopy = function ( v ) { if ( source === dest ) { return v; } else { return v.clone(); } }; dest.sourceOffset = source.sourceOffset !== undefined ? vecCopy( source.sourceOffset ) : new Vector3( 0, 100, 0 ), dest.destOffset = source.destOffset !== undefined ? vecCopy( source.destOffset ) : new Vector3( 0, 0, 0 ), dest.timeScale = source.timeScale !== undefined ? source.timeScale : 1, dest.roughness = source.roughness !== undefined ? source.roughness : 0.9, dest.straightness = source.straightness !== undefined ? source.straightness : 0.7, dest.up0 = source.up0 !== undefined ? vecCopy( source.up0 ) : new Vector3( 0, 0, 1 ); dest.up1 = source.up1 !== undefined ? vecCopy( source.up1 ) : new Vector3( 0, 0, 1 ), dest.radius0 = source.radius0 !== undefined ? source.radius0 : 1, dest.radius1 = source.radius1 !== undefined ? source.radius1 : 1, dest.radius0Factor = source.radius0Factor !== undefined ? source.radius0Factor : 0.5, dest.radius1Factor = source.radius1Factor !== undefined ? source.radius1Factor : 0.2, dest.minRadius = source.minRadius !== undefined ? source.minRadius : 0.2, // These parameters should not be changed after lightning creation. They can be changed but the ray will change its form abruptly: dest.isEternal = source.isEternal !== undefined ? source.isEternal : ( source.birthTime === undefined || source.deathTime === undefined ), dest.birthTime = source.birthTime, dest.deathTime = source.deathTime, dest.propagationTimeFactor = source.propagationTimeFactor !== undefined ? source.propagationTimeFactor : 0.1, dest.vanishingTimeFactor = source.vanishingTimeFactor !== undefined ? source.vanishingTimeFactor : 0.9, dest.subrayPeriod = source.subrayPeriod !== undefined ? source.subrayPeriod : 4, dest.subrayDutyCycle = source.subrayDutyCycle !== undefined ? source.subrayDutyCycle : 0.6; // These parameters cannot change after lightning creation: dest.maxIterations = source.maxIterations !== undefined ? source.maxIterations : 9; dest.isStatic = source.isStatic !== undefined ? source.isStatic : false; dest.ramification = source.ramification !== undefined ? source.ramification : 5; dest.maxSubrayRecursion = source.maxSubrayRecursion !== undefined ? source.maxSubrayRecursion : 3; dest.recursionProbability = source.recursionProbability !== undefined ? source.recursionProbability : 0.6; dest.generateUVs = source.generateUVs !== undefined ? source.generateUVs : false; dest.randomGenerator = source.randomGenerator, dest.noiseSeed = source.noiseSeed, dest.onDecideSubrayCreation = source.onDecideSubrayCreation, dest.onSubrayCreation = source.onSubrayCreation; return dest; }; LightningStrike.prototype.update = function ( time ) { if ( this.isStatic ) return; if ( this.rayParameters.isEternal || ( this.rayParameters.birthTime <= time && time <= this.rayParameters.deathTime ) ) { this.updateMesh( time ); if ( time < this.subrays[ 0 ].endPropagationTime ) { this.state = LightningStrike.RAY_PROPAGATING; } else if ( time > this.subrays[ 0 ].beginVanishingTime ) { this.state = LightningStrike.RAY_VANISHING; } else { this.state = LightningStrike.RAY_STEADY; } this.visible = true; } else { this.visible = false; if ( time < this.rayParameters.birthTime ) { this.state = LightningStrike.RAY_UNBORN; } else { this.state = LightningStrike.RAY_EXTINGUISHED; } } }; LightningStrike.prototype.init = function ( rayParameters ) { // Init all the state from the parameters this.rayParameters = rayParameters; // These parameters cannot change after lightning creation: this.maxIterations = rayParameters.maxIterations !== undefined ? Math.floor( rayParameters.maxIterations ) : 9; rayParameters.maxIterations = this.maxIterations; this.isStatic = rayParameters.isStatic !== undefined ? rayParameters.isStatic : false; rayParameters.isStatic = this.isStatic; this.ramification = rayParameters.ramification !== undefined ? Math.floor( rayParameters.ramification ) : 5; rayParameters.ramification = this.ramification; this.maxSubrayRecursion = rayParameters.maxSubrayRecursion !== undefined ? Math.floor( rayParameters.maxSubrayRecursion ) : 3; rayParameters.maxSubrayRecursion = this.maxSubrayRecursion; this.recursionProbability = rayParameters.recursionProbability !== undefined ? rayParameters.recursionProbability : 0.6; rayParameters.recursionProbability = this.recursionProbability; this.generateUVs = rayParameters.generateUVs !== undefined ? rayParameters.generateUVs : false; rayParameters.generateUVs = this.generateUVs; // Random generator if ( rayParameters.randomGenerator !== undefined ) { this.randomGenerator = rayParameters.randomGenerator; this.seedGenerator = rayParameters.randomGenerator; if ( rayParameters.noiseSeed !== undefined ) { this.seedGenerator.setSeed( rayParameters.noiseSeed ); } } else { this.randomGenerator = LightningStrike.createRandomGenerator(); this.seedGenerator = Math; } // Ray creation callbacks if ( rayParameters.onDecideSubrayCreation !== undefined ) { this.onDecideSubrayCreation = rayParameters.onDecideSubrayCreation; } else { this.createDefaultSubrayCreationCallbacks(); if ( rayParameters.onSubrayCreation !== undefined ) { this.onSubrayCreation = rayParameters.onSubrayCreation; } } // Internal state this.state = LightningStrike.RAY_INITIALIZED; this.maxSubrays = Math.ceil( 1 + Math.pow( this.ramification, Math.max( 0, this.maxSubrayRecursion - 1 ) ) ); rayParameters.maxSubrays = this.maxSubrays; this.maxRaySegments = 2 * ( 1 << this.maxIterations ); this.subrays = []; for ( var i = 0; i < this.maxSubrays; i ++ ) { this.subrays.push( this.createSubray() ); } this.raySegments = []; for ( var i = 0; i < this.maxRaySegments; i ++ ) { this.raySegments.push( this.createSegment() ); } this.time = 0; this.timeFraction = 0; this.currentSegmentCallback = null; this.currentCreateTriangleVertices = this.generateUVs ? this.createTriangleVerticesWithUVs : this.createTriangleVerticesWithoutUVs; this.numSubrays = 0; this.currentSubray = null; this.currentSegmentIndex = 0; this.isInitialSegment = false; this.subrayProbability = 0; this.currentVertex = 0; this.currentIndex = 0; this.currentCoordinate = 0; this.currentUVCoordinate = 0; this.vertices = null; this.uvs = null; this.indices = null; this.positionAttribute = null; this.uvsAttribute = null; this.simplexX = new SimplexNoise( this.seedGenerator ); this.simplexY = new SimplexNoise( this.seedGenerator ); this.simplexZ = new SimplexNoise( this.seedGenerator ); // Temp vectors this.forwards = new Vector3(); this.forwardsFill = new Vector3(); this.side = new Vector3(); this.down = new Vector3(); this.middlePos = new Vector3(); this.middleLinPos = new Vector3(); this.newPos = new Vector3(); this.vPos = new Vector3(); this.cross1 = new Vector3(); }; LightningStrike.prototype.createMesh = function () { var maxDrawableSegmentsPerSubRay = 1 << this.maxIterations; var maxVerts = 3 * ( maxDrawableSegmentsPerSubRay + 1 ) * this.maxSubrays; var maxIndices = 18 * maxDrawableSegmentsPerSubRay * this.maxSubrays; this.vertices = new Float32Array( maxVerts * 3 ); this.indices = new Uint32Array( maxIndices ); if ( this.generateUVs ) { this.uvs = new Float32Array( maxVerts * 2 ); } // Populate the mesh this.fillMesh( 0 ); this.setIndex( new Uint32BufferAttribute( this.indices, 1 ) ); this.positionAttribute = new Float32BufferAttribute( this.vertices, 3 ); this.setAttribute( 'position', this.positionAttribute ); if ( this.generateUVs ) { this.uvsAttribute = new Float32BufferAttribute( new Float32Array( this.uvs ), 2 ); this.setAttribute( 'uv', this.uvsAttribute ); } if ( ! this.isStatic ) { this.index.usage = DynamicDrawUsage; this.positionAttribute.usage = DynamicDrawUsage; if ( this.generateUVs ) { this.uvsAttribute.usage = DynamicDrawUsage; } } // Store buffers for later modification this.vertices = this.positionAttribute.array; this.indices = this.index.array; if ( this.generateUVs ) { this.uvs = this.uvsAttribute.array; } }; LightningStrike.prototype.updateMesh = function ( time ) { this.fillMesh( time ); this.drawRange.count = this.currentIndex; this.index.needsUpdate = true; this.positionAttribute.needsUpdate = true; if ( this.generateUVs ) { this.uvsAttribute.needsUpdate = true; } }; LightningStrike.prototype.fillMesh = function ( time ) { var scope = this; this.currentVertex = 0; this.currentIndex = 0; this.currentCoordinate = 0; this.currentUVCoordinate = 0; this.fractalRay( time, function fillVertices( segment ) { var subray = scope.currentSubray; if ( time < subray.birthTime ) { //&& ( ! this.rayParameters.isEternal || scope.currentSubray.recursion > 0 ) ) { return; } else if ( this.rayParameters.isEternal && scope.currentSubray.recursion == 0 ) { // Eternal rays don't propagate nor vanish, but its subrays do scope.createPrism( segment ); scope.onDecideSubrayCreation( segment, scope ); } else if ( time < subray.endPropagationTime ) { if ( scope.timeFraction >= segment.fraction0 * subray.propagationTimeFactor ) { // Ray propagation has arrived to this segment scope.createPrism( segment ); scope.onDecideSubrayCreation( segment, scope ); } } else if ( time < subray.beginVanishingTime ) { // Ray is steady (nor propagating nor vanishing) scope.createPrism( segment ); scope.onDecideSubrayCreation( segment, scope ); } else { if ( scope.timeFraction <= subray.vanishingTimeFactor + segment.fraction1 * ( 1 - subray.vanishingTimeFactor ) ) { // Segment has not yet vanished scope.createPrism( segment ); } scope.onDecideSubrayCreation( segment, scope ); } } ); }; LightningStrike.prototype.addNewSubray = function ( /*rayParameters*/ ) { return this.subrays[ this.numSubrays ++ ]; }; LightningStrike.prototype.initSubray = function ( subray, rayParameters ) { subray.pos0.copy( rayParameters.sourceOffset ); subray.pos1.copy( rayParameters.destOffset ); subray.up0.copy( rayParameters.up0 ); subray.up1.copy( rayParameters.up1 ); subray.radius0 = rayParameters.radius0; subray.radius1 = rayParameters.radius1; subray.birthTime = rayParameters.birthTime; subray.deathTime = rayParameters.deathTime; subray.timeScale = rayParameters.timeScale; subray.roughness = rayParameters.roughness; subray.straightness = rayParameters.straightness; subray.propagationTimeFactor = rayParameters.propagationTimeFactor; subray.vanishingTimeFactor = rayParameters.vanishingTimeFactor; subray.maxIterations = this.maxIterations; subray.seed = rayParameters.noiseSeed !== undefined ? rayParameters.noiseSeed : 0; subray.recursion = 0; }; LightningStrike.prototype.fractalRay = function ( time, segmentCallback ) { this.time = time; this.currentSegmentCallback = segmentCallback; this.numSubrays = 0; // Add the top level subray this.initSubray( this.addNewSubray(), this.rayParameters ); // Process all subrays that are being generated until consuming all of them for ( var subrayIndex = 0; subrayIndex < this.numSubrays; subrayIndex ++ ) { var subray = this.subrays[ subrayIndex ]; this.currentSubray = subray; this.randomGenerator.setSeed( subray.seed ); subray.endPropagationTime = MathUtils.lerp( subray.birthTime, subray.deathTime, subray.propagationTimeFactor ); subray.beginVanishingTime = MathUtils.lerp( subray.deathTime, subray.birthTime, 1 - subray.vanishingTimeFactor ); var random1 = this.randomGenerator.random; subray.linPos0.set( random1(), random1(), random1() ).multiplyScalar( 1000 ); subray.linPos1.set( random1(), random1(), random1() ).multiplyScalar( 1000 ); this.timeFraction = ( time - subray.birthTime ) / ( subray.deathTime - subray.birthTime ); this.currentSegmentIndex = 0; this.isInitialSegment = true; var segment = this.getNewSegment(); segment.iteration = 0; segment.pos0.copy( subray.pos0 ); segment.pos1.copy( subray.pos1 ); segment.linPos0.copy( subray.linPos0 ); segment.linPos1.copy( subray.linPos1 ); segment.up0.copy( subray.up0 ); segment.up1.copy( subray.up1 ); segment.radius0 = subray.radius0; segment.radius1 = subray.radius1; segment.fraction0 = 0; segment.fraction1 = 1; segment.positionVariationFactor = 1 - subray.straightness; this.subrayProbability = this.ramification * Math.pow( this.recursionProbability, subray.recursion ) / ( 1 << subray.maxIterations ); this.fractalRayRecursive( segment ); } this.currentSegmentCallback = null; this.currentSubray = null; }; LightningStrike.prototype.fractalRayRecursive = function ( segment ) { // Leave recursion condition if ( segment.iteration >= this.currentSubray.maxIterations ) { this.currentSegmentCallback( segment ); return; } // Interpolation this.forwards.subVectors( segment.pos1, segment.pos0 ); var lForwards = this.forwards.length(); if ( lForwards < 0.000001 ) { this.forwards.set( 0, 0, 0.01 ); lForwards = this.forwards.length(); } var middleRadius = ( segment.radius0 + segment.radius1 ) * 0.5; var middleFraction = ( segment.fraction0 + segment.fraction1 ) * 0.5; var timeDimension = this.time * this.currentSubray.timeScale * Math.pow( 2, segment.iteration ); this.middlePos.lerpVectors( segment.pos0, segment.pos1, 0.5 ); this.middleLinPos.lerpVectors( segment.linPos0, segment.linPos1, 0.5 ); var p = this.middleLinPos; // Noise this.newPos.set( this.simplexX.noise4d( p.x, p.y, p.z, timeDimension ), this.simplexY.noise4d( p.x, p.y, p.z, timeDimension ), this.simplexZ.noise4d( p.x, p.y, p.z, timeDimension ) ); this.newPos.multiplyScalar( segment.positionVariationFactor * lForwards ); this.newPos.add( this.middlePos ); // Recursion var newSegment1 = this.getNewSegment(); newSegment1.pos0.copy( segment.pos0 ); newSegment1.pos1.copy( this.newPos ); newSegment1.linPos0.copy( segment.linPos0 ); newSegment1.linPos1.copy( this.middleLinPos ); newSegment1.up0.copy( segment.up0 ); newSegment1.up1.copy( segment.up1 ); newSegment1.radius0 = segment.radius0; newSegment1.radius1 = middleRadius; newSegment1.fraction0 = segment.fraction0; newSegment1.fraction1 = middleFraction; newSegment1.positionVariationFactor = segment.positionVariationFactor * this.currentSubray.roughness; newSegment1.iteration = segment.iteration + 1; var newSegment2 = this.getNewSegment(); newSegment2.pos0.copy( this.newPos ); newSegment2.pos1.copy( segment.pos1 ); newSegment2.linPos0.copy( this.middleLinPos ); newSegment2.linPos1.copy( segment.linPos1 ); this.cross1.crossVectors( segment.up0, this.forwards.normalize() ); newSegment2.up0.crossVectors( this.forwards, this.cross1 ).normalize(); newSegment2.up1.copy( segment.up1 ); newSegment2.radius0 = middleRadius; newSegment2.radius1 = segment.radius1; newSegment2.fraction0 = middleFraction; newSegment2.fraction1 = segment.fraction1; newSegment2.positionVariationFactor = segment.positionVariationFactor * this.currentSubray.roughness; newSegment2.iteration = segment.iteration + 1; this.fractalRayRecursive( newSegment1 ); this.fractalRayRecursive( newSegment2 ); }; LightningStrike.prototype.createPrism = function ( segment ) { // Creates one triangular prism and its vertices at the segment this.forwardsFill.subVectors( segment.pos1, segment.pos0 ).normalize(); if ( this.isInitialSegment ) { this.currentCreateTriangleVertices( segment.pos0, segment.up0, this.forwardsFill, segment.radius0, 0 ); this.isInitialSegment = false; } this.currentCreateTriangleVertices( segment.pos1, segment.up0, this.forwardsFill, segment.radius1, segment.fraction1 ); this.createPrismFaces(); }; LightningStrike.prototype.createTriangleVerticesWithoutUVs = function ( pos, up, forwards, radius ) { // Create an equilateral triangle (only vertices) this.side.crossVectors( up, forwards ).multiplyScalar( radius * LightningStrike.COS30DEG ); this.down.copy( up ).multiplyScalar( - radius * LightningStrike.SIN30DEG ); var p = this.vPos; var v = this.vertices; p.copy( pos ).sub( this.side ).add( this.down ); v[ this.currentCoordinate ++ ] = p.x; v[ this.currentCoordinate ++ ] = p.y; v[ this.currentCoordinate ++ ] = p.z; p.copy( pos ).add( this.side ).add( this.down ); v[ this.currentCoordinate ++ ] = p.x; v[ this.currentCoordinate ++ ] = p.y; v[ this.currentCoordinate ++ ] = p.z; p.copy( up ).multiplyScalar( radius ).add( pos ); v[ this.currentCoordinate ++ ] = p.x; v[ this.currentCoordinate ++ ] = p.y; v[ this.currentCoordinate ++ ] = p.z; this.currentVertex += 3; }; LightningStrike.prototype.createTriangleVerticesWithUVs = function ( pos, up, forwards, radius, u ) { // Create an equilateral triangle (only vertices) this.side.crossVectors( up, forwards ).multiplyScalar( radius * LightningStrike.COS30DEG ); this.down.copy( up ).multiplyScalar( - radius * LightningStrike.SIN30DEG ); var p = this.vPos; var v = this.vertices; var uv = this.uvs; p.copy( pos ).sub( this.side ).add( this.down ); v[ this.currentCoordinate ++ ] = p.x; v[ this.currentCoordinate ++ ] = p.y; v[ this.currentCoordinate ++ ] = p.z; uv[ this.currentUVCoordinate ++ ] = u; uv[ this.currentUVCoordinate ++ ] = 0; p.copy( pos ).add( this.side ).add( this.down ); v[ this.currentCoordinate ++ ] = p.x; v[ this.currentCoordinate ++ ] = p.y; v[ this.currentCoordinate ++ ] = p.z; uv[ this.currentUVCoordinate ++ ] = u; uv[ this.currentUVCoordinate ++ ] = 0.5; p.copy( up ).multiplyScalar( radius ).add( pos ); v[ this.currentCoordinate ++ ] = p.x; v[ this.currentCoordinate ++ ] = p.y; v[ this.currentCoordinate ++ ] = p.z; uv[ this.currentUVCoordinate ++ ] = u; uv[ this.currentUVCoordinate ++ ] = 1; this.currentVertex += 3; }; LightningStrike.prototype.createPrismFaces = function ( vertex/*, index*/ ) { var indices = this.indices; var vertex = this.currentVertex - 6; indices[ this.currentIndex ++ ] = vertex + 1; indices[ this.currentIndex ++ ] = vertex + 2; indices[ this.currentIndex ++ ] = vertex + 5; indices[ this.currentIndex ++ ] = vertex + 1; indices[ this.currentIndex ++ ] = vertex + 5; indices[ this.currentIndex ++ ] = vertex + 4; indices[ this.currentIndex ++ ] = vertex + 0; indices[ this.currentIndex ++ ] = vertex + 1; indices[ this.currentIndex ++ ] = vertex + 4; indices[ this.currentIndex ++ ] = vertex + 0; indices[ this.currentIndex ++ ] = vertex + 4; indices[ this.currentIndex ++ ] = vertex + 3; indices[ this.currentIndex ++ ] = vertex + 2; indices[ this.currentIndex ++ ] = vertex + 0; indices[ this.currentIndex ++ ] = vertex + 3; indices[ this.currentIndex ++ ] = vertex + 2; indices[ this.currentIndex ++ ] = vertex + 3; indices[ this.currentIndex ++ ] = vertex + 5; }; LightningStrike.prototype.createDefaultSubrayCreationCallbacks = function () { var random1 = this.randomGenerator.random; this.onDecideSubrayCreation = function ( segment, lightningStrike ) { // Decide subrays creation at parent (sub)ray segment var subray = lightningStrike.currentSubray; var period = lightningStrike.rayParameters.subrayPeriod; var dutyCycle = lightningStrike.rayParameters.subrayDutyCycle; var phase0 = ( lightningStrike.rayParameters.isEternal && subray.recursion == 0 ) ? - random1() * period : MathUtils.lerp( subray.birthTime, subray.endPropagationTime, segment.fraction0 ) - random1() * period; var phase = lightningStrike.time - phase0; var currentCycle = Math.floor( phase / period ); var childSubraySeed = random1() * ( currentCycle + 1 ); var isActive = phase % period <= dutyCycle * period; var probability = 0; if ( isActive ) { probability = lightningStrike.subrayProbability; // Distribution test: probability *= segment.fraction0 > 0.5 && segment.fraction0 < 0.9 ? 1 / 0.4 : 0; } if ( subray.recursion < lightningStrike.maxSubrayRecursion && lightningStrike.numSubrays < lightningStrike.maxSubrays && random1() < probability ) { var childSubray = lightningStrike.addNewSubray(); var parentSeed = lightningStrike.randomGenerator.getSeed(); childSubray.seed = childSubraySeed; lightningStrike.randomGenerator.setSeed( childSubraySeed ); childSubray.recursion = subray.recursion + 1; childSubray.maxIterations = Math.max( 1, subray.maxIterations - 1 ); childSubray.linPos0.set( random1(), random1(), random1() ).multiplyScalar( 1000 ); childSubray.linPos1.set( random1(), random1(), random1() ).multiplyScalar( 1000 ); childSubray.up0.copy( subray.up0 ); childSubray.up1.copy( subray.up1 ); childSubray.radius0 = segment.radius0 * lightningStrike.rayParameters.radius0Factor; childSubray.radius1 = Math.min( lightningStrike.rayParameters.minRadius, segment.radius1 * lightningStrike.rayParameters.radius1Factor ); childSubray.birthTime = phase0 + ( currentCycle ) * period; childSubray.deathTime = childSubray.birthTime + period * dutyCycle; if ( ! lightningStrike.rayParameters.isEternal && subray.recursion == 0 ) { childSubray.birthTime = Math.max( childSubray.birthTime, subray.birthTime ); childSubray.deathTime = Math.min( childSubray.deathTime, subray.deathTime ); } childSubray.timeScale = subray.timeScale * 2; childSubray.roughness = subray.roughness; childSubray.straightness = subray.straightness; childSubray.propagationTimeFactor = subray.propagationTimeFactor; childSubray.vanishingTimeFactor = subray.vanishingTimeFactor; lightningStrike.onSubrayCreation( segment, subray, childSubray, lightningStrike ); lightningStrike.randomGenerator.setSeed( parentSeed ); } }; var vec1Pos = new Vector3(); var vec2Forward = new Vector3(); var vec3Side = new Vector3(); var vec4Up = new Vector3(); this.onSubrayCreation = function ( segment, parentSubray, childSubray, lightningStrike ) { // Decide childSubray origin and destination positions (pos0 and pos1) and possibly other properties of childSubray // Just use the default cone position generator lightningStrike.subrayCylinderPosition( segment, parentSubray, childSubray, 0.5, 0.6, 0.2 ); }; this.subrayConePosition = function ( segment, parentSubray, childSubray, heightFactor, sideWidthFactor, minSideWidthFactor ) { // Sets childSubray pos0 and pos1 in a cone childSubray.pos0.copy( segment.pos0 ); vec1Pos.subVectors( parentSubray.pos1, parentSubray.pos0 ); vec2Forward.copy( vec1Pos ).normalize(); vec1Pos.multiplyScalar( segment.fraction0 + ( 1 - segment.fraction0 ) * ( random1() * heightFactor ) ); var length = vec1Pos.length(); vec3Side.crossVectors( parentSubray.up0, vec2Forward ); var angle = 2 * Math.PI * random1(); vec3Side.multiplyScalar( Math.cos( angle ) ); vec4Up.copy( parentSubray.up0 ).multiplyScalar( Math.sin( angle ) ); childSubray.pos1.copy( vec3Side ).add( vec4Up ).multiplyScalar( length * sideWidthFactor * ( minSideWidthFactor + random1() * ( 1 - minSideWidthFactor ) ) ).add( vec1Pos ).add( parentSubray.pos0 ); }; this.subrayCylinderPosition = function ( segment, parentSubray, childSubray, heightFactor, sideWidthFactor, minSideWidthFactor ) { // Sets childSubray pos0 and pos1 in a cylinder childSubray.pos0.copy( segment.pos0 ); vec1Pos.subVectors( parentSubray.pos1, parentSubray.pos0 ); vec2Forward.copy( vec1Pos ).normalize(); vec1Pos.multiplyScalar( segment.fraction0 + ( 1 - segment.fraction0 ) * ( ( 2 * random1() - 1 ) * heightFactor ) ); var length = vec1Pos.length(); vec3Side.crossVectors( parentSubray.up0, vec2Forward ); var angle = 2 * Math.PI * random1(); vec3Side.multiplyScalar( Math.cos( angle ) ); vec4Up.copy( parentSubray.up0 ).multiplyScalar( Math.sin( angle ) ); childSubray.pos1.copy( vec3Side ).add( vec4Up ).multiplyScalar( length * sideWidthFactor * ( minSideWidthFactor + random1() * ( 1 - minSideWidthFactor ) ) ).add( vec1Pos ).add( parentSubray.pos0 ); }; }; LightningStrike.prototype.createSubray = function () { return { seed: 0, maxIterations: 0, recursion: 0, pos0: new Vector3(), pos1: new Vector3(), linPos0: new Vector3(), linPos1: new Vector3(), up0: new Vector3(), up1: new Vector3(), radius0: 0, radius1: 0, birthTime: 0, deathTime: 0, timeScale: 0, roughness: 0, straightness: 0, propagationTimeFactor: 0, vanishingTimeFactor: 0, endPropagationTime: 0, beginVanishingTime: 0 }; }; LightningStrike.prototype.createSegment = function () { return { iteration: 0, pos0: new Vector3(), pos1: new Vector3(), linPos0: new Vector3(), linPos1: new Vector3(), up0: new Vector3(), up1: new Vector3(), radius0: 0, radius1: 0, fraction0: 0, fraction1: 0, positionVariationFactor: 0 }; }; LightningStrike.prototype.getNewSegment = function () { return this.raySegments[ this.currentSegmentIndex ++ ]; }; LightningStrike.prototype.copy = function ( source ) { BufferGeometry.prototype.copy.call( this, source ); this.init( LightningStrike.copyParameters( {}, source.rayParameters ) ); return this; }; LightningStrike.prototype.clone = function () { return new this.constructor( LightningStrike.copyParameters( {}, this.rayParameters ) ); }; export { LightningStrike };
'use strict'; angular.module('users').controller('ProfileController', ['$scope', '$location', 'Authentication', '$http', '$stateParams', 'Boards', '$window', function($scope, $location, Authentication, $http, $stateParams, Boards, $window) { $scope.authentication = Authentication; // If user is not signed in then redirect to signin page if (!$scope.authentication.user) $location.path('/signin'); if ($scope.authentication.user) { if ($scope.authentication.user.gender === 'male') $scope.gender = 'M'; else if ($scope.authentication.user.gender === 'female') $scope.gender = 'F'; } $scope.loadOtherProfile = function () { $http.get('/users/' + $stateParams.username).success(function(response) { $scope.user = response; if ($scope.user.gender === 'male') { $scope.othergender = 'M'; } else if ($scope.user.gender === 'female') $scope.othergender = 'F'; $http.get('/boards/user/' + $stateParams.username).success(function (response) { $scope.postBadgeCount = response.postBadge; if (response.postBadge === 1) { $scope.postBadge = 'Participant Badge'; } else if (response.postBadge === 2) { $scope.postBadge = 'Chatter Badge'; } else if (response.postBadge === 3) { $scope.postBadge = 'Socialite Badge'; } updateTotalBadge(); }); $http.get('/transactions/user/' + $stateParams.username).success(function (response) { $scope.shopBadgeCount = response.shopBadge; $scope.donationBadgeCount = response.donationBadge; if (response.shopBadge === 1) { $scope.shopBadge = 'Shopper Badge'; } else if (response.shopBadge === 2) { $scope.shopBadge = 'Promoter Badge'; } else if (response.shopBadge === 3) { $scope.shopBadge = 'Elite Badge'; } if (response.donationBadge === 1) { $scope.donationBadge = 'Supporter Badge'; } else if (response.donationBadge === 2) { $scope.donationBadge = 'Contributor Badge'; } else if (response.donationBadge === 3) { $scope.donationBadge = 'Pillar Badge'; } updateTotalBadge(); }); }); }; // $scope.loadProfile = function () { $http.get('/boards/user').success(function (response) { $scope.postBadgeCount = response.postBadge; if (response.postBadge === 1) { $scope.postBadge = 'Participant Badge'; } else if (response.postBadge === 2) { $scope.postBadge = 'Chatter Badge'; } else if (response.postBadge === 3) { $scope.postBadge = 'Socialite Badge'; } updateTotalBadge(); }); $http.get('/transactions/user').success(function (response) { $scope.shopBadgeCount = response.shopBadge; $scope.donationBadgeCount = response.donationBadge; if (response.shopBadge === 1) { $scope.shopBadge = 'Shopper Badge'; } else if (response.shopBadge === 2) { $scope.shopBadge = 'Promoter Badge'; } else if (response.shopBadge === 3) { $scope.shopBadge = 'Elite Badge'; } if (response.donationBadge === 1) { $scope.donationBadge = 'Supporter Badge'; } else if (response.donationBadge === 2) { $scope.donationBadge = 'Contributor Badge'; } else if (response.donationBadge === 3) { $scope.donationBadge = 'Pillar Badge'; } updateTotalBadge(); }); }; function updateTotalBadge() { if ($scope.postBadgeCount >= 1 && $scope.shopBadgeCount >= 1 && $scope.donationBadgeCount >= 1) { $scope.badgeCollection = 'Explorer Badge'; if ($scope.donationBadgeCount >= 2 && $scope.shopBadgeCount >= 2) { $scope.badgeCollection = 'Backer Badge'; } } if ($scope.postBadgeCount === 3 && $scope.shopBadgeCount === 3 && $scope.donationBadgeCount === 3) { $scope.badgeCollection = 'Evangelist Badge'; } } } ]);
/* eslint-disable no-unused-expressions */ import TcpSocket from './windows-socket' describe('TCPSocket Windows Stream Socket unit tests', function () { var socket before(() => { global.Windows = { Networking: { HostName: function (hostname) { this.type = hostname this.hostname = hostname }, Sockets: { StreamSocket: function () { this.control = {} this.inputStream = { type: 'inputStream' } this.outputStream = { type: 'outputStream' } this.connectAsync = (host, port, protection) => { this.host = host this.port = port this.protection = protection return { done: successCb => setImmediate(successCb) } } }, SocketProtectionLevel: { plainSocket: 1, tls12: 2 } } }, Storage: { Streams: { DataReader: function (stream) { this.type = 'DataReader' this.stream = stream this.inputStreamOptions = false this._bytes = false this.loadAsync = () => ({ done: successCb => setImmediate(() => successCb((this._bytes && this._bytes.length) || 0)) }) this.readBytes = target => { for (let i = 0, len = this._bytes.length; i < len; i++) { target[i] = this._bytes[i] } this._bytes = false } }, DataWriter: function (stream) { this.type = 'DataWriter' this.stream = stream this.inputStreamOptions = false this._bytes = false this.writeBytes = data => { this._bytes = data } this.storeAsync = () => ({ done: successCb => setImmediate(successCb) }) }, InputStreamOptions: { partial: 3 } } } } }) beforeEach(function (done) { socket = TcpSocket.open('127.0.0.1', 9000, { useSecureTransport: false }) expect(socket).to.exist socket.onopen = function () { done() } }) describe('open and read', function () { it('should read data from socket', function (done) { socket.ondata = function (e) { expect(new Uint8Array(e.data)).to.deep.equal(new Uint8Array([0, 1, 2])) socket.close() } socket.onclose = () => done() socket._dataReader._bytes = new Uint8Array([0, 1, 2]) }) }) describe('close', function () { it('should work', function (done) { socket.onclose = function () { expect(socket.readyState).to.equal('closed') done() } socket.close() }) }) describe('send', function () { it('should send data to socket', function (done) { socket.ondrain = function () { socket.close() } socket.onclose = () => done() socket.send(new Uint8Array([0, 1, 2]).buffer) }) }) })
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('property-value', 'Integration | Component | property value', { integration: true }); test('it renders', function(assert) { // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... });" this.render(hbs`{{property-value}}`); assert.equal(this.$().text().trim(), ''); // Template block usage:" this.render(hbs` {{#property-value}} template block text {{/property-value}} `); assert.equal(this.$().text().trim(), 'template block text'); });
const AbstractBinding = require('@serialport/binding-abstract') const debug = require('debug')('serialport/binding-mock') const { wrapWithHiddenComName } = require('./legacy') let ports = {} let serialNumber = 0 function resolveNextTick(value) { return new Promise(resolve => process.nextTick(() => resolve(value))) } const cancelError = message => { const err = new Error(message) err.canceled = true return err } /** * Mock bindings for pretend serialport access */ class MockBinding extends AbstractBinding { constructor(opt = {}) { super(opt) this.pendingRead = null // thunk for a promise or null this.isOpen = false this.port = null this.lastWrite = null this.recording = Buffer.alloc(0) this.writeOperation = null // in flight promise or null } // Reset mocks static reset() { ports = {} serialNumber = 0 } // Create a mock port static createPort(path, opt) { serialNumber++ opt = { echo: false, record: false, readyData: Buffer.from('READY'), manufacturer: 'The J5 Robotics Company', vendorId: undefined, productId: undefined, ...opt, } ports[path] = { data: Buffer.alloc(0), echo: opt.echo, record: opt.record, readyData: Buffer.from(opt.readyData), info: { path, manufacturer: opt.manufacturer, serialNumber, pnpId: undefined, locationId: undefined, vendorId: opt.vendorId, productId: opt.productId, }, } debug(serialNumber, 'created port', JSON.stringify({ path, opt })) } static async list() { return wrapWithHiddenComName(Object.values(ports).map(port => port.info)) } // Emit data on a mock port emitData(data) { if (!this.isOpen) { throw new Error('Port must be open to pretend to receive data') } if (!Buffer.isBuffer(data)) { data = Buffer.from(data) } debug(this.serialNumber, 'emitting data - pending read:', Boolean(this.pendingRead)) this.port.data = Buffer.concat([this.port.data, data]) if (this.pendingRead) { process.nextTick(this.pendingRead) this.pendingRead = null } } async open(path, opt) { debug(null, `opening path ${path}`) const port = (this.port = ports[path]) await super.open(path, opt) await resolveNextTick() if (!port) { throw new Error(`Port does not exist - please call MockBinding.createPort('${path}') first`) } this.serialNumber = port.info.serialNumber if (port.openOpt && port.openOpt.lock) { throw new Error('Port is locked cannot open') } if (this.isOpen) { throw new Error('Open: binding is already open') } port.openOpt = { ...opt } this.isOpen = true debug(this.serialNumber, 'port is open') if (port.echo) { process.nextTick(() => { if (this.isOpen) { debug(this.serialNumber, 'emitting ready data') this.emitData(port.readyData) } }) } } async close() { const port = this.port debug(this.serialNumber, 'closing port') if (!port) { throw new Error('already closed') } await super.close() delete port.openOpt // reset data on close port.data = Buffer.alloc(0) debug(this.serialNumber, 'port is closed') delete this.port delete this.serialNumber this.isOpen = false if (this.pendingRead) { this.pendingRead(cancelError('port is closed')) } } async read(buffer, offset, length) { debug(this.serialNumber, 'reading', length, 'bytes') await super.read(buffer, offset, length) await resolveNextTick() if (!this.isOpen) { throw cancelError('Read canceled') } if (this.port.data.length <= 0) { return new Promise((resolve, reject) => { this.pendingRead = err => { if (err) { return reject(err) } this.read(buffer, offset, length).then(resolve, reject) } }) } const data = this.port.data.slice(0, length) const bytesRead = data.copy(buffer, offset) this.port.data = this.port.data.slice(length) debug(this.serialNumber, 'read', bytesRead, 'bytes') return { bytesRead, buffer } } async write(buffer) { debug(this.serialNumber, 'writing') if (this.writeOperation) { throw new Error('Overlapping writes are not supported and should be queued by the serialport object') } this.writeOperation = super.write(buffer).then(async () => { await resolveNextTick() if (!this.isOpen) { throw new Error('Write canceled') } const data = (this.lastWrite = Buffer.from(buffer)) // copy if (this.port.record) { this.recording = Buffer.concat([this.recording, data]) } if (this.port.echo) { process.nextTick(() => { if (this.isOpen) { this.emitData(data) } }) } this.writeOperation = null debug(this.serialNumber, 'writing finished') }) return this.writeOperation } async update(opt) { await super.update(opt) await resolveNextTick() this.port.openOpt.baudRate = opt.baudRate } async set(opt) { await super.set(opt) await resolveNextTick() } async get() { await super.get() await resolveNextTick() return { cts: true, dsr: false, dcd: false, } } async getBaudRate() { await super.getBaudRate() await resolveNextTick() return { baudRate: this.port.openOpt.baudRate, } } async flush() { await super.flush() await resolveNextTick() this.port.data = Buffer.alloc(0) } async drain() { await super.drain() await this.writeOperation await resolveNextTick() } } module.exports = MockBinding
let List = require( './list' ), notes = new Array(); class NotesController extends List { constructor() { super( notes ); } } module.exports = NotesController;
import React, { Component } from 'react'; import './App.css'; import Nav from './components/navigation'; class App extends Component { render() { return ( <div className="App"> <Nav /> </div > ); } } export default App;
'use strict'; var util = require( '../../../util' ); var fullFpsTime = 1000/60; // assume 60 frames per second module.exports = { setupDequeueing: function( opts ){ return function setupDequeueingImpl(){ var self = this; var r = this.renderer; if( self.dequeueingSetup ){ return; } else { self.dequeueingSetup = true; } var queueRedraw = util.debounce( function(){ r.redrawHint( 'eles', true ); r.redrawHint( 'drag', true ); r.redraw(); }, opts.deqRedrawThreshold ); var dequeue = function( willDraw, frameStartTime ){ var startTime = util.performanceNow(); var avgRenderTime = r.averageRedrawTime; var renderTime = r.lastRedrawTime; var deqd = []; var extent = r.cy.extent(); var pixelRatio = r.getPixelRatio(); while( true ){ var now = util.performanceNow(); var duration = now - startTime; var frameDuration = now - frameStartTime; if( renderTime < fullFpsTime ){ // if we're rendering faster than the ideal fps, then do dequeueing // during all of the remaining frame time var timeAvailable = fullFpsTime - ( willDraw ? avgRenderTime : 0 ); if( frameDuration >= opts.deqFastCost * timeAvailable ){ break; } } else { if( willDraw ){ if( duration >= opts.deqCost * renderTime || duration >= opts.deqAvgCost * avgRenderTime ){ break; } } else if( frameDuration >= opts.deqNoDrawCost * fullFpsTime ){ break; } } var thisDeqd = opts.deq( self, pixelRatio, extent ); if( thisDeqd.length > 0 ){ for( var i = 0; i < thisDeqd.length; i++ ){ deqd.push( thisDeqd[i] ); } } else { break; } } // callbacks on dequeue if( deqd.length > 0 ){ opts.onDeqd( self, deqd ); if( !willDraw && opts.shouldRedraw( self, deqd, pixelRatio, extent ) ){ queueRedraw(); } } }; var priority = opts.priority || util.noop; r.beforeRender( dequeue, priority( self ) ); }; } };
"use strict"; const cheerio = require("cheerio"); const semver = require("semver"); const scraper = require("./scraper"); const RELEASE = /^v\d+\.\d+\.\d+\/$/; const MIN_VERSION = process.env.MIN_NW_VERSION || "0.13.0"; scraper("http://dl.nwjs.io/") .then(function(body) { const $ = cheerio.load(body); const versions = $("a") .map(function(i, link) { return $(link).text(); }) .get() .filter(function(version) { return RELEASE.test(version); }) .map(function(version) { return version.replace("v", "").replace("/", ""); }) .filter(function(version) { return semver.gte(version, MIN_VERSION); }); versions.forEach(function(version) { console.log(version); }) });
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "m17.66 17.66-1.06 1.06-.71-.71 1.06-1.06-1.94-1.94-1.06 1.06-.71-.71 1.06-1.06-1.94-1.94-1.06 1.06-.71-.71 1.06-1.06L9.7 9.7l-1.06 1.06-.71-.71 1.06-1.06-1.94-1.94-1.06 1.06-.71-.71 1.06-1.06L4 4v14c0 1.1.9 2 2 2h14l-2.34-2.34zM7 17v-5.76L12.76 17H7z" }), 'SquareFoot'); exports.default = _default;
define( function (require) { var lang = {}; lang.inherits = function (subClass, superClass) { var Empty = function () {}; Empty.prototype = superClass.prototype; var selfPrototype = subClass.prototype; var proto = subClass.prototype = new Empty(); for (var key in selfPrototype) { proto[key] = selfPrototype[key]; } subClass.prototype.constructor = subClass; subClass.superClass = superClass.prototype; return subClass; }; lang.clone = function (source) { if (!source || typeof source !== 'object') { return source; } var result = source; if (u.isArray(source)) { result = u.clone(source); } else if (({}).toString.call(source) === '[object Object]' && ('isPrototypeOf' in source)) { result = {}; for (var key in source) { if (source.hasOwnProperty(key)) { result[key] = lib.deepClone(source[key]); } } } return result; }; lang.extend = function(target,source){ for (var pro in source) { if (source.hasOwnProperty(pro) && typeof source[pro] != "undefined") { target[pro] = source[pro]; } } return target; }; return lang; } );
var log = console.log, app = require('koa')(), koaBody = require('../index'), port = process.env.PORT || 4290, host = 'http://localhost'; app .use(koaBody({ multipart: true, formLimit: 15, formidable: { uploadDir: __dirname + '/uploads' } })) .use(function *(next) { if (this.request.method == 'POST') { log(this.request.body); // => POST body object this.body = JSON.stringify(this.request.body, null, 2); } yield next; }) .listen(port); log('Visit %s:%s/ in browser.', host, port); log(); log('Test with executing this commands:'); log('curl -i %s:%s/whatever -d "name=charlike"', host, port); log('curl -i %s:%s/whatever -d "name=some-long-name-for-error"', host, port); log('curl -i %s:%s/whatever -F "source=@%s/avatar.png"', host, port, __dirname); log(); log('Press CTRL+C to stop...');
//>>built define(["dojo/_base/declare"],function(b){return b(null,{postMixInProperties:function(){this.textDir=this.params.textDir?this.params.textDir:this.params.dir},_setTextDirAttr:function(a){null!=(/^(ltr|rtl|auto)$/.test(a)?a:null)&&(this._set("textDir",a),this.chart.setTextDir(a))},_setDirAttr:function(a){this._set("dir",a);this.chart.setDir(a)}})});
define( [ 'react', 'create-react-class', 'jquery', ], function (React, createReactClass,$){ var ContainerThree = createReactClass({ render: function(){ var style = { position: 'relative', height: '250px', width: 'auto', overflow: 'hidden' }; //style="overflow: hidden; width: auto; height: 250px;" return ( <div className="box box-primary"> <div className="box-header ui-sortable-handle"> <i className="ion ion-clipboard"></i> <h3 className="box-title">To Do List</h3> <div className="box-tools pull-right"> <ul className="pagination pagination-sm inline"> <li><a href="#">«</a></li> <li><a href="#">1</a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">»</a></li> </ul> </div> </div> <div className="box-body" > <ul className="todo-list ui-sortable"> </ul> </div> </div> ) } }) return ContainerThree; } )
/* * * This example demonstrates how to add existing device to collection * * API Documentation: * https://m2x.att.com/developer/documentation/v2/collections#Add-device-to-collection */ var config = require("./config"); var M2X = require("../lib/m2x"); var m2x_client = new M2X(config.api_key); var DeviceId = config.device; var CollectionId = config.collectionId; console.log("Adding Device to Collection..."); m2x_client.collections.addDeviceToCollection(CollectionId, DeviceId, function(response) { if (response.isSuccess()) { console.log("Status Code: ".concat(response.status)); console.log("Device Added to Collection Successfully."); } else { console.log(JSON.stringify(response.error())); console.log("Device not Added to Collection.Please Try Again.."); } });
/*jslint unparam: true, browser: true, indent: 2 */ ;(function ($, window, document, undefined) { 'use strict'; Foundation.libs.section = { name: 'section', version : '4.0.5', settings : { deep_linking: false, one_up: true, callback: function (){} }, init : function (scope, method, options) { this.scope = scope || this.scope; Foundation.inherit(this, 'throttle data_options'); if (typeof method === 'object') { $.extend(true, this.settings, method); } if (typeof method != 'string') { this.set_active_from_hash(); if (!this.settings.init) this.events(); return this.settings.init; } else { return this[method].call(this, options); } }, events : function () { var self = this; $(this.scope).on('click.fndtn.section', '[data-section] .title', function (e) { $.extend(true, self.settings, self.data_options($(this).closest('[data-section]'))); self.toggle_active.call(this, e, self); }); $(window).on('resize.fndtn.section', self.throttle(function () { self.resize.call(this); }, 30)) .on('hashchange', function () { if (!self.settings.toggled){ self.set_active_from_hash(); $(this).trigger('resize'); } }).trigger('resize'); $(document).on('click.fndtn.section', function (e) { if ($(e.target).closest('.title').length < 1) { $('[data-section].vertical-nav, [data-section].horizontal-nav') .find('section, .section') .removeClass('active') .attr('style', ''); } }); this.settings.init = true; }, toggle_active : function (e, self) { var $this = $(this), section = $this.closest('section, .section'), content = section.find('.content'), parent = section.closest('[data-section]'), self = Foundation.libs.section; self.settings.toggled = true; if (!self.settings.deep_linking && content.length > 0) { e.preventDefault(); } if (section.hasClass('active')) { if (self.small(parent) || self.is_vertical(parent) || self.is_horizontal(parent) || self.is_accordion(parent)) { section .removeClass('active') .attr('style', ''); } } else { var prev_active_section = null, title_height = self.outerHeight(section.find('.title')); if (self.small(parent) || self.settings.one_up) { prev_active_section = $this.closest('[data-section]').find('section.active, .section.active'); if (self.small(parent)) { prev_active_section.attr('style', ''); } else { prev_active_section.attr('style', 'visibility: hidden; padding-top: '+title_height+'px;'); } } if (self.small(parent)) { section.attr('style', ''); } else { section.css('padding-top', title_height); } section.addClass('active'); if (prev_active_section !== null) { prev_active_section.removeClass('active').attr('style', ''); } } setTimeout(function () { self.settings.toggled = false; }, 300); self.settings.callback(); }, resize : function () { var sections = $('[data-section]'), self = Foundation.libs.section; sections.each(function() { var $this = $(this), active_section = $this.find('section.active, .section.active'); if (active_section.length > 1) { active_section .not(':first') .removeClass('active') .attr('style', ''); } else if (active_section.length < 1 && !self.is_vertical($this) && !self.is_horizontal($this) && !self.is_accordion($this)) { var first = $this.find('section, .section').first(); first.addClass('active'); if (self.small($this)) { first.attr('style', ''); } else { first.css('padding-top', self.outerHeight(first.find('.title'))); } } if (self.small($this)) { active_section.attr('style', ''); } else { active_section.css('padding-top', self.outerHeight(active_section.find('.title'))); } self.position_titles($this); if (self.is_horizontal($this) && !self.small($this)) { self.position_content($this); } else { self.position_content($this, false); } }); }, is_vertical : function (el) { return el.hasClass('vertical-nav'); }, is_horizontal : function (el) { return el.hasClass('horizontal-nav'); }, is_accordion : function (el) { return el.hasClass('accordion'); }, set_active_from_hash : function () { var hash = window.location.hash.substring(1), sections = $('[data-section]'), self = this; sections.each(function () { var section = $(this); $.extend(true, self.settings, self.data_options(section)); if (hash.length > 0 && self.settings.deep_linking) { section .find('section, .section') .attr('style', '') .removeClass('active'); section .find('.content[data-slug="' + hash + '"]') .closest('section, .section') .addClass('active'); } }); }, position_titles : function (section, off) { var titles = section.find('.title'), previous_width = 0, self = this; if (typeof off === 'boolean') { titles.attr('style', ''); } else { titles.each(function () { $(this).css('left', previous_width); previous_width += self.outerWidth($(this)); }); } }, position_content : function (section, off) { var titles = section.find('.title'), content = section.find('.content'), self = this; if (typeof off === 'boolean') { content.attr('style', ''); section.attr('style', ''); } else { section.find('section, .section').each(function () { var title = $(this).find('.title'), content = $(this).find('.content'); content.css({left: title.position().left - 1, top: self.outerHeight(title) - 2}); }); // temporary work around for Zepto outerheight calculation issues. if (typeof Zepto === 'function') { section.height(this.outerHeight(titles.first())); } else { section.height(this.outerHeight(titles.first()) - 2); } } }, small : function (el) { if (el && this.is_accordion(el)) { return true; } if ($('html').hasClass('lt-ie9')) { return true; } if ($('html').hasClass('ie8compat')) { return true; } return $(this.scope).width() < 768; }, off : function () { $(this.scope).off('.fndtn.section'); $(window).off('.fndtn.section'); this.settings.init = false; } }; }(Foundation.zj, this, this.document));
var engine = require('./lib/engine'), importPipe = require('./lib/import-pipe'); exports.run = engine.run; exports.importPipe = importPipe.importPipe; exports.fetchPipe = importPipe.fetchPipe; exports.pipe2decider = importPipe.pipe2decider; exports.conf2input = importPipe.conf2input; exports.pathsForTerminals = importPipe.pathsForTerminals;
/* globals require, process, global, module */ /************************************************************* * Variables ************************************************************/ // Modules var exec = require('child_process').exec; // Globals var gulp = global.gulp; function sh(cmd, exitOnError, cb) { var child = exec(cmd, {encoding: 'utf8'}); var stdout = ''; var stderr = ''; child.stdout.on('data', function (data) { stdout += data; process.stdout.write(data); }); child.stderr.on('data', function (data) { stderr += data; process.stdout.write(data); }); child.on('close', function (code) { if (code > 0) { console.log('Error with code ' + code + ' after running: ' + cmd); if (exitOnError) { process.exit(code); } else { gulp.$.notify({ title: cmd, message: stdout, sound: true, }); } } cb(); }); } module.exports = sh;
({ baseUrl: ".", paths: { jquery: "jquery/jquery.min.js" }, name: "app", out: "main.js" })
var gulp = require('gulp'); var paths = require('../paths'); var browserSync = require('browser-sync'); // outputs changes to files to the console function reportChange(event){ console.log('File ' + event.path + ' was ' + event.type + ', running tasks...'); } // this task will watch for changes // to js, html, and css files and call the // reportChange method. Also, by depending on the // serve task, it will instantiate a browserSync session gulp.task('watch', ['serve'], function() { gulp.watch(paths.tsSource, ['build-system', browserSync.reload]).on('change', reportChange); gulp.watch(paths.html, ['build-html', browserSync.reload]).on('change', reportChange); gulp.watch(paths.style, browserSync.reload).on('change', reportChange); });
var Bindings = require("../bindings"); describe("observe sorted set", function () { it("should work", function () { var a = {name: 'a', index: 0}; var b = {name: 'b', index: 0}; var c = {name: 'c', index: 0}; var d = {name: 'd', index: 0}; var array = [a, b, c, d]; var object = Bindings.defineBindings({ array: array }, { "sortedSet": {"<-": "array.sortedSet{index}"} }); expect(object.sortedSet.toArray()).toEqual([d]); d.index = 3; expect(object.sortedSet.toArray()).toEqual([c, d]); c.index = 2; expect(object.sortedSet.toArray()).toEqual([b, c, d]); b.index = 1; expect(object.sortedSet.toArray()).toEqual([a, b, c, d]); a.index = 4; expect(object.sortedSet.toArray()).toEqual([b, c, d, a]); b.index = 4; expect(object.sortedSet.toArray()).toEqual([c, d, b]); }); });
/*! * Ext JS Library 3.1.1 * Copyright(c) 2006-2010 Ext JS, LLC * licensing@extjs.com * http://www.extjs.com/license */ if(typeof jQuery == "undefined"){ throw "Unable to load Ext, jQuery not found."; } (function(){ var libFlyweight; Ext.lib.Dom = { getViewWidth : function(full){ // jQuery doesn't report full window size on document query, so max both return full ? Math.max(jQuery(document).width(),jQuery(window).width()) : jQuery(window).width(); }, getViewHeight : function(full){ // jQuery doesn't report full window size on document query, so max both return full ? Math.max(jQuery(document).height(),jQuery(window).height()) : jQuery(window).height(); }, isAncestor : function(p, c){ var ret = false; p = Ext.getDom(p); c = Ext.getDom(c); if (p && c) { if (p.contains) { return p.contains(c); } else if (p.compareDocumentPosition) { return !!(p.compareDocumentPosition(c) & 16); } else { while (c = c.parentNode) { ret = c == p || ret; } } } return ret; }, getRegion : function(el){ return Ext.lib.Region.getRegion(el); }, ////////////////////////////////////////////////////////////////////////////////////// // Use of jQuery.offset() removed to promote consistent behavior across libs. // JVS 05/23/07 ////////////////////////////////////////////////////////////////////////////////////// getY : function(el){ return this.getXY(el)[1]; }, getX : function(el){ return this.getXY(el)[0]; }, getXY : function(el) { var p, pe, b, scroll, bd = (document.body || document.documentElement); el = Ext.getDom(el); if(el == bd){ return [0, 0]; } if (el.getBoundingClientRect) { b = el.getBoundingClientRect(); scroll = fly(document).getScroll(); return [Math.round(b.left + scroll.left), Math.round(b.top + scroll.top)]; } var x = 0, y = 0; p = el; var hasAbsolute = fly(el).getStyle("position") == "absolute"; while (p) { x += p.offsetLeft; y += p.offsetTop; if (!hasAbsolute && fly(p).getStyle("position") == "absolute") { hasAbsolute = true; } if (Ext.isGecko) { pe = fly(p); var bt = parseInt(pe.getStyle("borderTopWidth"), 10) || 0; var bl = parseInt(pe.getStyle("borderLeftWidth"), 10) || 0; x += bl; y += bt; if (p != el && pe.getStyle('overflow') != 'visible') { x += bl; y += bt; } } p = p.offsetParent; } if (Ext.isSafari && hasAbsolute) { x -= bd.offsetLeft; y -= bd.offsetTop; } if (Ext.isGecko && !hasAbsolute) { var dbd = fly(bd); x += parseInt(dbd.getStyle("borderLeftWidth"), 10) || 0; y += parseInt(dbd.getStyle("borderTopWidth"), 10) || 0; } p = el.parentNode; while (p && p != bd) { if (!Ext.isOpera || (p.tagName != 'TR' && fly(p).getStyle("display") != "inline")) { x -= p.scrollLeft; y -= p.scrollTop; } p = p.parentNode; } return [x, y]; }, setXY : function(el, xy){ el = Ext.fly(el, '_setXY'); el.position(); var pts = el.translatePoints(xy); if(xy[0] !== false){ el.dom.style.left = pts.left + "px"; } if(xy[1] !== false){ el.dom.style.top = pts.top + "px"; } }, setX : function(el, x){ this.setXY(el, [x, false]); }, setY : function(el, y){ this.setXY(el, [false, y]); } }; // all lib flyweight calls use their own flyweight to prevent collisions with developer flyweights function fly(el){ if(!libFlyweight){ libFlyweight = new Ext.Element.Flyweight(); } libFlyweight.dom = el; return libFlyweight; } Ext.lib.Event = { getPageX : function(e){ e = e.browserEvent || e; return e.pageX; }, getPageY : function(e){ e = e.browserEvent || e; return e.pageY; }, getXY : function(e){ e = e.browserEvent || e; return [e.pageX, e.pageY]; }, getTarget : function(e){ return e.target; }, // all Ext events will go through event manager which provides scoping on : function(el, eventName, fn, scope, override){ jQuery(el).bind(eventName, fn); }, un : function(el, eventName, fn){ jQuery(el).unbind(eventName, fn); }, purgeElement : function(el){ jQuery(el).unbind(); }, preventDefault : function(e){ e = e.browserEvent || e; if(e.preventDefault){ e.preventDefault(); }else{ e.returnValue = false; } }, stopPropagation : function(e){ e = e.browserEvent || e; if(e.stopPropagation){ e.stopPropagation(); }else{ e.cancelBubble = true; } }, stopEvent : function(e){ this.preventDefault(e); this.stopPropagation(e); }, onAvailable : function(id, fn, scope){ var start = new Date(); var f = function(){ if(start.getElapsed() > 10000){ clearInterval(iid); } var el = document.getElementById(id); if(el){ clearInterval(iid); fn.call(scope||window, el); } }; var iid = setInterval(f, 50); }, resolveTextNode: Ext.isGecko ? function(node){ if(!node){ return; } var s = HTMLElement.prototype.toString.call(node); if(s == '[xpconnect wrapped native prototype]' || s == '[object XULElement]'){ return; } return node.nodeType == 3 ? node.parentNode : node; } : function(node){ return node && node.nodeType == 3 ? node.parentNode : node; }, getRelatedTarget: function(ev) { ev = ev.browserEvent || ev; var t = ev.relatedTarget; if (!t) { if (ev.type == "mouseout") { t = ev.toElement; } else if (ev.type == "mouseover") { t = ev.fromElement; } } return this.resolveTextNode(t); } }; Ext.lib.Ajax = function(){ var createComplete = function(cb){ return function(xhr, status){ if((status == 'error' || status == 'timeout') && cb.failure){ cb.failure.call(cb.scope||window, createResponse(cb, xhr)); }else if(cb.success){ cb.success.call(cb.scope||window, createResponse(cb, xhr)); } }; }; var createResponse = function(cb, xhr){ var headerObj = {}, headerStr, t, s; try { headerStr = xhr.getAllResponseHeaders(); Ext.each(headerStr.replace(/\r\n/g, '\n').split('\n'), function(v){ t = v.indexOf(':'); if(t >= 0){ s = v.substr(0, t).toLowerCase(); if(v.charAt(t + 1) == ' '){ ++t; } headerObj[s] = v.substr(t + 1); } }); } catch(e) {} return { responseText: xhr.responseText, responseXML : xhr.responseXML, argument: cb.argument, status: xhr.status, statusText: xhr.statusText, getResponseHeader : function(header){return headerObj[header.toLowerCase()];}, getAllResponseHeaders : function(){return headerStr} }; }; return { request : function(method, uri, cb, data, options){ var o = { type: method, url: uri, data: data, timeout: cb.timeout, complete: createComplete(cb) }; if(options){ var hs = options.headers; if(options.xmlData){ o.data = options.xmlData; o.processData = false; o.type = (method ? method : (options.method ? options.method : 'POST')); if (!hs || !hs['Content-Type']){ o.contentType = 'text/xml'; } }else if(options.jsonData){ o.data = typeof options.jsonData == 'object' ? Ext.encode(options.jsonData) : options.jsonData; o.processData = false; o.type = (method ? method : (options.method ? options.method : 'POST')); if (!hs || !hs['Content-Type']){ o.contentType = 'application/json'; } } if(hs){ o.beforeSend = function(xhr){ for(var h in hs){ if(hs.hasOwnProperty(h)){ xhr.setRequestHeader(h, hs[h]); } } } } } jQuery.ajax(o); }, formRequest : function(form, uri, cb, data, isUpload, sslUri){ jQuery.ajax({ type: Ext.getDom(form).method ||'POST', url: uri, data: jQuery(form).serialize()+(data?'&'+data:''), timeout: cb.timeout, complete: createComplete(cb) }); }, isCallInProgress : function(trans){ return false; }, abort : function(trans){ return false; }, serializeForm : function(form){ return jQuery(form.dom||form).serialize(); } }; }(); Ext.lib.Anim = function(){ var createAnim = function(cb, scope){ var animated = true; return { stop : function(skipToLast){ // do nothing }, isAnimated : function(){ return animated; }, proxyCallback : function(){ animated = false; Ext.callback(cb, scope); } }; }; return { scroll : function(el, args, duration, easing, cb, scope){ // scroll anim not supported so just scroll immediately var anim = createAnim(cb, scope); el = Ext.getDom(el); if(typeof args.scroll.to[0] == 'number'){ el.scrollLeft = args.scroll.to[0]; } if(typeof args.scroll.to[1] == 'number'){ el.scrollTop = args.scroll.to[1]; } anim.proxyCallback(); return anim; }, motion : function(el, args, duration, easing, cb, scope){ return this.run(el, args, duration, easing, cb, scope); }, color : function(el, args, duration, easing, cb, scope){ // color anim not supported, so execute callback immediately var anim = createAnim(cb, scope); anim.proxyCallback(); return anim; }, run : function(el, args, duration, easing, cb, scope, type){ var anim = createAnim(cb, scope), e = Ext.fly(el, '_animrun'); var o = {}; for(var k in args){ switch(k){ // jquery doesn't support, so convert case 'points': var by, pts; e.position(); if(by = args.points.by){ var xy = e.getXY(); pts = e.translatePoints([xy[0]+by[0], xy[1]+by[1]]); }else{ pts = e.translatePoints(args.points.to); } o.left = pts.left; o.top = pts.top; if(!parseInt(e.getStyle('left'), 10)){ // auto bug e.setLeft(0); } if(!parseInt(e.getStyle('top'), 10)){ e.setTop(0); } if(args.points.from){ e.setXY(args.points.from); } break; case 'width': o.width = args.width.to; if (args.width.from) e.setWidth(args.width.from); break; case 'height': o.height = args.height.to; if (args.height.from) e.setHeight(args.height.from); break; case 'opacity': o.opacity = args.opacity.to; if (args.opacity.from) e.setOpacity(args.opacity.from); break; case 'left': o.left = args.left.to; if (args.left.from) e.setLeft(args.left.from); break; case 'top': o.top = args.top.to; if (args.top.from) e.setTop(args.top.from); break; case 'callback': case 'scope': // jQuery can't handle callback and scope arguments, so break here break; default: o[k] = args[k].to; if (args[k].from) e.setStyle(k, args[k].from); break; } } // TODO: find out about easing plug in? jQuery(el).animate(o, duration*1000, undefined, anim.proxyCallback); return anim; } }; }(); Ext.lib.Region = function(t, r, b, l) { this.top = t; this[1] = t; this.right = r; this.bottom = b; this.left = l; this[0] = l; }; Ext.lib.Region.prototype = { contains : function(region) { return ( region.left >= this.left && region.right <= this.right && region.top >= this.top && region.bottom <= this.bottom ); }, getArea : function() { return ( (this.bottom - this.top) * (this.right - this.left) ); }, intersect : function(region) { var t = Math.max( this.top, region.top ); var r = Math.min( this.right, region.right ); var b = Math.min( this.bottom, region.bottom ); var l = Math.max( this.left, region.left ); if (b >= t && r >= l) { return new Ext.lib.Region(t, r, b, l); } else { return null; } }, union : function(region) { var t = Math.min( this.top, region.top ); var r = Math.max( this.right, region.right ); var b = Math.max( this.bottom, region.bottom ); var l = Math.min( this.left, region.left ); return new Ext.lib.Region(t, r, b, l); }, constrainTo : function(r) { this.top = this.top.constrain(r.top, r.bottom); this.bottom = this.bottom.constrain(r.top, r.bottom); this.left = this.left.constrain(r.left, r.right); this.right = this.right.constrain(r.left, r.right); return this; }, adjust : function(t, l, b, r){ this.top += t; this.left += l; this.right += r; this.bottom += b; return this; } }; Ext.lib.Region.getRegion = function(el) { var p = Ext.lib.Dom.getXY(el); var t = p[1]; var r = p[0] + el.offsetWidth; var b = p[1] + el.offsetHeight; var l = p[0]; return new Ext.lib.Region(t, r, b, l); }; Ext.lib.Point = function(x, y) { if (Ext.isArray(x)) { y = x[1]; x = x[0]; } this.x = this.right = this.left = this[0] = x; this.y = this.top = this.bottom = this[1] = y; }; Ext.lib.Point.prototype = new Ext.lib.Region(); // prevent IE leaks if(Ext.isIE) { function fnCleanUp() { var p = Function.prototype; delete p.createSequence; delete p.defer; delete p.createDelegate; delete p.createCallback; delete p.createInterceptor; window.detachEvent("onunload", fnCleanUp); } window.attachEvent("onunload", fnCleanUp); } })();
import React from 'react'; const PostCard = (props) => { return ( <div> <div className="col-xs-12 col-sm-6"> <div className="post--card"> <h3 className="post__title">Pomodoro Clock</h3> <a className="post__author" href="#">created by Bob</a> <p className="post__desc"> A timer with 25 minute work intervals 5 minute breaks and one long 15 minute break every 4 sessions. With the option to set custom times. </p> <i className="fa fa-heart-o post__heart" aria-hidden="true"></i><span className="post__favnum">&nbsp;2903</span> <a className="post__link float-right " href="#">View Idea</a> </div> <div className="post--card--img"> <h3 className="post__title text-center">Meme Generator</h3> <a className="post__author text-center" href="#">created by Bob</a> <img className="post__img" src="http://i.imgur.com/49Kg4w8.jpg" /> <i className="fa fa-heart-o post__heart" aria-hidden="true"></i><span className="post__favnum">&nbsp;4321</span> <a className="post__link float-right " href="#">View Idea</a> </div> </div> <div className="col-xs-12 col-sm-6"> <div className="post--card--img"> <h3 className="post__title text-center">Random quote generator</h3> <a className="post__author text-center" href="#">created by Bob</a> <img className="post__img" src="https://d13yacurqjgara.cloudfront.net/users/8436/screenshots/113953/shot_1297462337.jpg" /> <i className="fa fa-heart-o post__heart" aria-hidden="true"></i><span className="post__favnum">&nbsp;825</span> <a className="post__link float-right " href="#">View Idea</a> </div> <div className="post--card"> <h3 className="post__title">Lorem Ipsum</h3> <a className="post__author" href="#">created by Bob</a> <p className="post__desc"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue... </p> <i className="fa fa-heart-o post__heart" aria-hidden="true"></i><span className="post__favnum">&nbsp;55</span> <a className="post__link float-right " href="#">View Idea</a> </div> </div> </div> ); } export default PostCard;
/* * Revolution custom js file * Author: Design_mylife * */ //full width slider jQuery(document).ready(function () { revapi = jQuery('.tp-banner').revolution( { delay: 6000, startwidth: 1170, startheight: 600, hideThumbs: 10, fullWidth: "on", forceFullWidth: "on", navigationStyle: "preview4" }); }); //ready jQuery(document).ready(function () { revapi = jQuery('.tp-banner-boxed').revolution( { delay: 6000, startwidth: 1170, startheight: 500, hideThumbs: 10, navigationStyle: "preview4" }); }); jQuery(document).ready(function () { revapi = jQuery('.tp-fullscreen-banner').revolution( { delay: 15000, startwidth: 1170, startheight: 500, hideThumbs: 10, fullWidth: "off", fullScreen: "on", fullScreenOffsetContainer: "" }); }); //ready //ken burns effect jQuery(document).ready(function () { revapi = jQuery('.ken-burns-banner').revolution( { dottedOverlay: "none", delay: 16000, startwidth: 1140, startheight: 700, hideThumbs: 200, thumbWidth: 100, thumbHeight: 50, thumbAmount: 5, navigationType: "bullet", navigationArrows: "solo", navigationStyle: "preview4", touchenabled: "on", onHoverStop: "on", swipe_velocity: 0.7, swipe_min_touches: 1, swipe_max_touches: 1, drag_block_vertical: false, parallax: "mouse", parallaxBgFreeze: "on", parallaxLevels: [7, 4, 3, 2, 5, 4, 3, 2, 1, 0], keyboardNavigation: "off", navigationHAlign: "center", navigationVAlign: "bottom", navigationHOffset: 0, navigationVOffset: 20, soloArrowLeftHalign: "left", soloArrowLeftValign: "center", soloArrowLeftHOffset: 20, soloArrowLeftVOffset: 0, soloArrowRightHalign: "right", soloArrowRightValign: "center", soloArrowRightHOffset: 20, soloArrowRightVOffset: 0, shadow: 0, fullWidth: "off", fullScreen: "on", spinner: "spinner4", stopLoop: "off", stopAfterLoops: -1, stopAtSlide: -1, shuffle: "off", autoHeight: "off", forceFullWidth: "off", hideThumbsOnMobile: "off", hideNavDelayOnMobile: 1500, hideBulletsOnMobile: "off", hideArrowsOnMobile: "off", hideThumbsUnderResolution: 0, hideSliderAtLimit: 0, hideCaptionAtLimit: 0, hideAllCaptionAtLilmit: 0, startWithSlide: 0 }); }); //ready //vertical slider jQuery(document).ready(function () { jQuery('.tp-banner-vertical').show().revolution( { dottedOverlay: "none", delay: 9000, startwidth: 1170, startheight: 500, hideThumbs: 200, thumbWidth: 100, thumbHeight: 50, thumbAmount: 5, navigationType: "none", navigationArrows: "solo", navigationStyle: "preview1", touchenabled: "on", onHoverStop: "on", swipe_velocity: 0.7, swipe_min_touches: 1, swipe_max_touches: 1, drag_block_vertical: false, keyboardNavigation: "on", navigationHAlign: "center", navigationVAlign: "bottom", navigationHOffset: 0, navigationVOffset: 20, soloArrowLeftHalign: "left", soloArrowLeftValign: "center", soloArrowLeftHOffset: 20, soloArrowLeftVOffset: 0, soloArrowRightHalign: "right", soloArrowRightValign: "center", soloArrowRightHOffset: 20, soloArrowRightVOffset: 0, shadow: 0, fullWidth: "on", fullScreen: "off", spinner: "spinner0", stopLoop: "off", stopAfterLoops: -1, stopAtSlide: -1, shuffle: "off", autoHeight: "off", forceFullWidth: "on", hideThumbsOnMobile: "off", hideNavDelayOnMobile: 1500, hideBulletsOnMobile: "off", hideArrowsOnMobile: "off", hideThumbsUnderResolution: 0, hideSliderAtLimit: 0, hideCaptionAtLimit: 0, hideAllCaptionAtLilmit: 0, startWithSlide: 0 }); }); //ready
import React, { Component } from 'react' import classnames from 'classnames' import PropTypes from '../utils/proptypes' import { getLang } from '../lang' import { format } from '../utils/strings' import * as Datetime from '../utils/datetime' export default class TimeAgo extends Component { count (current) { const marginms = Datetime.convert(this.props.base).getTime() - current.getTime() const marginHuman = this.toReadable(marginms) return marginHuman ? format(getLang(marginms > 0 ? 'in' : 'ago'), marginHuman) : 'right now' } toReadable (marginms) { const SECOND = 1000 const MINUTE = SECOND * 60 const HOUR = MINUTE * 60 const DAY = HOUR * 24 const WEEK = DAY * 7 const MONTH = DAY * 30 const YEAR = DAY * 365 marginms = Math.abs(marginms) return marginms > YEAR ? this.template(marginms / YEAR, 'year') : marginms > MONTH ? this.template(marginms / MONTH, 'month') : marginms > WEEK ? this.template(marginms / WEEK, 'week') : marginms > DAY ? this.template(marginms / DAY, 'day') : marginms > HOUR ? this.template(marginms / HOUR, 'hour') : marginms > MINUTE ? this.template(marginms / MINUTE, 'minute') : marginms > SECOND ? this.template(marginms / SECOND, 'second') : this.template(0) } template (margin, category) { const strategy = { default: Math.round, least: Math.floor, most: Math.ceil } return margin ? strategy[this.props.mode](margin) + format(getLang(category), margin > 1 ? 's' : '') : getLang('now') } render () { const { children, className, onClick } = this.props const current = new Date() return ( <label className={classnames({className})}> {children} {onClick ? <a onClick={onClick}> {this.count(current)} </a> : this.count(current)} </label> ) } } TimeAgo.propTypes = { base: PropTypes.datetime.isRequired, children: PropTypes.any, className: PropTypes.string, mode: PropTypes.string, onClick: PropTypes.func } TimeAgo.defaultProps = { mode: 'default' }
import cleanData from '../cleanData'; describe('i18n | Components | CMEditViewCopyLocale | utils', () => { describe('cleanData', () => { it('should change the localization key with the one passed in the argument', () => { const data = { address: 'test', addresseses: [], common: 'common', createdAt: '2021-03-17T15:34:05.866Z', createdBy: { blocked: null, email: 'cyril@strapi.io', firstname: 'cyril', id: 1, isActive: true, lastname: 'lopez', preferedLanguage: null, registrationToken: null, resetPasswordToken: null, username: null, }, id: 14, locale: 'fr-FR', localizations: [ { id: 13, locale: 'en', publishedAt: null, }, ], name: 'name', publishedAt: null, updatedAt: '2021-03-17T15:34:18.958Z', updatedBy: { blocked: null, email: 'cyril@strapi.io', firstname: 'cyril', id: 1, isActive: true, lastname: 'lopez', preferedLanguage: null, registrationToken: null, resetPasswordToken: null, username: null, }, }; const contentType = { attributes: { address: { type: 'relation' }, addresseses: { type: 'relation' }, common: { pluginOptions: { i18n: { localized: true } }, type: 'text' }, createdAt: { type: 'timestamp' }, id: { type: 'integer' }, name: { pluginOptions: { i18n: { localized: true } } }, updatedAt: { type: 'timestamp' }, }, }; const initLocalizations = [ { id: 14, locale: 'fr-FR', publishedAt: null, }, ]; const expected = { common: 'common', locale: 'fr-FR', localizations: [ { id: 14, locale: 'fr-FR', publishedAt: null, }, ], name: 'name', }; expect(cleanData(data, { contentType, components: {} }, initLocalizations)).toEqual(expected); }); }); });
var logger = require('winston'); exports.notFound = function(req, res, next){ res.send(404, 'Sorry cant find that!'); } exports.logErrors = function(err, req, res, next) { logger.log("error", err.stack); next(err); } exports.clientErrorHandler = function(err, req, res, next) { if (req.xhr) { logger.log("error", "sending xhr error"); res.send(500, { error: 'oops!' }); } else { next(err); } } exports.errorHandler = function(err, req, res, next) { res.status(500); res.render('error', { title: "Error", error: err }); }
'use strict'; describe('Service: gridService', function () { // load the service's module beforeEach(module('uixApp')); // instantiate service var gridService; beforeEach(inject(function (_gridService_) { gridService = _gridService_; })); it('should do something', function () { expect(!!gridService).toBe(true); }); });
console.log("GlobalsDB-Admin is starting..."); var server, config, fs = require("fs"); try { config = require("./config.js"); } catch (e) { console.error("Unable to start: invalid configuration file config.js"); console.error(e); process.exit(1); } // set config global config.system = { cwd: __dirname }; // try to load GlobalsDB module try { require(config.database.modulePath); } catch (e) { console.error("Unable to load cache node module. Check if correct module configured.\n", e); process.exit(1); } // check databases var ds = config.database.databases, i = 0; for (var d in ds) { if (!ds.hasOwnProperty(d)) continue; if (!fs.existsSync(ds[d] + "/CACHE.DAT")) { // "simple" check console.error("Configured database " + d + " (" + ds[d] + ") does not exists or is not a valid Caché database (missed CACHE.DAT)"); delete ds[d]; } else { i++; } } if (i === 0) { console.error("Unable to start: no configured databases. " + "Please, edit config.database.databases"); process.exit(1); } // try to connect server try { server = require("./server/index.js"); } catch (e) { console.error("Unable to start: problems with server/index.js\n", e); process.exit(1); } // set basic in-app exception handler process.on("uncaughtException", function(err) { fs.appendFile(config.system.cwd + "/" + config.server.logFileName, "INTERNAL ERROR OCCURRED: " + err + "\n"); }); // init server server.init(function(ok) { if (ok) { console.log("System start successful. Everything ready!"); } else { console.error("Unable to start: server not up.") ; } });
import { assert } from 'chai'; import utils from 'osg/utils'; import 'tests/mockup/mockup'; import primitiveFunctor from 'osg/primitiveFunctor'; import primitiveSet from 'osg/primitiveSet'; import DrawElements from 'osg/DrawElements'; import DrawArrays from 'osg/DrawArrays'; import Geometry from 'osg/Geometry'; import BufferArray from 'osg/BufferArray'; import { vec3 } from 'osg/glMatrix'; export default function() { var createGeometry = function(primitiveType, arraysOrElements) { var g = new Geometry(); var vertexes = new utils.Float32Array(9); vertexes[0] = 0; vertexes[1] = 0; vertexes[2] = 0; vertexes[3] = 2.0; vertexes[4] = 2.0; vertexes[5] = 0.0; vertexes[6] = -2.0; vertexes[7] = 2.0; vertexes[8] = 0.0; var normal = new utils.Float32Array(9); normal[0] = 0; normal[1] = 0; normal[2] = 1; normal[3] = 0; normal[4] = 0; normal[5] = 1; normal[6] = 0; normal[7] = 0; normal[8] = 1; var indexes = new utils.Uint16Array(3); indexes[0] = 2; indexes[1] = 0; indexes[2] = 1; g.getAttributes().Vertex = new BufferArray(BufferArray.ARRAY_BUFFER, vertexes, 3); g.getAttributes().Normal = new BufferArray(BufferArray.ARRAY_BUFFER, normal, 3); var primitive; if (arraysOrElements === 0) { primitive = new DrawArrays(primitiveType, 0, vertexes.length / 3); } else { primitive = new DrawElements( primitiveType, new BufferArray(BufferArray.ELEMENT_ARRAY_BUFFER, indexes, 1) ); } g.getPrimitives().push(primitive); return g; }; test('PrimitiveFunctor Points', function() { // Test DrawArrays var node = createGeometry(primitiveSet.POINTS, 0); var vertices = node.getAttributes().Vertex.getElements(); // The callback must be defined as a closure var vectors = []; var cb = { operatorPoint: function(v) { vectors.push(v[0]); vectors.push(v[1]); vectors.push(v[2]); } }; primitiveFunctor(node, cb, vertices); assert.equalVector(vertices, vectors, 0.00001); // Test DrawElements node = createGeometry(primitiveSet.POINTS, 1); vectors = []; primitiveFunctor(node, cb, vertices); assert.isOk(vectors[0] === -2.0, 'Vectors[ 0 ] should be -2 and result is ' + vectors[0]); assert.isOk(vectors[1] === 2.0, 'Vectors[ 1 ] should be 2 and result is ' + vectors[1]); assert.isOk(vectors[2] === 0.0, 'Vectors[ 2 ] should be 0 and result is ' + vectors[2]); assert.isOk(vectors[3] === 0.0, 'Vectors[ 3 ] should be 0 and result is ' + vectors[3]); assert.isOk(vectors[4] === 0.0, 'Vectors[ 4 ] should be 0 and result is ' + vectors[4]); assert.isOk(vectors[5] === 0.0, 'Vectors[ 5 ] should be 0 and result is ' + vectors[5]); assert.isOk(vectors[6] === 2.0, 'Vectors[ 6 ] should be 2 and result is ' + vectors[6]); assert.isOk(vectors[7] === 2.0, 'Vectors[ 7 ] should be 2 and result is ' + vectors[7]); assert.isOk(vectors[8] === 0.0, 'Vectors[ 8 ] should be 0 and result is ' + vectors[8]); }); test('PrimitiveFunctor Lines', function() { // Test DrawArrays var node = createGeometry(primitiveSet.LINES, 0); var vertices = node.getAttributes().Vertex.getElements(); // The callback must be defined as a closure var vectors = []; var cb = { operatorLine: function(v1, v2) { vectors.push(v1); vectors.push(v2); } }; primitiveFunctor(node, cb, vertices); assert.equalVector(vectors[0], [0, 0, 0]); assert.equalVector(vectors[1], [2, 2, 0]); // Test DrawElements node = createGeometry(primitiveSet.LINES, 1); vectors = []; primitiveFunctor(node, cb, vertices); assert.equalVector(vectors[0], [-2.0, 2.0, 0]); assert.equalVector(vectors[1], [0, 0, 0]); }); test('PrimitiveFunctor LineStrip', function() { // Test DrawArrays var node = createGeometry(primitiveSet.LINE_STRIP, 0); var vertices = node.getAttributes().Vertex.getElements(); // The callback must be defined as a closure var vectors = []; var cb = { operatorLine: function(v1, v2) { vectors.push(vec3.clone(v1)); vectors.push(vec3.clone(v2)); } }; primitiveFunctor(node, cb, vertices); assert.equalVector(vectors[0], [0, 0, 0]); assert.equalVector(vectors[1], [2, 2, 0]); assert.equalVector(vectors[2], [2, 2, 0]); assert.equalVector(vectors[3], [-2, 2, 0]); // Test DrawElements node = createGeometry(primitiveSet.LINE_STRIP, 1); vectors = []; primitiveFunctor(node, cb, vertices); assert.equalVector(vectors[0], [-2.0, 2.0, 0]); assert.equalVector(vectors[1], [0, 0, 0]); assert.equalVector(vectors[2], [0, 0, 0]); assert.equalVector(vectors[3], [2, 2, 0]); }); test('PrimitiveFunctor LineLoop', function() { // Test DrawArrays var node = createGeometry(primitiveSet.LINE_LOOP, 0); var vertices = node.getAttributes().Vertex.getElements(); // The callback must be defined as a closure var vectors = []; var cb = { operatorLine: function(v1, v2) { vectors.push(vec3.clone(v1)); vectors.push(vec3.clone(v2)); } }; primitiveFunctor(node, cb, vertices); assert.equalVector(vectors[0], [0, 0, 0]); assert.equalVector(vectors[1], [2, 2, 0]); assert.equalVector(vectors[2], [2, 2, 0]); assert.equalVector(vectors[3], [-2, 2, 0]); assert.equalVector(vectors[4], [-2, 2, 0]); assert.equalVector(vectors[5], [0, 0, 0]); // Test DrawElements node = createGeometry(primitiveSet.LINE_LOOP, 1); vectors = []; primitiveFunctor(node, cb, vertices); assert.equalVector(vectors[0], [-2.0, 2.0, 0]); assert.equalVector(vectors[1], [0, 0, 0]); assert.equalVector(vectors[2], [0, 0, 0]); assert.equalVector(vectors[3], [2, 2, 0]); assert.equalVector(vectors[4], [2, 2, 0]); assert.equalVector(vectors[5], [-2.0, 2.0, 0]); }); test('PrimitiveFunctor Triangle', function() { // Test DrawArrays var node = createGeometry(primitiveSet.TRIANGLES, 0); var vertices = node.getAttributes().Vertex.getElements(); // The callback must be defined as a closure var vectors = []; var cb = { operatorTriangle: function(v1, v2, v3) { vectors.push(vec3.clone(v1)); vectors.push(vec3.clone(v2)); vectors.push(vec3.clone(v3)); } }; primitiveFunctor(node, cb, vertices); assert.equalVector(vectors[0], [0, 0, 0]); assert.equalVector(vectors[1], [2, 2, 0]); assert.equalVector(vectors[2], [-2, 2, 0]); // Test DrawElements node = createGeometry(primitiveSet.TRIANGLES, 1); vectors = []; primitiveFunctor(node, cb, vertices); assert.equalVector(vectors[0], [-2.0, 2.0, 0]); assert.equalVector(vectors[1], [0, 0, 0]); assert.equalVector(vectors[2], [2.0, 2.0, 0]); }); }
'use strict'; var Vault = require('../index'); var assert = require('assert'); describe('parse', function() { describe('string', function () { Vault.set('name', 'jimmy'); var name = Vault.get('name'); it('should be a typeof string', function () { assert.equal('string', typeof name); }); it('should return a string', function () { assert.equal('jimmy', name); }); }); describe('number', function () { Vault.set('age', 33); var age = Vault.get('age'); it('should be a typeof number', function () { assert.equal('number', typeof age); }); it('should return a number', function () { assert.equal(33, age); }); }); describe('array', function () { Vault.set('cities', [ 'Pittsburgh', 'San Jose', 'London', 'Porvenir', 'Cambridge', 'San Francisco' ]); var cities = Vault.get('cities'); it('should be a typeof object', function () { assert.equal('object', typeof cities); }); it('should have array length', function () { assert.equal(6, cities.length); }); it('should return an array item', function () { assert.equal('San Francisco', cities[5]); }); }); describe('object', function () { Vault.set('libs', { 'vault.js': 'https://github.com/jimmybyrum/vault.js', 'voice-commands.js': 'https://github.com/jimmybyrum/voice-commands.js' }); var libs = Vault.get('libs'); it('should be a typeof object', function () { assert.equal('object', typeof libs); }); it('should return the key', function () { assert.equal('vault.js', Object.keys(libs)[0]); }); it('should return the value', function () { assert.equal('https://github.com/jimmybyrum/vault.js', libs['vault.js']); }); }); describe('deep object', function () { Vault.set('deep', { name: 'James', age: 33, cities: { pgh: { name: 'Pittsburgh', founded: 1758, teams: [ 'Penguins', 'Steelers', 'Pirates' ] } } }); var deep = Vault.get('deep'); it('should be a typeof object', function () { assert.equal('object', typeof deep); }); it('should return the key', function () { assert.equal('pgh', Object.keys(deep.cities)[0]); }); it('should return the value', function () { assert.equal(1758, deep.cities.pgh.founded); }); it('should return a value from a nested array', function () { assert.equal('Penguins', deep.cities.pgh.teams[0]); }); }); describe('default_value', function () { var notThere = Vault.get('notThere', 'A Default Value'); it('should be a typeof string', function () { assert.equal('string', typeof notThere); }); it('should return the default_value', function () { assert.equal('A Default Value', notThere); }); }); describe('get and remove', function () { Vault.set('oneTimeOnly', 'only once'); var oneTimeOnly = Vault.getAndRemove('oneTimeOnly'); it('should be a typeof string', function () { assert.equal('string', typeof oneTimeOnly); }); it('should return a string', function () { assert.equal('only once', oneTimeOnly); }); it('should return undefined when called a second time', function () { assert.equal(undefined, Vault.get('oneTimeOnly')); }); }); describe('expires', function () { Vault.set('thisVarExpiresSoon', 'expiring soon', { expires: '+1 seconds' }); var expires = Vault.get('thisVarExpiresSoon'); it('should be a typeof string', function () { assert.equal('string', typeof expires); }); it('should return a string', function () { assert.equal('expiring soon', expires); }); it('should return undefined after waiting 1 second', function (done) { setTimeout(function() { assert.equal(undefined, Vault.get('thisVarExpiresSoon')); done(); }, 1000); }); }); });
var chai = require("chai"); var chaiAsPromised = require("chai-as-promised"); chai.use(chaiAsPromised); chai.should(); var assert = chai.assert; var expect = chai.expect; var fs = require('fs'); var rimraf = require('rimraf'); var outputDir = './output'; if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir); var easyimg = require('./easyimage.js'); var srcimg = 'kitten.jpg'; var warningimg = 'letter.png'; describe('.info - ', function () { describe('valid file type', function () { it('should show file info', function () { return easyimg.info(srcimg); }); }); describe('valid file type with warning', function () { it('should show file info', function () { return expect(easyimg.info(warningimg)).to.eventually.have.property('warnings'); }); }); describe('invalid file type', function () { it('should not be supported', function () { return assert.isRejected(easyimg.info('./test.js'), /^identify/); }); }); }); describe('.convert -', function () { afterEach(function(done) { fs.unlink(__dirname + '/output/convert.png', function() { /* ignore any error unlinking */ done(); }); }); it('should convert an image format to another', function () { return easyimg.convert({src:srcimg, dst: __dirname + '/output/convert.png', quality:10}).then(function (file) { file.should.be.a('object'); file.should.have.property('type'); file.type.should.be.equal('PNG'); file.name.should.be.equal('convert.png'); }); }); }); describe('.rotate -', function () { afterEach(function(done) { fs.unlink(__dirname + '/output/rotated.jpg', function() { /* ignore any error unlinking */ done(); }); }); it('should rotate the image by 90 degree', function () { return easyimg.info(srcimg).then(function(info){ info.should.have.property('width') info.should.have.property('height') // Mainly check only if width and height are swaped return easyimg.rotate({src:srcimg, dst: __dirname + '/output/rotated.jpg', degree: 90}).then(function (file) { file.should.be.a('object'); file.name.should.be.equal('rotated.jpg'); file.should.have.property('width'); file.width.should.be.equal(info.height); file.height.should.be.equal(info.width); }); }) }); }); describe('.resize -', function () { afterEach(function(done) { fs.unlink(__dirname + '/output/resize.jpg', function() { /* ignore any error unlinking */ done(); }); }); it('should resize an image', function () { return easyimg.resize({src:srcimg, dst: __dirname + '/output/resize.jpg', width:640, height:480}).then(function (file) { file.should.be.a('object'); file.should.have.property('width'); file.width.should.be.equal(640); file.name.should.be.equal('resize.jpg'); }); }); }); describe('.crop -', function () { afterEach(function(done) { fs.unlink(__dirname + '/output/crop.jpg', function() { /* ignore any error unlinking */ done(); }); }); it('should crop an image', function () { return easyimg.crop({ src:srcimg, dst: __dirname + '/output/crop.jpg', cropwidth:128, cropheight:128, gravity:'North', x:0, y:0 }).then(function (file) { file.should.be.a('object'); file.should.have.property('width'); file.width.should.be.equal(128); file.name.should.be.equal('crop.jpg'); }); }); }); describe('.rescrop -', function () { afterEach(function(done) { fs.unlink(__dirname + '/output/rescrop.jpg', function() { /* ignore any error unlinking */ done(); }); }); it('should resize and crop', function () { return easyimg.rescrop({ src:srcimg, dst: __dirname + '/output/rescrop.jpg', width:400, height:5400, cropwidth:100, cropheight:100, x:0, y:0 }).then(function (file) { file.should.be.a('object'); file.should.have.property('width'); file.width.should.be.equal(100); file.name.should.be.equal('rescrop.jpg'); }); }); }); describe('.thumbnail -', function () { afterEach(function(done) { fs.unlink(__dirname + '/output/thumb nail.jpg', function() { /* ignore any error unlinking */ done(); }); }); //this.timeout(5000); it('should generate a thumbnail', function () { return easyimg.thumbnail({ src:srcimg, dst: __dirname + '/output/thumb nail.jpg', width:128, height:128, x:0, y:0 }).then(function (file) { file.should.be.a('object'); file.should.have.property('width'); file.width.should.be.equal(128); file.name.should.be.equal('thumb nail.jpg'); }); }); }); describe('.exec -', function () { afterEach(function(done) { fs.unlink(__dirname + '/output/hello kitty.gif', function() { /* ignore any error unlinking */ done(); }); }); it('should invoke `convert` command', function () { return easyimg.exec('convert '+ srcimg +' ./output/hello\\ kitty.gif').then(function (file) { }); }); }); describe('additionals', function () { afterEach(function(done) { rimraf(__dirname + '/output/foo/', function() { done(); }); }); //this.timeout(5000); it('should create directories if they do not exist', function () { return easyimg.thumbnail({ src:srcimg, dst: __dirname + '/output/foo/bar/hey.jpg', width:128, height:128, x:0, y:0 }).then(function (file) { file.should.be.a('object'); file.name.should.be.equal('hey.jpg'); }); }); });
/* * jQuery File Upload Image Processing Plugin 1.0.6 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2012, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint nomen: true, unparam: true, regexp: true */ /*global define, window, document */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define([ 'jquery', 'load-image', 'canvas-to-blob', './jquery.fileupload.js' ], factory); } else { // Browser globals: factory( window.jQuery, window.loadImage, window.canvasToBlob ); } }(function ($, loadImage, canvasToBlob) { 'use strict'; // The File Upload IP version extends the basic fileupload widget // with image processing functionality: $.widget('blueimpIP.fileupload', $.blueimp.fileupload, { options: { // The regular expression to define which image files are to be // resized, given that the browser supports the operation: resizeSourceFileTypes: /^image\/(gif|jpeg|png)$/, // The maximum file size of images that are to be resized: resizeSourceMaxFileSize: 20000000, // 20MB // The maximum width of the resized images: resizeMaxWidth: undefined, // The maximum height of the resized images: resizeMaxHeight: undefined, // The minimum width of the resized images: resizeMinWidth: undefined, // The minimum height of the resized images: resizeMinHeight: undefined, // The add callback is invoked as soon as files are added to the fileupload // widget (via file input selection, drag & drop or add API call). // See the basic file upload widget for more information: add: function (e, data) { $(this).fileupload('resize', data).done(function () { data.submit(); }); } }, // Resizes the image file at the given index and stores the created blob // at the original position of the files list, returns a Promise object: _resizeImage: function (files, index, options) { var that = this, file = files[index], deferred = $.Deferred(), canvas, blob; options = options || this.options; loadImage( file, function (img) { var width = img.width, height = img.height; canvas = loadImage.scale(img, { maxWidth: options.resizeMaxWidth, maxHeight: options.resizeMaxHeight, minWidth: options.resizeMinWidth, minHeight: options.resizeMinHeight, canvas: true }); if (width !== canvas.width || height !== canvas.height) { canvasToBlob(canvas, function (blob) { if (!blob.name) { if (file.type === blob.type) { blob.name = file.name; } else if (file.name) { blob.name = file.name.replace( /\..+$/, '.' + blob.type.substr(6) ); } } files[index] = blob; deferred.resolveWith(that); }, file); } else { deferred.resolveWith(that); } } ); return deferred.promise(); }, // Resizes the images given as files property of the data parameter, // returns a Promise object that allows to bind a done handler, which // will be invoked after processing all images is done: resize: function (data) { var that = this, options = $.extend({}, this.options, data), resizeAll = $.type(options.resizeSourceMaxFileSize) !== 'number', isXHRUpload = this._isXHRUpload(options); $.each(data.files, function (index, file) { if (isXHRUpload && that._resizeSupport && (options.resizeMaxWidth || options.resizeMaxHeight || options.resizeMinWidth || options.resizeMinHeight) && (resizeAll || file.size < options.resizeSourceMaxFileSize) && options.resizeSourceFileTypes.test(file.type)) { that._processing += 1; if (that._processing === 1) { that.element.addClass('fileupload-processing'); } that._processingQueue = that._processingQueue.pipe(function () { var deferred = $.Deferred(); that._resizeImage( data.files, index, options ).done(function () { that._processing -= 1; if (that._processing === 0) { that.element .removeClass('fileupload-processing'); } deferred.resolveWith(that); }); return deferred.promise(); }); } }); return this._processingQueue; }, _create: function () { $.blueimp.fileupload.prototype._create.call(this); this._processing = 0; this._processingQueue = $.Deferred().resolveWith(this).promise(); this._resizeSupport = canvasToBlob && canvasToBlob( document.createElement('canvas'), $.noop ); } }); }));
/** * @fileoverview Rule to replace assignment expressions with operator assignment * @author Brandon Mills */ "use strict"; //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ /** * Checks whether an operator is commutative and has an operator assignment * shorthand form. * @param {string} operator Operator to check. * @returns {boolean} True if the operator is commutative and has a * shorthand form. */ function isCommutativeOperatorWithShorthand(operator) { return ["*", "&", "^", "|"].indexOf(operator) >= 0; } /** * Checks whether an operator is not commuatative and has an operator assignment * shorthand form. * @param {string} operator Operator to check. * @returns {boolean} True if the operator is not commuatative and has * a shorthand form. */ function isNonCommutativeOperatorWithShorthand(operator) { return ["+", "-", "/", "%", "<<", ">>", ">>>"].indexOf(operator) >= 0; } //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ /** * Checks whether two expressions reference the same value. For example: * a = a * a.b = a.b * a[0] = a[0] * a['b'] = a['b'] * @param {ASTNode} a Left side of the comparison. * @param {ASTNode} b Right side of the comparison. * @returns {boolean} True if both sides match and reference the same value. */ function same(a, b) { if (a.type !== b.type) { return false; } switch (a.type) { case "Identifier": return a.name === b.name; case "Literal": return a.value === b.value; case "MemberExpression": /* * x[0] = x[0] * x[y] = x[y] * x.y = x.y */ return same(a.object, b.object) && same(a.property, b.property); default: return false; } } module.exports = function(context) { /** * Ensures that an assignment uses the shorthand form where possible. * @param {ASTNode} node An AssignmentExpression node. * @returns {void} */ function verify(node) { var expr, left, operator; if (node.operator !== "=" || node.right.type !== "BinaryExpression") { return; } left = node.left; expr = node.right; operator = expr.operator; if (isCommutativeOperatorWithShorthand(operator)) { if (same(left, expr.left) || same(left, expr.right)) { context.report(node, "Assignment can be replaced with operator assignment."); } } else if (isNonCommutativeOperatorWithShorthand(operator)) { if (same(left, expr.left)) { context.report(node, "Assignment can be replaced with operator assignment."); } } } /** * Warns if an assignment expression uses operator assignment shorthand. * @param {ASTNode} node An AssignmentExpression node. * @returns {void} */ function prohibit(node) { if (node.operator !== "=") { context.report(node, "Unexpected operator assignment shorthand."); } } return { AssignmentExpression: context.options[0] !== "never" ? verify : prohibit }; }; module.exports.schema = [ { enum: ["always", "never"] } ];
module.exports = [{ 'name': 'Accounting/Auditing' }, { 'name': 'Administrative' }, { 'name': 'Advertising' }, { 'name': 'Business Analyst' }, { 'name': 'Financial Analyst' }, { 'name': 'Data Analyst' }, { 'name': 'Art/Creative' }, { 'name': 'Business Development' }, { 'name': 'Consulting' }, { 'name': 'Customer Service' }, { 'name': 'Distribution' }, { 'name': 'Design' }, { 'name': 'Education' }, { 'name': 'Engineering' }, { 'name': 'Finance' }, { 'name': 'General Business' }, { 'name': 'Health Care Provider' }, { 'name': 'Human Resources' }, { 'name': 'Information Technology' }, { 'name': 'Legal' }, { 'name': 'Management' }, { 'name': 'Manufacturing' }, { 'name': 'Marketing' }, { 'name': 'Other' }, { 'name': 'Public Relations' }, { 'name': 'Purchasing' }, { 'name': 'Product Management' }, { 'name': 'Project Management' }, { 'name': 'Production' }, { 'name': 'Quality Assurance' }, { 'name': 'Research' }, { 'name': 'Sales' }, { 'name': 'Science' }, { 'name': 'Strategy/Planning' }, { 'name': 'Supply Chain' }, { 'name': 'Secretary' }, { 'name': 'Training' }, { 'name': 'Writing/Editing' }]
'use strict'; const common = require('../common'); const assert = require('assert'); const { REPLServer } = require('repl'); const { Stream } = require('stream'); const { inspect } = require('util'); common.skipIfInspectorDisabled(); common.skipIfDumbTerminal(); const PROMPT = 'repl > '; class REPLStream extends Stream { readable = true; writable = true; constructor() { super(); this.lines = ['']; } run(data) { for (const entry of data) { this.emit('data', entry); } this.emit('data', '\n'); } write(chunk) { const chunkLines = chunk.toString('utf8').split('\n'); this.lines[this.lines.length - 1] += chunkLines[0]; if (chunkLines.length > 1) { this.lines.push(...chunkLines.slice(1)); } this.emit('line'); return true; } wait() { this.lines = ['']; return new Promise((resolve, reject) => { const onError = (err) => { this.removeListener('line', onLine); reject(err); }; const onLine = () => { if (this.lines[this.lines.length - 1].includes(PROMPT)) { this.removeListener('error', onError); this.removeListener('line', onLine); resolve(this.lines); } }; this.once('error', onError); this.on('line', onLine); }); } pause() {} resume() {} } function runAndWait(cmds, repl) { const promise = repl.inputStream.wait(); for (const cmd of cmds) { repl.inputStream.run(cmd); } return promise; } async function tests(options) { const repl = REPLServer({ prompt: PROMPT, stream: new REPLStream(), ignoreUndefined: true, useColors: true, ...options }); repl.inputStream.run([ 'function foo(x) { return x; }', 'function koo() { console.log("abc"); }', 'a = undefined;' ]); const testCases = [{ input: 'foo', noPreview: '[Function: foo]', preview: [ 'foo', '\x1B[90m[Function: foo]\x1B[39m\x1B[11G\x1B[1A\x1B[1B\x1B[2K\x1B[1A\r', '\x1B[36m[Function: foo]\x1B[39m' ] }, { input: 'koo', noPreview: '[Function: koo]', preview: [ 'k\x1B[90moo\x1B[39m\x1B[9G\x1B[0Ko\x1B[90mo\x1B[39m\x1B[10G\x1B[0Ko', '\x1B[90m[Function: koo]\x1B[39m\x1B[11G\x1B[1A\x1B[1B\x1B[2K\x1B[1A\r', '\x1B[36m[Function: koo]\x1B[39m' ] }, { input: 'a', noPreview: 'repl > ', // No "undefined" output. preview: ['a\r'] // No "undefined" preview. }, { input: " { b: 1 }['b'] === 1", noPreview: '\x1B[33mtrue\x1B[39m', preview: [ " { b: 1 }['b']", '\x1B[90m1\x1B[39m\x1B[22G\x1B[1A\x1B[1B\x1B[2K\x1B[1A ', '\x1B[90m1\x1B[39m\x1B[23G\x1B[1A\x1B[1B\x1B[2K\x1B[1A=== 1', '\x1B[90mtrue\x1B[39m\x1B[28G\x1B[1A\x1B[1B\x1B[2K\x1B[1A\r', '\x1B[33mtrue\x1B[39m' ] }, { input: "{ b: 1 }['b'] === 1;", noPreview: '\x1B[33mfalse\x1B[39m', preview: [ "{ b: 1 }['b']", '\x1B[90m1\x1B[39m\x1B[21G\x1B[1A\x1B[1B\x1B[2K\x1B[1A ', '\x1B[90m1\x1B[39m\x1B[22G\x1B[1A\x1B[1B\x1B[2K\x1B[1A=== 1', '\x1B[90mtrue\x1B[39m\x1B[27G\x1B[1A\x1B[1B\x1B[2K\x1B[1A;', '\x1B[90mfalse\x1B[39m\x1B[28G\x1B[1A\x1B[1B\x1B[2K\x1B[1A\r', '\x1B[33mfalse\x1B[39m' ] }, { input: '{ a: true }', noPreview: '{ a: \x1B[33mtrue\x1B[39m }', preview: [ '{ a: tru\x1B[90me\x1B[39m\x1B[16G\x1B[0Ke }\r', '{ a: \x1B[33mtrue\x1B[39m }' ] }, { input: '{ a: true };', noPreview: '\x1B[33mtrue\x1B[39m', preview: [ '{ a: tru\x1B[90me\x1B[39m\x1B[16G\x1B[0Ke };', '\x1B[90mtrue\x1B[39m\x1B[20G\x1B[1A\x1B[1B\x1B[2K\x1B[1A\r', '\x1B[33mtrue\x1B[39m' ] }, { input: ' \t { a: true};', noPreview: '\x1B[33mtrue\x1B[39m', preview: [ ' { a: tru\x1B[90me\x1B[39m\x1B[18G\x1B[0Ke}', '\x1B[90m{ a: true }\x1B[39m\x1B[20G\x1B[1A\x1B[1B\x1B[2K\x1B[1A;', '\x1B[90mtrue\x1B[39m\x1B[21G\x1B[1A\x1B[1B\x1B[2K\x1B[1A\r', '\x1B[33mtrue\x1B[39m' ] }, { input: '1n + 2n', noPreview: '\x1B[33m3n\x1B[39m', preview: [ '1n + 2', '\x1B[90mType[39m\x1B[14G\x1B[1A\x1B[1B\x1B[2K\x1B[1An', '\x1B[90m3n\x1B[39m\x1B[15G\x1B[1A\x1B[1B\x1B[2K\x1B[1A\r', '\x1B[33m3n\x1B[39m' ] }, { input: '{};1', noPreview: '\x1B[33m1\x1B[39m', preview: [ '{};1', '\x1B[90m1\x1B[39m\x1B[12G\x1B[1A\x1B[1B\x1B[2K\x1B[1A\r', '\x1B[33m1\x1B[39m' ] }]; const hasPreview = repl.terminal && (options.preview !== undefined ? !!options.preview : true); for (const { input, noPreview, preview } of testCases) { console.log(`Testing ${input}`); const toBeRun = input.split('\n'); let lines = await runAndWait(toBeRun, repl); if (hasPreview) { // Remove error messages. That allows the code to run in different // engines. // eslint-disable-next-line no-control-regex lines = lines.map((line) => line.replace(/Error: .+?\x1B/, '')); assert.strictEqual(lines.pop(), '\x1B[1G\x1B[0Jrepl > \x1B[8G'); assert.deepStrictEqual(lines, preview); } else { assert.ok(lines[0].includes(noPreview), lines.map(inspect)); if (preview.length !== 1 || preview[0] !== `${input}\r`) assert.strictEqual(lines.length, 2); } } } tests({ terminal: false }); // No preview tests({ terminal: true }); // Preview tests({ terminal: false, preview: false }); // No preview tests({ terminal: false, preview: true }); // No preview tests({ terminal: true, preview: true }); // Preview
var path = require('path'); var fs = require('fs'); var url = require('url'); var _ = require('lodash'); module.exports = function (settings) { return function (req, res, next) { settings.load(parseHostname(req), function (err, config) { if (err) return next(); if (!config) config = {}; req.config = config || {config: {}}; req.config.index = config.index || 'index.html'; // // Why aren't these stored in the cache? // // FIXME: these cause the tests to fail _.extend(req.config, req.config.config); if (!req.config) req.config = {}; next(); }); }; function parseHostname (req) { var protocol = (req.connection.encrypted) ? 'https://' : 'http://'; var urlObj = url.parse(protocol + req.headers.host); return urlObj.hostname; } };
(function( $, sinon, undefined ) { "use strict"; module( "Methods", { setup: function() { this.select = $( "#select-1" ).bselect({ animationDuration: 0 }); this.bselect = this.select.bselect( "element" ); }, teardown: function() { this.select.bselect( "destroy" ); } }); test( "element", 1, function() { ok( this.bselect.is( ".bselect" ), "returns bselect container" ); }); test( "option", 4, function() { var option = this.select.bselect( "option" ); ok( $.isPlainObject( option ), "returns hash with all options when no option defined" ); notStrictEqual( option.minSearchInput, undefined, "default option keys are present in the options hash" ); option = this.select.bselect( "option", "minSearchInput", 2 ); ok( option.is( this.select ), "after setting an option, returns self" ); option = this.select.bselect( "option", "minSearchInput" ); strictEqual( option, 2, "get the current option value" ); }); test( "select", 6, function() { var spy, select, li; spy = sinon.spy(); this.select.change( spy ); select = this.select.bselect( "select", 2 ); li = this.bselect.find( "li" ).eq( 2 ); ok( select.is( this.select ), "returns the select element" ); ok( li.is( ".active" ), "the LI index 2 must be .active" ); strictEqual( select.val(), li.data( "value" ), "the original select should have the same value as the option selected (issue #3)" ); strictEqual( li.attr( "aria-selected" ), "true", "the LI should get aria-selected='true'" ); this.select.bselect( "select", 4 ); ok( li.is( ".active" ), "if the index is not found, shouldn't do anything" ); ok( spy.calledOnce, "should trigger 'change' event of the select element" ); }); test( "show", 4, function() { var select = this.select.bselect( "show" ); var input = this.bselect.find( ".bselect-search-input" ); ok( select.is( this.select ), "returns the select element" ); ok( this.bselect.is( ".open" ), "must be .open" ); ok( this.bselect.find( ".bselect-dropdown" ).is( ":visible" ), "the list of items should get visible" ); strictEqual( input.attr( "aria-expanded" ), "true", "the search input must get aria-expanded='true'" ); }); test( "hide", 4, function() { this.select.show(); var select = this.select.bselect( "hide" ); ok( select.is( this.select ), "returns the select element" ); ok( !this.bselect.is( ".open" ), "must not be .open" ); ok( this.bselect.find( ".bselect-dropdown" ).is( ":hidden" ), "the list of items should get hidden" ); strictEqual( this.bselect.find( ".bselect-search-input" ).attr( "aria-expanded" ), "false", "the search input must get aria-expanded='false'" ); }); test( "toggle", 3, function() { var select = this.select.bselect( "toggle" ); ok( select.is( this.select ), "returns the select element" ); ok( this.bselect.find( ".bselect-dropdown" ).is( ":visible" ), "'show' must be called when hidden" ); select.bselect( "toggle" ); ok( this.bselect.find( ".bselect-dropdown" ).is( ":hidden" ), "'hide' must be called when visible" ); }); test( "search", 5, function() { var select = this.select.bselect( "search", "1" ); var LI = this.bselect.find( ".bselect-dropdown" ).show().find( "li" ); ok( select.is( this.select ), "returns the select element" ); strictEqual( LI.filter( ":visible" ).length, 1, "shows only the items with the searched term" ); // In the HTML, the <option> tags contain text like "Option 1". this.select.bselect( "search", "option" ); strictEqual( LI.filter( ":visible" ).length, 3, "search is case insensitive" ); this.select.bselect( "search", "" ); strictEqual( LI.filter( ":visible" ).length, 3, "clears the search when no input given" ); this.select.bselect( "search", "blablabla" ); ok( this.bselect.find( ".bselect-message" ).is( ":visible" ), "should show a message telling that no results were returned (issue #7)" ); }); test( "clearSearch", 3, function() { var select = this.select.bselect( "search", "1" ).bselect( "clearSearch" ), bselect = this.select.bselect( "element" ); bselect.find( ".bselect-dropdown" ).show(); ok( select.is( this.select ), "returns the select element" ); strictEqual( bselect.find( ".bselect-search-input" ).val(), "", "the search text must have no value" ); strictEqual( bselect.find( "li:visible" ).length, 3, "all items must be visible" ); }); test( "refresh", 2, function() { var options, select; options = this.select.find( "option[value!='']" ); options.eq( 0 ).remove(); select = this.select.bselect( "refresh" ); ok( select.is( this.select ), "returns the select element" ); strictEqual( this.bselect.find( ".bselect-option" ).length, options.length - 1, "the modifications in the select must be applied in the dropdown" ); }); test( "disable", 3, function() { var select = this.select.bselect( "disable" ); ok( select.is( this.select ), "returns the select element" ); ok( select.prop( "disabled" ), "the select has disabled attribute as true" ); ok( this.bselect.is( ".disabled" ), "should be .disabled" ); }); test( "enable", 3, function() { var select = this.select.bselect( "disable" ).bselect( "enable" ); ok( select.is( this.select ), "returns the select element" ); ok( !select.prop( "disabled" ), "the select has disabled attribute as false" ); ok( !this.bselect.is( ".disabled" ), "should not be .disabled" ); }); test( "destroy", 4, function() { var select = this.select.bselect( "destroy" ); ok( select.is( this.select ), "returns the select element" ); equal( select.data( "bselect" ), null, "has no bselect data" ); ok( select.is( ":visible" ), "is shown after destroying" ); strictEqual( this.bselect.has( "body" ).length, 0, "has no .bselect related element" ); }); })( jQuery, sinon );
webix.protoUI({ name:"ckeditor", $init:function(config){ this.$view.className += " webix_selectable"; }, defaults:{ borderless:true, toolbar: [ [ 'Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink' ], [ 'FontSize', 'TextColor', 'BGColor' ] ] }, _init_ckeditor_once:function(){ var tid = this.config.textAreaID = "t"+webix.uid(); this.$view.innerHTML = "<textarea id='"+tid+"'>"+this.config.value+"</textarea>"; window.CKEDITOR_BASEPATH = webix.codebase+"ckeditor/"; var t = { toolbar: this.config.toolbar, width:this.$width -2, height:this.$height - 44 }; webix.extend(t,this.config.editor||{}); webix.require("ckeditor/ckeditor.js", function(){ this._3rd_editor = CKEDITOR.replace( this.config.textAreaID, t); }, this); }, _set_inner_size:function(x, y){ if (!this._3rd_editor || !this._3rd_editor.container || !this.$width) return; this._3rd_editor.resize(x, y); }, $setSize:function(x,y){ if (webix.ui.view.prototype.$setSize.call(this, x, y)){ this._init_ckeditor_once(); this._set_inner_size(x,y); } }, setValue:function(value){ this.config.value = value; if (this._3rd_editor) this._3rd_editor.setData(value); else webix.delay(function(){ this.setValue(value); },this,[],100); }, getValue:function(){ return this._3rd_editor?this._3rd_editor.getData():this.config.value; }, focus:function(){ this._focus_await = true; if (this._3rd_editor) this._3rd_editor.focus(); }, getEditor:function(){ return this._3rd_editor.getData(); } }, webix.ui.view);
Template['clients'].helpers({ 'clients': function() { return Clients.find(); } });
import { Class } from '../mixin/index'; import { $, Animation, isNumeric, isString, query, requestAnimationFrame, win } from '../util/index'; export default function (UIkit) { UIkit.component('sticky', { mixins: [Class], props: { top: null, bottom: Boolean, offset: Number, animation: String, clsActive: String, clsInactive: String, widthElement: 'jQuery', showOnUp: Boolean, media: 'media', target: Number }, defaults: { top: 0, bottom: false, offset: 0, animation: '', clsActive: 'uk-active', clsInactive: '', widthElement: false, showOnUp: false, media: false, target: false }, init() { this.$el.addClass(this.clsInactive); }, connected() { this.placeholder = $('<div class="uk-sticky-placeholder"></div>').insertAfter(this.$el).attr('hidden', true); this._widthElement = this.widthElement || this.placeholder; }, ready() { this.topProp = this.top; this.bottomProp = this.bottom; if (this.target && location.hash && win.scrollTop() > 0) { var target = query(location.hash); if (target) { requestAnimationFrame(() => { var top = target.offset().top, elTop = this.$el.offset().top, elHeight = this.$el.outerHeight(), elBottom = elTop + elHeight; if (elBottom >= top && elTop <= top + target.outerHeight()) { window.scrollTo(0, top - elHeight - this.target - this.offset); } }); } } }, update: [ { write() { var outerHeight = this.$el.outerHeight(), isActive = this.isActive(), el; this.placeholder .css('height', this.$el.css('position') !== 'absolute' ? outerHeight : '') .css(this.$el.css(['marginTop', 'marginBottom', 'marginLeft', 'marginRight'])); this.width = this._widthElement.attr('hidden', null).outerWidth(); this._widthElement.attr('hidden', !isActive); this.topOffset = (isActive ? this.placeholder.offset() : this.$el.offset()).top; this.bottomOffset = this.topOffset + outerHeight; ['top', 'bottom'].forEach(prop => { this[prop] = this[`${prop}Prop`]; if (!this[prop]) { return; } if (isNumeric(this[prop])) { this[prop] = this[`${prop}Offset`] + parseFloat(this[prop]); } else { if (isString(this[prop]) && this[prop].match(/^-?\d+vh$/)) { this[prop] = window.innerHeight * parseFloat(this[prop]) / 100; } else { el = this[prop] === true ? this.$el.parent() : query(this[prop], this.$el); if (el) { this[prop] = el.offset().top + el.outerHeight(); } } } }); this.top = Math.max(parseFloat(this.top), this.topOffset) - this.offset; this.bottom = this.bottom && this.bottom - outerHeight; this.inactive = this.media && !window.matchMedia(this.media).matches; if (isActive) { this.update(); } }, events: ['load', 'resize', 'orientationchange'] }, { write({dir} = {}) { var isActive = this.isActive(), scroll = win.scrollTop(); if (scroll < 0 || !this.$el.is(':visible') || this.disabled) { return; } if (this.inactive || scroll < this.top || this.showOnUp && (dir !== 'up' || dir === 'up' && !isActive && scroll <= this.bottomOffset) ) { if (!isActive) { return; } isActive = false; if (this.animation && this.bottomOffset < this.$el.offset().top) { Animation.cancel(this.$el).then(() => Animation.out(this.$el, this.animation).then(() => this.hide())); } else { this.hide(); } } else if (isActive) { this.update(); } else if (this.animation) { Animation.cancel(this.$el).then(() => { this.show(); Animation.in(this.$el, this.animation); }); } else { this.show(); } }, events: ['scroll'] }, ], methods: { show() { this.update(); this.$el .removeClass(this.clsInactive) .addClass(this.clsActive) .trigger('active'); this.placeholder.attr('hidden', null); }, hide() { this.$el .addClass(this.clsInactive) .removeClass(this.clsActive) .css({position: '', top: '', width: ''}) .trigger('inactive'); this.placeholder.attr('hidden', true); }, update() { var top = Math.max(0, this.offset), scroll = win.scrollTop(); if (this.bottom && scroll > this.bottom - this.offset) { top = this.bottom - scroll; } this.$el.css({ position: 'fixed', top: `${top}px`, width: this.width }); }, isActive() { return this.$el.hasClass(this.clsActive) && !(this.animation && this.$el.hasClass('uk-animation-leave')); } }, disconnected() { this.placeholder.remove(); this.placeholder = null; this._widthElement = null; } }); }
var ObserveOnObservable = (function (__super__) { inherits(ObserveOnObservable, __super__); function ObserveOnObservable(source, s) { this.source = source; this._s = s; __super__.call(this); } ObserveOnObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new ObserveOnObserver(this._s, o)); }; return ObserveOnObservable; }(ObservableBase)); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { return new ObserveOnObservable(this, scheduler); };
var searchData= [ ['quadcol_2ecpp',['QuadCol.cpp',['../_quad_col_8cpp.html',1,'']]], ['quadcol_2eh',['QuadCol.h',['../_quad_col_8h.html',1,'']]] ];
/* Simple JQuery menu. HTML structure to use: Notes: Each menu MUST have a class 'menu' set. If the menu doesn't have this, the JS won't make it dynamic If you want a panel to be expanded at page load, give the containing LI element the classname 'expand'. Use this to set the right state in your page (generation) code. Optional extra classnames for the UL element that holds an accordion: noaccordion : no accordion functionality collapsible : menu works like an accordion but can be fully collapsed <ul class="menu [optional class] [optional class]"> <li><a href="#">Sub menu heading</a> <ul> <li><a href="http://site.com/">Link</a></li> <li><a href="http://site.com/">Link</a></li> <li><a href="http://site.com/">Link</a></li> ... ... </ul> // This item is open at page load time <li class="expand"><a href="#">Sub menu heading</a> <ul> <li><a href="http://site.com/">Link</a></li> <li><a href="http://site.com/">Link</a></li> <li><a href="http://site.com/">Link</a></li> ... ... </ul> ... ... </ul> Copyright 2007-2010 by Marco van Hylckama Vlieg web: http://www.i-marco.nl/weblog/ email: marco@i-marco.nl Free to use any way you like. */ jQuery.fn.initMenu = function() { return this.each(function() { var theMenu = $(this).get(0); $('li.expand > .acitem', this).prev().addClass('active'); $('.acitem', this).hide(); $('li.expand > .acitem', this).hide(); $('li a', this).click( function(e) { e.stopImmediatePropagation(); var theElement = $(this).next(); var parent = this.parentNode.parentNode; if ($(parent).hasClass('noaccordion')) { if (theElement[0] === undefined) { window.location.href = this.href; } $(theElement).slideToggle('normal', function() { if ($(this).is(':visible')) { $(this).prev().addClass('active'); } else { $(this).prev().removeClass('active'); } }); return false; } else { if (theElement.hasClass('acitem') && theElement.is(':visible')) { //if($(parent).hasClass('collapsible')) { $('.acitem:visible', parent).first().slideUp('fast', function() { $(this).prev().removeClass('active'); } ); //return false; // } return false; } if (theElement.hasClass('acitem') && !theElement.is(':visible')) { $('.acitem:visible', parent).first().slideUp('normal', function() { $(this).prev().removeClass('active'); }); theElement.prev().addClass('active'); theElement.slideDown('normal', function() { // $(this).prev().addClass('active'); }); return false; } } } ); }); };
'use strict'; var Lib = require('../../lib'); var constants = require('./constants'); var isNumeric = require('fast-isnumeric'); var Axes = require('../../plots/cartesian/axes'); var maxRowLength = require('../../lib').maxRowLength; var getImageSize = require('./helpers').getImageSize; module.exports = function calc(gd, trace) { var h; var w; if(trace._hasZ) { h = trace.z.length; w = maxRowLength(trace.z); } else if(trace._hasSource) { var size = getImageSize(trace.source); h = size.height; w = size.width; } var xa = Axes.getFromId(gd, trace.xaxis || 'x'); var ya = Axes.getFromId(gd, trace.yaxis || 'y'); var x0 = xa.d2c(trace.x0) - trace.dx / 2; var y0 = ya.d2c(trace.y0) - trace.dy / 2; // Set axis range var i; var xrange = [x0, x0 + w * trace.dx]; var yrange = [y0, y0 + h * trace.dy]; if(xa && xa.type === 'log') for(i = 0; i < w; i++) xrange.push(x0 + i * trace.dx); if(ya && ya.type === 'log') for(i = 0; i < h; i++) yrange.push(y0 + i * trace.dy); trace._extremes[xa._id] = Axes.findExtremes(xa, xrange); trace._extremes[ya._id] = Axes.findExtremes(ya, yrange); trace._scaler = makeScaler(trace); var cd0 = { x0: x0, y0: y0, z: trace.z, w: w, h: h }; return [cd0]; }; function scale(zero, ratio, min, max) { return function(c) { return Lib.constrain((c - zero) * ratio, min, max); }; } function constrain(min, max) { return function(c) { return Lib.constrain(c, min, max);}; } // Generate a function to scale color components according to zmin/zmax and the colormodel function makeScaler(trace) { var cr = constants.colormodel[trace.colormodel]; var colormodel = (cr.colormodel || trace.colormodel); var n = colormodel.length; trace._sArray = []; // Loop over all color components for(var k = 0; k < n; k++) { if(cr.min[k] !== trace.zmin[k] || cr.max[k] !== trace.zmax[k]) { trace._sArray.push(scale( trace.zmin[k], (cr.max[k] - cr.min[k]) / (trace.zmax[k] - trace.zmin[k]), cr.min[k], cr.max[k] )); } else { trace._sArray.push(constrain(cr.min[k], cr.max[k])); } } return function(pixel) { var c = pixel.slice(0, n); for(var k = 0; k < n; k++) { var ck = c[k]; if(!isNumeric(ck)) return false; c[k] = trace._sArray[k](ck); } return c; }; }
const root = __dirname + '/../../../..'; require('@babel/register')({ root, cwd: root, configFile: root + '/packages/server/babel.config.js', extensions: ['.js', '.jsx', '.ts', '.tsx'], cache: false }); require.extensions['.scss'] = () => {}; require.extensions['.css'] = () => {}; require.extensions['.less'] = () => {}; Object.assign(global, require('../../jest.config').globals); const { setup } = require('@gqlapp/testing-server-ts'); require('..'); module.exports = setup;
const dashboards = require('../lib/dashboards.js'); const helper = require('../lib/helper.js'); const config = require('config'); var program = require('commander'); // Print out the URL of the newly created dashboard var handleCreate = function(error, response, body) { var rspBody = helper.handleCB(error, response, body); if (rspBody != null) { var destId = config.get(program.dest).accountId; var url = 'http://insights.newrelic.com/accounts/' + destId + '/dashboards/' + rspBody.dashboard.id; console.log('Dashboard created: ' + url); } } // Read the source dashboard var readDash = function(error, response, body) { var dashboardBody = helper.handleCB(error, response, body); if (dashboardBody != null) { console.log('Found source dashboard named: ' + dashboardBody.dashboard.title); var srcId = config.get(program.src).accountId; var destId = config.get(program.dest).accountId; var newBody = dashboards.updateAccountId(dashboardBody, srcId, destId); console.log(newBody); dashboards.create(newBody, program.dest, handleCreate); } } // Setup the commander program program .version('0.0.1') .option('--src [account]', 'Source account that has the dashboard to be copied') .option('--dash [dashboardId]', 'Id of the dashboard to be copied') .option('--dest [account]', 'Destination account to copy the dashboard to') .parse(process.argv); if (!process.argv.slice(7).length) { program.outputHelp(); } else { // Make sure [from] is in the config if (!config.has(program.src)) { console.error('Your config does not have *src* account: ' + program.src, 'check your NODE_ENV=', process.env.NODE_ENV); } else if (!config.has(program.dest)) { console.error('Your config does not have *dest* account: ' + program.dest, 'check your NODE_ENV=', process.env.NODE_ENV); } else { // We have good data so try to read the dashboard console.log('Trying to find dashboard: ' + program.dash); dashboards.getOne(program.dash, program.src, readDash); } }
import _ from 'underscore'; import s from 'underscore.string'; import moment from 'moment'; /** * Chechs if a messages contains a user highlight * * @param {string} message * @param {array|undefined} highlights * * @returns {boolean} */ export function messageContainsHighlight(message, highlights) { if (! highlights || highlights.length === 0) { return false; } return highlights.some(function(highlight) { const regexp = new RegExp(s.escapeRegExp(highlight), 'i'); return regexp.test(message.msg); }); } function notifyUsersOnMessage(message, room) { // skips this callback if the message was edited and increments it if the edit was way in the past (aka imported) if (message.editedAt && Math.abs(moment(message.editedAt).diff()) > 60000) { // TODO: Review as I am not sure how else to get around this as the incrementing of the msgs count shouldn't be in this callback RocketChat.models.Rooms.incMsgCountById(message.rid, 1); return message; } else if (message.editedAt) { // only updates last message if it was edited (skip rest of callback) if (RocketChat.settings.get('Store_Last_Message') && (!room.lastMessage || room.lastMessage._id === message._id)) { RocketChat.models.Rooms.setLastMessageById(message.rid, message); } return message; } if (message.ts && Math.abs(moment(message.ts).diff()) > 60000) { RocketChat.models.Rooms.incMsgCountById(message.rid, 1); return message; } if (room != null) { let toAll = false; let toHere = false; const mentionIds = []; const highlightsIds = []; const highlights = RocketChat.models.Subscriptions.findByRoomWithUserHighlights(room._id, { fields: { userHighlights: 1, 'u._id': 1 } }).fetch(); if (message.mentions != null) { message.mentions.forEach(function(mention) { if (!toAll && mention._id === 'all') { toAll = true; } if (!toHere && mention._id === 'here') { toHere = true; } if (mention._id !== message.u._id) { mentionIds.push(mention._id); } }); } highlights.forEach(function(subscription) { if (subscription.userHighlights && messageContainsHighlight(message, subscription.userHighlights)) { if (subscription.u._id !== message.u._id) { highlightsIds.push(subscription.u._id); } } }); if (room.t === 'd') { const unreadCountDM = RocketChat.settings.get('Unread_Count_DM'); if (unreadCountDM === 'all_messages') { RocketChat.models.Subscriptions.incUnreadForRoomIdExcludingUserId(room._id, message.u._id); } else if (toAll || toHere) { RocketChat.models.Subscriptions.incGroupMentionsAndUnreadForRoomIdExcludingUserId(room._id, message.u._id, 1, 1); } else if ((mentionIds && mentionIds.length > 0) || (highlightsIds && highlightsIds.length > 0)) { RocketChat.models.Subscriptions.incUserMentionsAndUnreadForRoomIdAndUserIds(room._id, _.compact(_.unique(mentionIds.concat(highlightsIds))), 1, 1); } } else { const unreadCount = RocketChat.settings.get('Unread_Count'); if (toAll || toHere) { let incUnread = 0; if (['all_messages', 'group_mentions_only', 'user_and_group_mentions_only'].includes(unreadCount)) { incUnread = 1; } RocketChat.models.Subscriptions.incGroupMentionsAndUnreadForRoomIdExcludingUserId(room._id, message.u._id, 1, incUnread); } else if ((mentionIds && mentionIds.length > 0) || (highlightsIds && highlightsIds.length > 0)) { let incUnread = 0; if (['all_messages', 'user_mentions_only', 'user_and_group_mentions_only'].includes(unreadCount)) { incUnread = 1; } RocketChat.models.Subscriptions.incUserMentionsAndUnreadForRoomIdAndUserIds(room._id, _.compact(_.unique(mentionIds.concat(highlightsIds))), 1, incUnread); } else if (unreadCount === 'all_messages') { RocketChat.models.Subscriptions.incUnreadForRoomIdExcludingUserId(room._id, message.u._id); } } } // Update all the room activity tracker fields // This method take so long to execute on gient rooms cuz it will trugger the cache rebuild for the releations of that room RocketChat.models.Rooms.incMsgCountAndSetLastMessageById(message.rid, 1, message.ts, RocketChat.settings.get('Store_Last_Message') && message); // Update all other subscriptions to alert their owners but witout incrementing // the unread counter, as it is only for mentions and direct messages // We now set alert and open properties in two separate update commands. This proved to be more efficient on MongoDB - because it uses a more efficient index. RocketChat.models.Subscriptions.setAlertForRoomIdExcludingUserId(message.rid, message.u._id); RocketChat.models.Subscriptions.setOpenForRoomIdExcludingUserId(message.rid, message.u._id); return message; } RocketChat.callbacks.add('afterSaveMessage', notifyUsersOnMessage, RocketChat.callbacks.priority.LOW, 'notifyUsersOnMessage');
'use strict'; /** * idbRequest * ----------------------------------------------------------------------------- * [Exposed=(Window,Worker)] * interface IDBRequest : EventTarget { * readonly attribute any result; * readonly attribute DOMException? error; * readonly attribute (IDBObjectStore or IDBIndex or IDBCursor)? source; * readonly attribute IDBTransaction? transaction; * readonly attribute IDBRequestReadyState readyState; * * // Event handlers: * attribute EventHandler onsuccess; * attribute EventHandler onerror; * }; * * enum IDBRequestReadyState { * "pending", * "done" * }; */ export default function (Clazzer) { 'ngInject'; // --------------------------------------------------------------------------- // Atributos falntantes por definir // $_promise const ReadyState = new Clazzer({}) .static('Pending', 'pending') .static('Done', 'done'); return new // --------------------------------------------------------------------------- // Constructor Clazzer(function idbRequest (me) { new Clazzer(this).static('$me', me); }) // --------------------------------------------------------------------------- // Herencia .inherit(EventTarget) // --------------------------------------------------------------------------- // Statics .static('ReadyState', ReadyState.clazz) // --------------------------------------------------------------------------- // Getters .getter('$result', 'result') .getter('$error', 'error') .getter('$source', 'source') .getter('$readyState', 'readyState') .getter('$transaction', 'transaction') // --------------------------------------------------------------------------- // Event handlers .handlerEvent('$success', 'onsuccess') .handlerEvent('$failed', 'onerror') // --------------------------------------------------------------------------- // Property .property('$promise', { get: function() { const thiz = this; if (thiz.$_promise) return thiz.$_promise; // Crear promise para el request thiz.$_promise = new Promise(function (resolve, reject) { thiz.$success(function (event) { resolve(event); }) .$failed(function (event) { reject(event); }); }); new Clazzer(thiz.$_promise).static('$request', thiz ); return thiz.$_promise; } }) // --------------------------------------------------------------------------- .clazz; }
import { Mixin } from 'ember-metal/mixin'; import create from 'ember-metal/platform/create'; import { meta } from 'ember-metal/utils'; import { on, addListener, removeListener, suspendListener, suspendListeners, sendEvent, hasListeners } from "ember-metal/events"; QUnit.module('system/props/events_test'); test('listener should receive event - removing should remove', function() { var obj = {}; var count = 0; var F = function() { count++; }; addListener(obj, 'event!', F); equal(count, 0, 'nothing yet'); sendEvent(obj, 'event!'); equal(count, 1, 'received event'); removeListener(obj, 'event!', F); count = 0; sendEvent(obj, 'event!'); equal(count, 0, 'received event'); }); test('listeners should be inherited', function() { var obj = {}; var count = 0; var F = function() { count++; }; addListener(obj, 'event!', F); var obj2 = create(obj); equal(count, 0, 'nothing yet'); sendEvent(obj2, 'event!'); equal(count, 1, 'received event'); removeListener(obj2, 'event!', F); count = 0; sendEvent(obj2, 'event!'); equal(count, 0, 'did not receive event'); sendEvent(obj, 'event!'); equal(count, 1, 'should still invoke on parent'); }); test('adding a listener more than once should only invoke once', function() { var obj = {}; var count = 0; var F = function() { count++; }; addListener(obj, 'event!', F); addListener(obj, 'event!', F); sendEvent(obj, 'event!'); equal(count, 1, 'should only invoke once'); }); test('adding a listener with a target should invoke with target', function() { var obj = {}; var target; target = { count: 0, method: function() { this.count++; } }; addListener(obj, 'event!', target, target.method); sendEvent(obj, 'event!'); equal(target.count, 1, 'should invoke'); }); test('suspending a listener should not invoke during callback', function() { var obj = {}; var target, otherTarget; target = { count: 0, method: function() { this.count++; } }; otherTarget = { count: 0, method: function() { this.count++; } }; addListener(obj, 'event!', target, target.method); addListener(obj, 'event!', otherTarget, otherTarget.method); function callback() { /*jshint validthis:true */ equal(this, target); sendEvent(obj, 'event!'); return 'result'; } sendEvent(obj, 'event!'); equal(suspendListener(obj, 'event!', target, target.method, callback), 'result'); sendEvent(obj, 'event!'); equal(target.count, 2, 'should invoke'); equal(otherTarget.count, 3, 'should invoke'); }); test('adding a listener with string method should lookup method on event delivery', function() { var obj = {}; var target; target = { count: 0, method: function() {} }; addListener(obj, 'event!', target, 'method'); sendEvent(obj, 'event!'); equal(target.count, 0, 'should invoke but do nothing'); target.method = function() { this.count++; }; sendEvent(obj, 'event!'); equal(target.count, 1, 'should invoke now'); }); test('calling sendEvent with extra params should be passed to listeners', function() { var obj = {}; var params = null; addListener(obj, 'event!', function() { params = Array.prototype.slice.call(arguments); }); sendEvent(obj, 'event!', ['foo', 'bar']); deepEqual(params, ['foo', 'bar'], 'params should be saved'); }); test('implementing sendEvent on object should invoke', function() { var obj = { sendEvent: function(eventName, params) { equal(eventName, 'event!', 'eventName'); deepEqual(params, ['foo', 'bar']); this.count++; }, count: 0 }; addListener(obj, 'event!', obj, function() { this.count++; }); sendEvent(obj, 'event!', ['foo', 'bar']); equal(obj.count, 2, 'should have invoked method & listener'); }); test('hasListeners tells you if there are listeners for a given event', function() { var obj = {}; var F = function() {}; var F2 = function() {}; equal(hasListeners(obj, 'event!'), false, 'no listeners at first'); addListener(obj, 'event!', F); addListener(obj, 'event!', F2); equal(hasListeners(obj, 'event!'), true, 'has listeners'); removeListener(obj, 'event!', F); equal(hasListeners(obj, 'event!'), true, 'has listeners'); removeListener(obj, 'event!', F2); equal(hasListeners(obj, 'event!'), false, 'has no more listeners'); addListener(obj, 'event!', F); equal(hasListeners(obj, 'event!'), true, 'has listeners'); }); test('calling removeListener without method should remove all listeners', function() { var obj = {}; var F = function() {}; var F2 = function() {}; equal(hasListeners(obj, 'event!'), false, 'no listeners at first'); addListener(obj, 'event!', F); addListener(obj, 'event!', F2); equal(hasListeners(obj, 'event!'), true, 'has listeners'); removeListener(obj, 'event!'); equal(hasListeners(obj, 'event!'), false, 'has no more listeners'); }); test('while suspended, it should not be possible to add a duplicate listener', function() { var obj = {}; var target; target = { count: 0, method: function() { this.count++; } }; addListener(obj, 'event!', target, target.method); function callback() { addListener(obj, 'event!', target, target.method); } sendEvent(obj, 'event!'); suspendListener(obj, 'event!', target, target.method, callback); equal(target.count, 1, 'should invoke'); equal(meta(obj).listeners['event!'].length, 3, "a duplicate listener wasn't added"); // now test suspendListeners... sendEvent(obj, 'event!'); suspendListeners(obj, ['event!'], target, target.method, callback); equal(target.count, 2, 'should have invoked again'); equal(meta(obj).listeners['event!'].length, 3, "a duplicate listener wasn't added"); }); test('a listener can be added as part of a mixin', function() { var triggered = 0; var MyMixin = Mixin.create({ foo1: on('bar', function() { triggered++; }), foo2: on('bar', function() { triggered++; }) }); var obj = {}; MyMixin.apply(obj); sendEvent(obj, 'bar'); equal(triggered, 2, 'should invoke listeners'); }); test('a listener added as part of a mixin may be overridden', function() { var triggered = 0; var FirstMixin = Mixin.create({ foo: on('bar', function() { triggered++; }) }); var SecondMixin = Mixin.create({ foo: on('baz', function() { triggered++; }) }); var obj = {}; FirstMixin.apply(obj); SecondMixin.apply(obj); sendEvent(obj, 'bar'); equal(triggered, 0, 'should not invoke from overriden property'); sendEvent(obj, 'baz'); equal(triggered, 1, 'should invoke from subclass property'); });